From 7c00af18febf6c0b833c7633b4fb60a9a1bb93af Mon Sep 17 00:00:00 2001 From: IRONM00N <64110067+IRONM00N@users.noreply.github.com> Date: Sat, 16 Oct 2021 15:50:41 -0400 Subject: Code Clean Up (#2) * intellij code clean up * optimize imports * format * intellij suggestions * fix empty catch issues --- .../moulberry/notenoughupdates/CustomItems.java | 38 +- .../notenoughupdates/ItemPriceInformation.java | 169 +- .../github/moulberry/notenoughupdates/NEUApi.java | 3 +- .../notenoughupdates/NEUEventListener.java | 1117 +++++------ .../moulberry/notenoughupdates/NEUManager.java | 541 ++--- .../moulberry/notenoughupdates/NEUOverlay.java | 1136 +++++------ .../notenoughupdates/NotEnoughUpdates.java | 141 +- .../notenoughupdates/auction/APIManager.java | 398 ++-- .../notenoughupdates/auction/CustomAH.java | 82 +- .../notenoughupdates/auction/CustomAHGui.java | 1 - .../collectionlog/GuiCollectionLog.java | 50 +- .../commands/ClientCommandBase.java | 2 +- .../notenoughupdates/commands/Commands.java | 427 ++-- .../notenoughupdates/commands/SimpleCommand.java | 7 +- .../notenoughupdates/commands/StatsCommand.java | 16 +- .../notenoughupdates/core/BackgroundBlur.java | 95 +- .../notenoughupdates/core/ChromaColour.java | 19 +- .../notenoughupdates/core/GlScissorStack.java | 20 +- .../notenoughupdates/core/GuiElement.java | 4 +- .../notenoughupdates/core/GuiElementBoolean.java | 48 +- .../notenoughupdates/core/GuiElementColour.java | 245 ++- .../notenoughupdates/core/GuiElementTextField.java | 317 +-- .../notenoughupdates/core/config/Config.java | 3 +- .../core/config/GuiPositionEditor.java | 18 +- .../core/config/KeybindHelper.java | 25 +- .../notenoughupdates/core/config/Position.java | 108 +- .../notenoughupdates/core/config/PositionNew.java | 36 +- .../core/config/annotations/Category.java | 1 + .../config/annotations/ConfigEditorButton.java | 1 + .../config/annotations/ConfigEditorColour.java | 1 - .../config/annotations/ConfigEditorDropdown.java | 2 +- .../config/annotations/ConfigEditorSlider.java | 2 +- .../core/config/annotations/ConfigEditorText.java | 1 - .../core/config/annotations/ConfigOption.java | 3 +- .../core/config/gui/GuiOptionEditor.java | 22 +- .../core/config/gui/GuiOptionEditorAccordion.java | 26 +- .../core/config/gui/GuiOptionEditorBoolean.java | 10 +- .../core/config/gui/GuiOptionEditorButton.java | 21 +- .../core/config/gui/GuiOptionEditorColour.java | 30 +- .../config/gui/GuiOptionEditorDraggableList.java | 152 +- .../core/config/gui/GuiOptionEditorDropdown.java | 85 +- .../core/config/gui/GuiOptionEditorKeybind.java | 33 +- .../core/config/gui/GuiOptionEditorSlider.java | 60 +- .../core/config/gui/GuiOptionEditorText.java | 35 +- .../core/config/gui/GuiPositionEditor.java | 56 +- .../core/config/struct/ConfigProcessor.java | 63 +- .../core/util/GuiElementSlider.java | 58 +- .../notenoughupdates/core/util/MiscUtils.java | 31 +- .../notenoughupdates/core/util/Splitters.java | 1 - .../notenoughupdates/core/util/StringUtils.java | 10 +- .../notenoughupdates/core/util/lerp/LerpUtils.java | 10 +- .../core/util/lerp/LerpingFloat.java | 18 +- .../core/util/lerp/LerpingInteger.java | 16 +- .../core/util/render/RenderUtils.java | 146 +- .../core/util/render/TextRenderUtils.java | 32 +- .../notenoughupdates/cosmetics/CapeManager.java | 130 +- .../notenoughupdates/cosmetics/CapeNode.java | 112 +- .../notenoughupdates/cosmetics/GuiCosmetics.java | 282 ++- .../notenoughupdates/cosmetics/NEUCape.java | 356 ++-- .../notenoughupdates/cosmetics/ShaderManager.java | 53 +- .../notenoughupdates/dungeons/DungeonBlocks.java | 59 +- .../notenoughupdates/dungeons/DungeonMap.java | 747 +++---- .../notenoughupdates/dungeons/DungeonWin.java | 277 +-- .../dungeons/GuiDungeonMapEditor.java | 480 ++--- .../notenoughupdates/gamemodes/GuiGamemodes.java | 208 +- .../notenoughupdates/gamemodes/SBGamemodes.java | 163 +- .../infopanes/CollectionLogInfoPane.java | 208 +- .../notenoughupdates/infopanes/DevInfoPane.java | 322 +-- .../infopanes/FlipperInfoPane.java | 41 +- .../notenoughupdates/infopanes/HTMLInfoPane.java | 165 +- .../notenoughupdates/infopanes/InfoPane.java | 15 +- .../infopanes/ScrollableInfoPane.java | 10 +- .../notenoughupdates/infopanes/TextInfoPane.java | 26 +- .../notenoughupdates/itemeditor/GuiElement.java | 6 + .../itemeditor/GuiElementButton.java | 8 +- .../itemeditor/GuiElementText.java | 4 +- .../itemeditor/GuiElementTextField.java | 288 ++- .../notenoughupdates/itemeditor/NEUItemEditor.java | 173 +- .../notenoughupdates/mbgui/MBAnchorPoint.java | 6 +- .../notenoughupdates/mbgui/MBGuiElement.java | 5 + .../notenoughupdates/mbgui/MBGuiGroup.java | 19 +- .../notenoughupdates/mbgui/MBGuiGroupAligned.java | 24 +- .../notenoughupdates/mbgui/MBGuiGroupFloating.java | 50 +- .../miscfeatures/AuctionBINWarning.java | 102 +- .../miscfeatures/AuctionSortModeWarning.java | 26 +- .../miscfeatures/BetterContainers.java | 27 +- .../miscfeatures/CollectionLogManager.java | 20 +- .../miscfeatures/CrystalMetalDetectorSolver.java | 4 +- .../miscfeatures/CrystalOverlay.java | 161 +- .../miscfeatures/CustomItemEffects.java | 457 +++-- .../miscfeatures/CustomSkulls.java | 91 +- .../miscfeatures/DamageCommas.java | 80 +- .../miscfeatures/DwarvenMinesTextures.java | 232 ++- .../miscfeatures/DwarvenMinesWaypoints.java | 144 +- .../miscfeatures/EnchantingSolvers.java | 230 +-- .../notenoughupdates/miscfeatures/FairySouls.java | 114 +- .../miscfeatures/FancyPortals.java | 110 +- .../miscfeatures/FishingHelper.java | 228 +-- .../miscfeatures/ItemCooldowns.java | 100 +- .../miscfeatures/ItemCustomizeManager.java | 49 +- .../miscfeatures/ItemRarityHalo.java | 76 +- .../notenoughupdates/miscfeatures/MiningStuff.java | 98 +- .../miscfeatures/NPCRetexturing.java | 28 +- .../miscfeatures/NullzeeSphere.java | 98 +- .../miscfeatures/PetInfoOverlay.java | 487 ++--- .../notenoughupdates/miscfeatures/SlotLocking.java | 261 ++- .../miscfeatures/StorageManager.java | 285 +-- .../miscfeatures/StreamerMode.java | 13 +- .../notenoughupdates/miscfeatures/SunTzu.java | 25 +- .../miscgui/AccessoryBagOverlay.java | 549 +++--- .../notenoughupdates/miscgui/CalendarOverlay.java | 761 ++++---- .../notenoughupdates/miscgui/GuiCustomEnchant.java | 961 +++++---- .../notenoughupdates/miscgui/GuiEnchantColour.java | 243 ++- .../miscgui/GuiInvButtonEditor.java | 399 ++-- .../notenoughupdates/miscgui/GuiItemCustomize.java | 5 +- .../notenoughupdates/miscgui/GuiItemRecipe.java | 15 +- .../miscgui/InventoryStorageSelector.java | 249 +-- .../miscgui/NEUOverlayPlacements.java | 103 +- .../notenoughupdates/miscgui/StorageOverlay.java | 1220 ++++++------ .../notenoughupdates/miscgui/TradeWindow.java | 615 +++--- .../miscgui/tutorials/NeuTutorial.java | 152 +- .../miscgui/tutorials/TutorialBase.java | 97 +- .../mixins/MixinAbstractClientPlayer.java | 20 +- .../notenoughupdates/mixins/MixinContainer.java | 6 +- .../mixins/MixinEffectRenderer.java | 6 +- .../notenoughupdates/mixins/MixinEntityPlayer.java | 8 +- .../mixins/MixinEntityPlayerSP.java | 8 +- .../mixins/MixinEntityRenderer.java | 74 +- .../notenoughupdates/mixins/MixinGuiChest.java | 14 +- .../notenoughupdates/mixins/MixinGuiContainer.java | 116 +- .../notenoughupdates/mixins/MixinGuiIngame.java | 17 +- .../notenoughupdates/mixins/MixinGuiInventory.java | 4 +- .../notenoughupdates/mixins/MixinGuiScreen.java | 3 +- .../mixins/MixinInventoryEffectRenderer.java | 6 +- .../mixins/MixinInventoryPlayer.java | 9 +- .../mixins/MixinItemCameraTransforms.java | 2 +- .../notenoughupdates/mixins/MixinItemRenderer.java | 11 +- .../notenoughupdates/mixins/MixinItemStack.java | 23 +- .../mixins/MixinLayerArmorBase.java | 25 +- .../mixins/MixinLayerCustomHead.java | 12 +- .../mixins/MixinLoadingScreenRenderer.java | 6 +- .../notenoughupdates/mixins/MixinMinecraft.java | 29 +- .../notenoughupdates/mixins/MixinMouseHelper.java | 2 +- .../mixins/MixinNetHandlerPlayClient.java | 35 +- .../mixins/MixinPlayerControllerMP.java | 7 +- .../notenoughupdates/mixins/MixinRender.java | 8 +- .../notenoughupdates/mixins/MixinRenderFish.java | 53 +- .../notenoughupdates/mixins/MixinRenderGlobal.java | 44 +- .../notenoughupdates/mixins/MixinRenderItem.java | 92 +- .../notenoughupdates/mixins/MixinRenderList.java | 6 +- .../mixins/MixinRendererLivingEntity.java | 11 +- .../mixins/MixinTextureManager.java | 4 +- .../mixins/MixinTileEntitySkullRenderer.java | 5 +- .../mixins/MixinTileEntitySpecialRenderer.java | 10 +- .../mixins/MixinVboRenderList.java | 4 +- .../notenoughupdates/mixins/MixinWorld.java | 15 +- .../notenoughupdates/mixins/MixinWorldClient.java | 4 +- .../notenoughupdates/options/NEUConfig.java | 216 +- .../notenoughupdates/options/NEUConfigEditor.java | 526 ++--- .../options/seperateSections/Dungeons.java | 3 - .../options/seperateSections/Enchanting.java | 4 +- .../options/seperateSections/ItemOverlays.java | 6 +- .../options/seperateSections/Mining.java | 4 - .../options/seperateSections/Misc.java | 7 - .../options/seperateSections/MiscOverlays.java | 18 +- .../options/seperateSections/Notifications.java | 2 +- .../options/seperateSections/StorageGUI.java | 1 - .../options/seperateSections/Toolbar.java | 2 - .../options/seperateSections/TooltipTweaks.java | 2 - .../options/seperateSections/TradeMenu.java | 1 - .../overlays/AuctionSearchOverlay.java | 228 ++- .../overlays/BonemerangOverlay.java | 29 +- .../notenoughupdates/overlays/CraftingOverlay.java | 1 - .../notenoughupdates/overlays/FarmingOverlay.java | 128 +- .../notenoughupdates/overlays/FuelBar.java | 105 +- .../notenoughupdates/overlays/MiningOverlay.java | 176 +- .../notenoughupdates/overlays/OverlayManager.java | 26 +- .../overlays/RancherBootOverlay.java | 78 +- .../notenoughupdates/overlays/TextOverlay.java | 62 +- .../notenoughupdates/overlays/TimersOverlay.java | 201 +- .../profileviewer/GuiProfileViewer.java | 2059 ++++++++++---------- .../notenoughupdates/profileviewer/Panorama.java | 65 +- .../profileviewer/PlayerStats.java | 256 +-- .../profileviewer/ProfileViewer.java | 550 +++--- .../moulberry/notenoughupdates/util/Constants.java | 3 +- .../notenoughupdates/util/GuiTextures.java | 1 - .../notenoughupdates/util/HastebinUploader.java | 15 +- .../notenoughupdates/util/HypixelApi.java | 40 +- .../notenoughupdates/util/LerpingFloat.java | 18 +- .../notenoughupdates/util/NEUResourceManager.java | 3 +- .../notenoughupdates/util/ProfileApiSyncer.java | 24 +- .../util/RequestFocusListener.java | 49 +- .../util/ReverseWorldRenderer.java | 37 +- .../moulberry/notenoughupdates/util/SBInfo.java | 55 +- .../notenoughupdates/util/SpecialColour.java | 19 +- .../moulberry/notenoughupdates/util/TexLoc.java | 28 +- .../moulberry/notenoughupdates/util/Utils.java | 570 +++--- .../notenoughupdates/util/XPInformation.java | 88 +- 198 files changed, 12730 insertions(+), 12819 deletions(-) (limited to 'src/main/java/io') diff --git a/src/main/java/io/github/moulberry/notenoughupdates/CustomItems.java b/src/main/java/io/github/moulberry/notenoughupdates/CustomItems.java index c16cb7d0..7eefac6a 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/CustomItems.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/CustomItems.java @@ -31,7 +31,7 @@ public class CustomItems { "DUCTTAPE", "iron_shovel", "You ever accidentally bury your duct tape?", - "No problem! Our team of experts specialise in", + "No problem! Our team of experts specialise in", "subterranean duct tape excavation. That's right:", "your buried duct tape problems are a thing of the past,", "all for the low price of $7.99 or a subscription", @@ -44,24 +44,24 @@ public class CustomItems { public static JsonObject RUNE = create("RUNE", "paper", "No.", "I hate runes."); public static JsonObject TWOBEETWOTEE = create("2B2T", "bedrock", "Minecraft's oldest anarchy Minecraft server in Minecraft.", "This Minecraft anarchy server is the oldest server,", - "being a server since 2010 when Minecraft was a game with a server.", - "It is complete anarchy in Minecraft which means that there is total anarchy.", - "Hacking is allowed in Minecraft on this anarchy server which", - "is the oldest anarchy server in Minecraft, 2b2t. Hack. Steal. Cheat. Lie.", - "On the oldest anarchy server in Minecraft. 2b2t. The worst server in Minecraft,", - "where there are no rules. On the oldest anarchy server in Minecraft.", - "In this Minecraft anarchy server, there have been numerous Minecraft", - "incursions on the server, some of which I, a player on this Minecraft", - "anarchy server in Minecraft, have participated in. One of this server's", - "most infamous Minecraft players on the oldest Minecraft"); + "being a server since 2010 when Minecraft was a game with a server.", + "It is complete anarchy in Minecraft which means that there is total anarchy.", + "Hacking is allowed in Minecraft on this anarchy server which", + "is the oldest anarchy server in Minecraft, 2b2t. Hack. Steal. Cheat. Lie.", + "On the oldest anarchy server in Minecraft. 2b2t. The worst server in Minecraft,", + "where there are no rules. On the oldest anarchy server in Minecraft.", + "In this Minecraft anarchy server, there have been numerous Minecraft", + "incursions on the server, some of which I, a player on this Minecraft", + "anarchy server in Minecraft, have participated in. One of this server's", + "most infamous Minecraft players on the oldest Minecraft"); public static JsonObject LEOCTHL = create("LEOCTHL", "dragon_egg", "--- Stats below may not be entirely accurate ---", "17 legendary dragon pets", - "24 epic dragon pets", - "18 epic golem pets", - "12 legendary golem pets", - "39 legendary phoenix pets", - "", - "get flexed"); + "24 epic dragon pets", + "18 epic golem pets", + "12 legendary golem pets", + "39 legendary phoenix pets", + "", + "get flexed"); public static JsonObject CREDITS = Constants.MISC.getAsJsonObject("credits"); public static JsonObject IRONM00N = create( "IRONM00N", @@ -79,9 +79,9 @@ public class CustomItems { JsonObject json = new JsonObject(); json.addProperty("itemid", itemid); json.addProperty("internalname", internalname); - json.addProperty("displayname", EnumChatFormatting.RED+displayname); + json.addProperty("displayname", EnumChatFormatting.RED + displayname); JsonArray jsonlore = new JsonArray(); - for(String line : lore) { + for (String line : lore) { jsonlore.add(new JsonPrimitive(EnumChatFormatting.GRAY + line)); } json.add("lore", jsonlore); diff --git a/src/main/java/io/github/moulberry/notenoughupdates/ItemPriceInformation.java b/src/main/java/io/github/moulberry/notenoughupdates/ItemPriceInformation.java index 83c4b7ae..0aa80126 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/ItemPriceInformation.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/ItemPriceInformation.java @@ -4,7 +4,6 @@ import com.google.gson.JsonObject; import io.github.moulberry.notenoughupdates.auction.APIManager; import io.github.moulberry.notenoughupdates.core.config.KeybindHelper; import io.github.moulberry.notenoughupdates.util.Constants; -import io.github.moulberry.notenoughupdates.util.Utils; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; @@ -21,10 +20,10 @@ public class ItemPriceInformation { } public static boolean addToTooltip(List tooltip, String internalname, ItemStack stack, boolean useStackSize) { - if(stack.getTagCompound().hasKey("disableNeuTooltip") && stack.getTagCompound().getBoolean("disableNeuTooltip")){ + if (stack.getTagCompound().hasKey("disableNeuTooltip") && stack.getTagCompound().getBoolean("disableNeuTooltip")) { return false; } - if(NotEnoughUpdates.INSTANCE.config.tooltipTweaks.disablePriceKey && !KeybindHelper.isKeyDown(NotEnoughUpdates.INSTANCE.config.tooltipTweaks.disablePriceKeyKeybind)){ + if (NotEnoughUpdates.INSTANCE.config.tooltipTweaks.disablePriceKey && !KeybindHelper.isKeyDown(NotEnoughUpdates.INSTANCE.config.tooltipTweaks.disablePriceKeyKeybind)) { return false; } JsonObject auctionInfo = NotEnoughUpdates.INSTANCE.manager.auctionManager.getItemAuctionInfo(internalname); @@ -39,7 +38,7 @@ public class ItemPriceInformation { NumberFormat format = NumberFormat.getInstance(Locale.US); - if(bazaarItem) { + if (bazaarItem) { List lines = NotEnoughUpdates.INSTANCE.config.tooltipTweaks.priceInfoBaz; boolean added = false; @@ -48,161 +47,169 @@ public class ItemPriceInformation { int stackMultiplier = 1; int shiftStackMultiplier = useStackSize && stack.stackSize > 1 ? stack.stackSize : 64; - if(shiftPressed) { + if (shiftPressed) { stackMultiplier = shiftStackMultiplier; } //values = {"", "Buy", "Sell", "Buy (Insta)", "Sell (Insta)", "Raw Craft Cost"} - for(int lineId : lines) { + for (int lineId : lines) { switch (lineId) { case 0: - if(bazaarInfo.has("avg_buy")) { - if(!added) { + if (bazaarInfo.has("avg_buy")) { + if (!added) { tooltip.add(""); - if(!shiftPressed) tooltip.add(EnumChatFormatting.DARK_GRAY.toString()+"[SHIFT show x"+shiftStackMultiplier+"]"); + if (!shiftPressed) + tooltip.add(EnumChatFormatting.DARK_GRAY + "[SHIFT show x" + shiftStackMultiplier + "]"); added = true; } - int bazaarBuyPrice = (int)bazaarInfo.get("avg_buy").getAsFloat()*stackMultiplier; - tooltip.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"Bazaar Buy: "+ - EnumChatFormatting.GOLD+EnumChatFormatting.BOLD+format.format(bazaarBuyPrice)+" coins"); + int bazaarBuyPrice = (int) bazaarInfo.get("avg_buy").getAsFloat() * stackMultiplier; + tooltip.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "Bazaar Buy: " + + EnumChatFormatting.GOLD + EnumChatFormatting.BOLD + format.format(bazaarBuyPrice) + " coins"); } break; case 1: - if(bazaarInfo.has("avg_sell")) { - if(!added) { + if (bazaarInfo.has("avg_sell")) { + if (!added) { tooltip.add(""); - if(!shiftPressed) tooltip.add(EnumChatFormatting.DARK_GRAY.toString()+"[SHIFT show x"+shiftStackMultiplier+"]"); + if (!shiftPressed) + tooltip.add(EnumChatFormatting.DARK_GRAY + "[SHIFT show x" + shiftStackMultiplier + "]"); added = true; } - int bazaarSellPrice = (int)bazaarInfo.get("avg_sell").getAsFloat()*stackMultiplier; - tooltip.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"Bazaar Sell: "+ - EnumChatFormatting.GOLD+EnumChatFormatting.BOLD+format.format(bazaarSellPrice)+" coins"); + int bazaarSellPrice = (int) bazaarInfo.get("avg_sell").getAsFloat() * stackMultiplier; + tooltip.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "Bazaar Sell: " + + EnumChatFormatting.GOLD + EnumChatFormatting.BOLD + format.format(bazaarSellPrice) + " coins"); } break; case 2: - if(bazaarInfo.has("curr_buy")) { - if(!added) { + if (bazaarInfo.has("curr_buy")) { + if (!added) { tooltip.add(""); - if(!shiftPressed) tooltip.add(EnumChatFormatting.DARK_GRAY.toString()+"[SHIFT show x"+shiftStackMultiplier+"]"); + if (!shiftPressed) + tooltip.add(EnumChatFormatting.DARK_GRAY + "[SHIFT show x" + shiftStackMultiplier + "]"); added = true; } - int bazaarInstantBuyPrice = (int)bazaarInfo.get("curr_buy").getAsFloat()*stackMultiplier; - tooltip.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"Bazaar Insta-Buy: "+ - EnumChatFormatting.GOLD+EnumChatFormatting.BOLD+format.format(bazaarInstantBuyPrice)+" coins"); + int bazaarInstantBuyPrice = (int) bazaarInfo.get("curr_buy").getAsFloat() * stackMultiplier; + tooltip.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "Bazaar Insta-Buy: " + + EnumChatFormatting.GOLD + EnumChatFormatting.BOLD + format.format(bazaarInstantBuyPrice) + " coins"); } break; case 3: - if(bazaarInfo.has("curr_sell")) { - if(!added) { + if (bazaarInfo.has("curr_sell")) { + if (!added) { tooltip.add(""); - if(!shiftPressed) tooltip.add(EnumChatFormatting.DARK_GRAY.toString()+"[SHIFT show x"+shiftStackMultiplier+"]"); + if (!shiftPressed) + tooltip.add(EnumChatFormatting.DARK_GRAY + "[SHIFT show x" + shiftStackMultiplier + "]"); added = true; } - int bazaarInstantSellPrice = (int)bazaarInfo.get("curr_sell").getAsFloat()*stackMultiplier; - tooltip.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"Bazaar Insta-Sell: "+ - EnumChatFormatting.GOLD+EnumChatFormatting.BOLD+format.format(bazaarInstantSellPrice)+" coins"); + int bazaarInstantSellPrice = (int) bazaarInfo.get("curr_sell").getAsFloat() * stackMultiplier; + tooltip.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "Bazaar Insta-Sell: " + + EnumChatFormatting.GOLD + EnumChatFormatting.BOLD + format.format(bazaarInstantSellPrice) + " coins"); } break; case 4: - if(craftCost.fromRecipe) { - if((int)craftCost.craftCost == 0){ continue;} - if(!added) { + if (craftCost.fromRecipe) { + if ((int) craftCost.craftCost == 0) { + continue; + } + if (!added) { tooltip.add(""); added = true; } - tooltip.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"Raw Craft Cost: "+ - EnumChatFormatting.GOLD+EnumChatFormatting.BOLD+format.format((int)craftCost.craftCost)+" coins"); + tooltip.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "Raw Craft Cost: " + + EnumChatFormatting.GOLD + EnumChatFormatting.BOLD + format.format((int) craftCost.craftCost) + " coins"); } break; } } return added; - } else if(auctionItem) { + } else if (auctionItem) { List lines = NotEnoughUpdates.INSTANCE.config.tooltipTweaks.priceInfoAuc; boolean added = false; - for(int lineId : lines) { + for (int lineId : lines) { switch (lineId) { case 0: - if(lowestBin > 0) { - if(!added) { + if (lowestBin > 0) { + if (!added) { tooltip.add(""); added = true; } - tooltip.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"Lowest BIN: " + - EnumChatFormatting.GOLD+EnumChatFormatting.BOLD+format.format(lowestBin)+" coins"); + tooltip.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "Lowest BIN: " + + EnumChatFormatting.GOLD + EnumChatFormatting.BOLD + format.format(lowestBin) + " coins"); } break; case 1: - if(auctionInfo != null) { - if(!added) { + if (auctionInfo != null) { + if (!added) { tooltip.add(""); added = true; } - if(auctionInfo.has("clean_price")) { - tooltip.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"AH Price (Clean): "+ EnumChatFormatting.GOLD+ - EnumChatFormatting.BOLD+ - format.format((int)auctionInfo.get("clean_price").getAsFloat())+" coins"); + if (auctionInfo.has("clean_price")) { + tooltip.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "AH Price (Clean): " + EnumChatFormatting.GOLD + + EnumChatFormatting.BOLD + + format.format((int) auctionInfo.get("clean_price").getAsFloat()) + " coins"); } else { - int auctionPrice = (int)(auctionInfo.get("price").getAsFloat() / auctionInfo.get("count").getAsFloat()); - tooltip.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"AH Price: "+ EnumChatFormatting.GOLD+ - EnumChatFormatting.BOLD+format.format(auctionPrice)+" coins"); + int auctionPrice = (int) (auctionInfo.get("price").getAsFloat() / auctionInfo.get("count").getAsFloat()); + tooltip.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "AH Price: " + EnumChatFormatting.GOLD + + EnumChatFormatting.BOLD + format.format(auctionPrice) + " coins"); } } break; case 2: - if(auctionInfo != null) { - if(!added) { + if (auctionInfo != null) { + if (!added) { tooltip.add(""); added = true; } - if(auctionInfo.has("clean_price")) { - tooltip.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"AH Sales (Clean): "+ - EnumChatFormatting.GOLD+EnumChatFormatting.BOLD+ - format.format(auctionInfo.get("clean_sales").getAsFloat())+" sales/day"); + if (auctionInfo.has("clean_price")) { + tooltip.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "AH Sales (Clean): " + + EnumChatFormatting.GOLD + EnumChatFormatting.BOLD + + format.format(auctionInfo.get("clean_sales").getAsFloat()) + " sales/day"); } else { - tooltip.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"AH Sales: "+ - EnumChatFormatting.GOLD+EnumChatFormatting.BOLD+ - format.format(auctionInfo.get("sales").getAsFloat())+" sales/day"); + tooltip.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "AH Sales: " + + EnumChatFormatting.GOLD + EnumChatFormatting.BOLD + + format.format(auctionInfo.get("sales").getAsFloat()) + " sales/day"); } } break; case 3: - if(craftCost.fromRecipe) { - if((int)craftCost.craftCost == 0){ continue;} - if(!added) { + if (craftCost.fromRecipe) { + if ((int) craftCost.craftCost == 0) { + continue; + } + if (!added) { tooltip.add(""); added = true; } - tooltip.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"Raw Craft Cost: "+ - EnumChatFormatting.GOLD+EnumChatFormatting.BOLD+format.format((int)craftCost.craftCost)+" coins"); + tooltip.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "Raw Craft Cost: " + + EnumChatFormatting.GOLD + EnumChatFormatting.BOLD + format.format((int) craftCost.craftCost) + " coins"); } break; case 4: - if(lowestBinAvg > 0) { - if(!added) { + if (lowestBinAvg > 0) { + if (!added) { tooltip.add(""); added = true; } - tooltip.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"AVG Lowest BIN: "+ - EnumChatFormatting.GOLD+EnumChatFormatting.BOLD+format.format(lowestBinAvg)+" coins"); + tooltip.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "AVG Lowest BIN: " + + EnumChatFormatting.GOLD + EnumChatFormatting.BOLD + format.format(lowestBinAvg) + " coins"); } break; case 5: - if(Constants.ESSENCECOSTS == null) break; + if (Constants.ESSENCECOSTS == null) break; JsonObject essenceCosts = Constants.ESSENCECOSTS; - if(!essenceCosts.has(internalname)) { + if (!essenceCosts.has(internalname)) { break; } JsonObject itemCosts = essenceCosts.get(internalname).getAsJsonObject(); String essenceType = itemCosts.get("type").getAsString(); int dungeonItemLevel = -1; - if(stack != null && stack.hasTagCompound() && + if (stack != null && stack.hasTagCompound() && stack.getTagCompound().hasKey("ExtraAttributes", 10)) { NBTTagCompound ea = stack.getTagCompound().getCompoundTag("ExtraAttributes"); @@ -210,24 +217,24 @@ public class ItemPriceInformation { dungeonItemLevel = ea.getInteger("dungeon_item_level"); } } - if(dungeonItemLevel == -1) { + if (dungeonItemLevel == -1) { int dungeonizeCost = 0; - if(itemCosts.has("dungeonize")) { + if (itemCosts.has("dungeonize")) { dungeonizeCost = itemCosts.get("dungeonize").getAsInt(); } - tooltip.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"Dungeonize Cost: " + - EnumChatFormatting.GOLD+EnumChatFormatting.BOLD+dungeonizeCost+" "+essenceType); - } else if(dungeonItemLevel >= 0 && dungeonItemLevel <= 4) { - String costType = (dungeonItemLevel+1)+""; + tooltip.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "Dungeonize Cost: " + + EnumChatFormatting.GOLD + EnumChatFormatting.BOLD + dungeonizeCost + " " + essenceType); + } else if (dungeonItemLevel >= 0 && dungeonItemLevel <= 4) { + String costType = (dungeonItemLevel + 1) + ""; int upgradeCost = itemCosts.get(costType).getAsInt(); StringBuilder star = new StringBuilder(); - for(int i=0; i<=dungeonItemLevel; i++) { + for (int i = 0; i <= dungeonItemLevel; i++) { star.append('\u272A'); } - tooltip.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"Upgrade to "+ - EnumChatFormatting.GOLD+star+EnumChatFormatting.YELLOW+EnumChatFormatting.BOLD+": " + - EnumChatFormatting.GOLD+EnumChatFormatting.BOLD+upgradeCost+" "+essenceType); + tooltip.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "Upgrade to " + + EnumChatFormatting.GOLD + star + EnumChatFormatting.YELLOW + EnumChatFormatting.BOLD + ": " + + EnumChatFormatting.GOLD + EnumChatFormatting.BOLD + upgradeCost + " " + essenceType); } break; } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/NEUApi.java b/src/main/java/io/github/moulberry/notenoughupdates/NEUApi.java index 56a196b4..df06aae7 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/NEUApi.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/NEUApi.java @@ -4,7 +4,8 @@ import net.minecraftforge.fml.relauncher.ReflectionHelper; public class NEUApi { static boolean disableInventoryButtons = false; - public static void setInventoryButtonsToDisabled(){ + + public static void setInventoryButtonsToDisabled() { disableInventoryButtons = true; } } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/NEUEventListener.java b/src/main/java/io/github/moulberry/notenoughupdates/NEUEventListener.java index 42b53ef2..527abd02 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/NEUEventListener.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/NEUEventListener.java @@ -1,7 +1,10 @@ package io.github.moulberry.notenoughupdates; import com.google.common.collect.Lists; -import com.google.gson.*; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; import com.mojang.authlib.GameProfile; import com.mojang.authlib.minecraft.MinecraftProfileTexture; import io.github.moulberry.notenoughupdates.auction.CustomAHGui; @@ -82,7 +85,7 @@ public class NEUEventListener { private void displayUpdateMessageIfOutOfDate() { File repo = neu.manager.repoLocation; - if(repo.exists()) { + if (repo.exists()) { File updateJson = new File(repo, "update.json"); try { JsonObject o = neu.manager.getJsonFromFile(updateJson); @@ -93,7 +96,7 @@ public class NEUEventListener { boolean shouldUpdate = !NotEnoughUpdates.VERSION.equalsIgnoreCase(version); boolean shouldPreUpdate = !NotEnoughUpdates.PRE_VERSION.equalsIgnoreCase(preVersion); - if(o.has("version_id") && o.get("version_id").isJsonPrimitive()) { + if (o.has("version_id") && o.get("version_id").isJsonPrimitive()) { int version_id = o.get("version_id").getAsInt(); shouldUpdate = version_id > NotEnoughUpdates.VERSION_ID; } @@ -102,20 +105,20 @@ public class NEUEventListener { shouldPreUpdate = pre_version_id > NotEnoughUpdates.PRE_VERSION_ID; } - if(shouldUpdate) { + if (shouldUpdate) { String update_msg = o.get("update_msg").getAsString(); int first_len = -1; - for(String line : update_msg.split("\n")) { + for (String line : update_msg.split("\n")) { FontRenderer fr = Minecraft.getMinecraft().fontRendererObj; int len = fr.getStringWidth(line); - if(first_len == -1) { + if (first_len == -1) { first_len = len; } - int missing_len = first_len-len; - if(missing_len > 0) { + int missing_len = first_len - len; + if (missing_len > 0) { StringBuilder sb = new StringBuilder(line); - for(int i=0; i lines, boolean showForever) { displayNotification(lines, showForever, false); } public static void displayNotification(List lines, boolean showForever, boolean overInventory) { - if(showForever) { + if (showForever) { notificationDisplayMillis = -420; } else { notificationDisplayMillis = System.currentTimeMillis(); @@ -200,30 +204,30 @@ public class NEUEventListener { @SubscribeEvent public void onTick(TickEvent.ClientTickEvent event) { - if(Minecraft.getMinecraft().currentScreen == null || !(Minecraft.getMinecraft().currentScreen instanceof GuiChat)) { + if (Minecraft.getMinecraft().currentScreen == null || !(Minecraft.getMinecraft().currentScreen instanceof GuiChat)) { Keyboard.enableRepeatEvents(false); } - if(event.phase != TickEvent.Phase.START) return; - if(Minecraft.getMinecraft().theWorld == null) return; - if(Minecraft.getMinecraft().thePlayer == null) return; + if (event.phase != TickEvent.Phase.START) return; + if (Minecraft.getMinecraft().theWorld == null) return; + if (Minecraft.getMinecraft().thePlayer == null) return; - if(Minecraft.getMinecraft().currentScreen instanceof GuiChest) { + if (Minecraft.getMinecraft().currentScreen instanceof GuiChest) { GuiChest chest = (GuiChest) Minecraft.getMinecraft().currentScreen; ContainerChest cc = (ContainerChest) chest.inventorySlots; - if(!loadedInvName.equals(cc.getLowerChestInventory().getDisplayName().getUnformattedText())) { + if (!loadedInvName.equals(cc.getLowerChestInventory().getDisplayName().getUnformattedText())) { loadedInvName = cc.getLowerChestInventory().getDisplayName().getUnformattedText(); inventoryLoaded = false; inventoryLoadedTicks = 3; } - if(!inventoryLoaded) { - if(cc.getLowerChestInventory().getStackInSlot(cc.getLowerChestInventory().getSizeInventory()-1) != null) { + if (!inventoryLoaded) { + if (cc.getLowerChestInventory().getStackInSlot(cc.getLowerChestInventory().getSizeInventory() - 1) != null) { inventoryLoaded = true; } else { - for(ItemStack stack : chest.inventorySlots.getInventory()) { - if(stack != null) { - if(--inventoryLoadedTicks <= 0) { + for (ItemStack stack : chest.inventorySlots.getInventory()) { + if (stack != null) { + if (--inventoryLoadedTicks <= 0) { inventoryLoaded = true; } break; @@ -236,7 +240,7 @@ public class NEUEventListener { inventoryLoadedTicks = 3; } - if(Keyboard.isKeyDown(Keyboard.KEY_NUMPAD1) && Keyboard.isKeyDown(Keyboard.KEY_NUMPAD4) && Keyboard.isKeyDown(Keyboard.KEY_NUMPAD9)) { + if (Keyboard.isKeyDown(Keyboard.KEY_NUMPAD1) && Keyboard.isKeyDown(Keyboard.KEY_NUMPAD4) && Keyboard.isKeyDown(Keyboard.KEY_NUMPAD9)) { ChatComponentText component = new ChatComponentText("\u00a7cYou are permanently banned from this server!"); component.appendText("\n"); component.appendText("\n\u00a77Reason: \u00a7rSuspicious account activity/Other"); @@ -248,51 +252,51 @@ public class NEUEventListener { return; } - if(neu.hasSkyblockScoreboard()) { - if(!preloadedItems) { + if (neu.hasSkyblockScoreboard()) { + if (!preloadedItems) { preloadedItems = true; List list = new ArrayList<>(neu.manager.getItemInformation().values()); - for(JsonObject json : list) { + for (JsonObject json : list) { itemPreloader.submit(() -> { ItemStack stack = neu.manager.jsonToStack(json, true, true); - if(stack.getItem() == Items.skull) toPreload.add(stack); + if (stack.getItem() == Items.skull) toPreload.add(stack); }); } - } else if(!toPreload.isEmpty()) { + } else if (!toPreload.isEmpty()) { Utils.drawItemStack(toPreload.get(0), -100, -100); toPreload.remove(0); } else { itemPreloader.shutdown(); } - for(TextOverlay overlay : OverlayManager.textOverlays) { + for (TextOverlay overlay : OverlayManager.textOverlays) { overlay.shouldUpdateFrequent = true; } } boolean longUpdate = false; long currentTime = System.currentTimeMillis(); - if(currentTime - lastLongUpdate > 1000) { + if (currentTime - lastLongUpdate > 1000) { longUpdate = true; lastLongUpdate = currentTime; } - if(!NotEnoughUpdates.INSTANCE.config.dungeons.slowDungeonBlocks) { + if (!NotEnoughUpdates.INSTANCE.config.dungeons.slowDungeonBlocks) { DungeonBlocks.tick(); } DungeonWin.tick(); String containerName = null; - if(Minecraft.getMinecraft().currentScreen instanceof GuiChest) { + if (Minecraft.getMinecraft().currentScreen instanceof GuiChest) { GuiChest eventGui = (GuiChest) Minecraft.getMinecraft().currentScreen; ContainerChest cc = (ContainerChest) eventGui.inventorySlots; containerName = cc.getLowerChestInventory().getDisplayName().getUnformattedText(); - if(GuiCustomEnchant.getInstance().shouldOverride(containerName)) { + if (GuiCustomEnchant.getInstance().shouldOverride(containerName)) { GuiCustomEnchant.getInstance().tick(); } } - if(longUpdate) { + if (longUpdate) { CrystalOverlay.tick(); DwarvenMinesTextures.tick(); FairySouls.tick(); @@ -303,8 +307,8 @@ public class NEUEventListener { NPCRetexturing.getInstance().tick(); StorageOverlay.getInstance().markDirty(); - if(neu.hasSkyblockScoreboard()) { - for(TextOverlay overlay : OverlayManager.textOverlays) { + if (neu.hasSkyblockScoreboard()) { + for (TextOverlay overlay : OverlayManager.textOverlays) { overlay.tick(); } } @@ -315,58 +319,57 @@ public class NEUEventListener { NotEnoughUpdates.profileViewer.putNameUuid(Minecraft.getMinecraft().thePlayer.getName(), Minecraft.getMinecraft().thePlayer.getUniqueID().toString().replace("-", "")); - if(NotEnoughUpdates.INSTANCE.config.dungeons.slowDungeonBlocks) { + if (NotEnoughUpdates.INSTANCE.config.dungeons.slowDungeonBlocks) { DungeonBlocks.tick(); } - if(System.currentTimeMillis() - SBInfo.getInstance().joinedWorld > 500 && + if (System.currentTimeMillis() - SBInfo.getInstance().joinedWorld > 500 && System.currentTimeMillis() - SBInfo.getInstance().unloadedWorld > 500) { neu.updateSkyblockScoreboard(); } CapeManager.getInstance().tick(); - if(containerName != null) { - if(!containerName.trim().startsWith("Accessory Bag")) { + if (containerName != null) { + if (!containerName.trim().startsWith("Accessory Bag")) { AccessoryBagOverlay.resetCache(); } } else { AccessoryBagOverlay.resetCache(); } - if(neu.hasSkyblockScoreboard()) { + if (neu.hasSkyblockScoreboard()) { SBInfo.getInstance().tick(); lastSkyblockScoreboard = currentTime; - if(!joinedSB) { + if (!joinedSB) { joinedSB = true; //SBGamemodes.loadFromFile(); - - if(NotEnoughUpdates.INSTANCE.config.notifications.showUpdateMsg) { + if (NotEnoughUpdates.INSTANCE.config.notifications.showUpdateMsg) { displayUpdateMessageIfOutOfDate(); } - if(NotEnoughUpdates.INSTANCE.config.notifications.doRamNotif) { - long maxMemoryMB = Runtime.getRuntime().maxMemory()/1024L/1024L; - if(maxMemoryMB > 4100) { + if (NotEnoughUpdates.INSTANCE.config.notifications.doRamNotif) { + long maxMemoryMB = Runtime.getRuntime().maxMemory() / 1024L / 1024L; + if (maxMemoryMB > 4100) { notificationDisplayMillis = System.currentTimeMillis(); notificationLines = new ArrayList<>(); - notificationLines.add(EnumChatFormatting.GRAY+"Too much memory allocated!"); - notificationLines.add(String.format(EnumChatFormatting.DARK_GRAY+"NEU has detected %03dMB of memory allocated to Minecraft!", maxMemoryMB)); - notificationLines.add(EnumChatFormatting.GRAY+"It is recommended to allocated between 2-4GB of memory"); - notificationLines.add(EnumChatFormatting.GRAY+"More than 4GB MAY cause FPS issues, EVEN if you have 16GB+ available"); + notificationLines.add(EnumChatFormatting.GRAY + "Too much memory allocated!"); + notificationLines.add(String.format(EnumChatFormatting.DARK_GRAY + "NEU has detected %03dMB of memory allocated to Minecraft!", maxMemoryMB)); + notificationLines.add(EnumChatFormatting.GRAY + "It is recommended to allocated between 2-4GB of memory"); + notificationLines.add(EnumChatFormatting.GRAY + "More than 4GB MAY cause FPS issues, EVEN if you have 16GB+ available"); notificationLines.add(""); - notificationLines.add(EnumChatFormatting.GRAY+"For more information, visit #ram-info in discord.gg/moulberry"); + notificationLines.add(EnumChatFormatting.GRAY + "For more information, visit #ram-info in discord.gg/moulberry"); } } - if(!NotEnoughUpdates.INSTANCE.config.hidden.loadedModBefore) { + if (!NotEnoughUpdates.INSTANCE.config.hidden.loadedModBefore) { NotEnoughUpdates.INSTANCE.config.hidden.loadedModBefore = true; - if(Constants.MISC == null || !Constants.MISC.has("featureslist")){ - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(""+EnumChatFormatting.DARK_RED+EnumChatFormatting.BOLD+"WARNING: "+EnumChatFormatting.RESET+EnumChatFormatting.RED+"Could not load Feature List URL from repo.")); - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(""+EnumChatFormatting.RED+ "Please run "+EnumChatFormatting.BOLD+"/neuresetrepo"+EnumChatFormatting.RESET+EnumChatFormatting.RED+" and "+EnumChatFormatting.BOLD+"restart your game"+EnumChatFormatting.RESET+EnumChatFormatting.RED+" in order to fix. "+EnumChatFormatting.DARK_RED+EnumChatFormatting.BOLD+"If that doesn't fix it"+EnumChatFormatting.RESET+EnumChatFormatting.RED+", please join discord.gg/moulberry and post in #neu-support")); + if (Constants.MISC == null || !Constants.MISC.has("featureslist")) { + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("" + EnumChatFormatting.DARK_RED + EnumChatFormatting.BOLD + "WARNING: " + EnumChatFormatting.RESET + EnumChatFormatting.RED + "Could not load Feature List URL from repo.")); + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("" + EnumChatFormatting.RED + "Please run " + EnumChatFormatting.BOLD + "/neuresetrepo" + EnumChatFormatting.RESET + EnumChatFormatting.RED + " and " + EnumChatFormatting.BOLD + "restart your game" + EnumChatFormatting.RESET + EnumChatFormatting.RED + " in order to fix. " + EnumChatFormatting.DARK_RED + EnumChatFormatting.BOLD + "If that doesn't fix it" + EnumChatFormatting.RESET + EnumChatFormatting.RED + ", please join discord.gg/moulberry and post in #neu-support")); Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("")); - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(""+EnumChatFormatting.GOLD+"To view the feature list after restarting type /neufeatures")); + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("" + EnumChatFormatting.GOLD + "To view the feature list after restarting type /neufeatures")); } else { String url = Constants.MISC.get("featureslist").getAsString(); Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("")); @@ -379,14 +382,14 @@ public class NEUEventListener { } Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("")); ChatComponentText clickTextHelp = new ChatComponentText( - EnumChatFormatting.YELLOW+"Click this message if you would like to view a list of NotEnoughUpdate's commands."); + EnumChatFormatting.YELLOW + "Click this message if you would like to view a list of NotEnoughUpdate's commands."); clickTextHelp.setChatStyle(Utils.createClickStyle(ClickEvent.Action.RUN_COMMAND, "/neuhelp")); Minecraft.getMinecraft().thePlayer.addChatMessage(clickTextHelp); Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("")); } } } - if(currentTime - lastSkyblockScoreboard < 5*60*1000) { //5 minutes + if (currentTime - lastSkyblockScoreboard < 5 * 60 * 1000) { //5 minutes neu.manager.auctionManager.tick(); } else { neu.manager.auctionManager.markNeedsUpdate(); @@ -472,10 +475,10 @@ public class NEUEventListener { } }*/ - @SubscribeEvent(priority= EventPriority.HIGHEST) + @SubscribeEvent(priority = EventPriority.HIGHEST) public void onRenderEntitySpecials(RenderLivingEvent.Specials.Pre event) { - if(Minecraft.getMinecraft().currentScreen instanceof GuiProfileViewer) { - if(((GuiProfileViewer)Minecraft.getMinecraft().currentScreen).getEntityPlayer() == event.entity) { + if (Minecraft.getMinecraft().currentScreen instanceof GuiProfileViewer) { + if (((GuiProfileViewer) Minecraft.getMinecraft().currentScreen).getEntityPlayer() == event.entity) { event.setCanceled(true); } } @@ -487,19 +490,19 @@ public class NEUEventListener { Minecraft.getMinecraft().currentScreen instanceof GuiContainer && neu.overlay.isUsingMobsFilter()) { event.setCanceled(true); } - if(event.type != null && event.type.equals(RenderGameOverlayEvent.ElementType.PLAYER_LIST)) { + if (event.type != null && event.type.equals(RenderGameOverlayEvent.ElementType.PLAYER_LIST)) { GlStateManager.enableDepth(); } } @SubscribeEvent public void onRenderGameOverlayPost(RenderGameOverlayEvent.Post event) { - if(neu.hasSkyblockScoreboard() && event.type.equals(RenderGameOverlayEvent.ElementType.ALL)) { + if (neu.hasSkyblockScoreboard() && event.type.equals(RenderGameOverlayEvent.ElementType.ALL)) { DungeonWin.render(event.partialTicks); GlStateManager.pushMatrix(); GlStateManager.translate(0, 0, -200); - for(TextOverlay overlay : OverlayManager.textOverlays) { - if(OverlayManager.dontRenderOverlay != null && OverlayManager.dontRenderOverlay.isAssignableFrom(overlay.getClass())) { + for (TextOverlay overlay : OverlayManager.textOverlays) { + if (OverlayManager.dontRenderOverlay != null && OverlayManager.dontRenderOverlay.isAssignableFrom(overlay.getClass())) { continue; } GlStateManager.translate(0, 0, -1); @@ -509,55 +512,56 @@ public class NEUEventListener { GlStateManager.popMatrix(); OverlayManager.dontRenderOverlay = null; } - if(Keyboard.isKeyDown(Keyboard.KEY_X)) { + if (Keyboard.isKeyDown(Keyboard.KEY_X)) { notificationDisplayMillis = 0; } - if(event.type == RenderGameOverlayEvent.ElementType.ALL){ + if (event.type == RenderGameOverlayEvent.ElementType.ALL) { renderNotification(); } } - private static void renderNotification(){ + + private static void renderNotification() { long timeRemaining = 15000 - (System.currentTimeMillis() - notificationDisplayMillis); boolean display = timeRemaining > 0 || notificationDisplayMillis == -420; - if(display && notificationLines != null && notificationLines.size() > 0) { + if (display && notificationLines != null && notificationLines.size() > 0) { int width = 0; - int height = notificationLines.size()*10+10; + int height = notificationLines.size() * 10 + 10; - for(String line : notificationLines) { + for (String line : notificationLines) { int len = Minecraft.getMinecraft().fontRendererObj.getStringWidth(line) + 8; - if(len > width) { + if (len > width) { width = len; } } ScaledResolution sr = Utils.pushGuiScale(2); - int midX = sr.getScaledWidth()/2; - int topY = sr.getScaledHeight()*3/4-height/2; - RenderUtils.drawFloatingRectDark(midX-width/2, sr.getScaledHeight()*3/4-height/2, width, height); + int midX = sr.getScaledWidth() / 2; + int topY = sr.getScaledHeight() * 3 / 4 - height / 2; + RenderUtils.drawFloatingRectDark(midX - width / 2, sr.getScaledHeight() * 3 / 4 - height / 2, width, height); /*Gui.drawRect(midX-width/2, sr.getScaledHeight()*3/4-height/2, midX+width/2, sr.getScaledHeight()*3/4+height/2, 0xFF3C3C3C); Gui.drawRect(midX-width/2+2, sr.getScaledHeight()*3/4-height/2+2, midX+width/2-2, sr.getScaledHeight()*3/4+height/2-2, 0xFFC8C8C8);*/ int xLen = Minecraft.getMinecraft().fontRendererObj.getStringWidth("[X] Close"); - Minecraft.getMinecraft().fontRendererObj.drawString("[X] Close", midX+width/2f-3-xLen, - topY+3, 0xFFFF5555, false); + Minecraft.getMinecraft().fontRendererObj.drawString("[X] Close", midX + width / 2f - 3 - xLen, + topY + 3, 0xFFFF5555, false); - if(notificationDisplayMillis > 0) { - Minecraft.getMinecraft().fontRendererObj.drawString((timeRemaining/1000)+"s", midX-width/2f+3, - topY+3, 0xFFaaaaaa, false); + if (notificationDisplayMillis > 0) { + Minecraft.getMinecraft().fontRendererObj.drawString((timeRemaining / 1000) + "s", midX - width / 2f + 3, + topY + 3, 0xFFaaaaaa, false); } Utils.drawStringCentered(notificationLines.get(0), Minecraft.getMinecraft().fontRendererObj, - midX, topY+4+5, false, -1); - for(int i=1; i { - if(Minecraft.getMinecraft().currentScreen != event.gui) { + if (Minecraft.getMinecraft().currentScreen != event.gui) { return; } - if(lower.getStackInSlot(23).getDisplayName().endsWith("Crafting Table")) { + if (lower.getStackInSlot(23).getDisplayName().endsWith("Crafting Table")) { try { ItemStack res = lower.getStackInSlot(25); String resInternalname = neu.manager.getInternalNameForItem(res); - if(lower.getStackInSlot(48) != null) { + if (lower.getStackInSlot(48) != null) { String backName = null; NBTTagCompound tag = lower.getStackInSlot(48).getTagCompound(); - if(tag.hasKey("display", 10)) { + if (tag.hasKey("display", 10)) { NBTTagCompound nbttagcompound = tag.getCompoundTag("display"); - if(nbttagcompound.getTagId("Lore") == 9){ + if (nbttagcompound.getTagId("Lore") == 9) { NBTTagList nbttaglist1 = nbttagcompound.getTagList("Lore", 8); backName = nbttaglist1.getStringTagAt(0); } } - if(backName != null) { + if (backName != null) { String[] split = backName.split(" "); - if(split[split.length-1].contains("Rewards")) { - String col = backName.substring(split[0].length()+1, - backName.length()-split[split.length-1].length()-1); + if (split[split.length - 1].contains("Rewards")) { + String col = backName.substring(split[0].length() + 1, + backName.length() - split[split.length - 1].length() - 1); JsonObject json = neu.manager.getItemInformation().get(resInternalname); json.addProperty("crafttext", "Requires: " + col); Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Added: " + resInternalname)); - neu.manager.writeJsonDefaultDir(json, resInternalname+".json"); + neu.manager.writeJsonDefaultDir(json, resInternalname + ".json"); neu.manager.loadItem(resInternalname); } } @@ -713,7 +718,7 @@ public class NEUEventListener { Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Added: " + resInternalname)); neu.manager.writeJsonDefaultDir(json, resInternalname+".json"); neu.manager.loadItem(resInternalname);*/ - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); } } @@ -742,22 +747,22 @@ public class NEUEventListener { private IChatComponent processChatComponent(IChatComponent chatComponent) { IChatComponent newComponent; - if(chatComponent instanceof ChatComponentText) { + if (chatComponent instanceof ChatComponentText) { ChatComponentText text = (ChatComponentText) chatComponent; newComponent = new ChatComponentText(processText(text.getUnformattedTextForChat())); newComponent.setChatStyle(text.getChatStyle().createShallowCopy()); - for(IChatComponent sibling : text.getSiblings()) { + for (IChatComponent sibling : text.getSiblings()) { newComponent.appendSibling(processChatComponent(sibling)); } - } else if(chatComponent instanceof ChatComponentTranslation) { + } else if (chatComponent instanceof ChatComponentTranslation) { ChatComponentTranslation trans = (ChatComponentTranslation) chatComponent; Object[] args = trans.getFormatArgs(); Object[] newArgs = new Object[args.length]; - for(int i=0; i * If hoverInv is true, will render the overlay immediately (resulting in the inventory being drawn over the GUI) * If hoverInv is false, the overlay will render in #onGuiScreenDraw (resulting in the GUI being drawn over the inv) - * + *

* All of this only matters if players are using gui scale auto which may result in the inventory being drawn * over the various panes. + * * @param event */ @SubscribeEvent public void onGuiBackgroundDraw(GuiScreenEvent.BackgroundDrawnEvent event) { - if(showNotificationOverInv){ + if (showNotificationOverInv) { renderNotification(); } - if((shouldRenderOverlay(event.gui) || event.gui instanceof CustomAHGui) && neu.isOnSkyblock()) { + if ((shouldRenderOverlay(event.gui) || event.gui instanceof CustomAHGui) && neu.isOnSkyblock()) { ScaledResolution scaledresolution = new ScaledResolution(Minecraft.getMinecraft()); int width = scaledresolution.getScaledWidth(); - boolean hoverPane = event.getMouseX() < width*neu.overlay.getInfoPaneOffsetFactor() || - event.getMouseX() > width*neu.overlay.getItemPaneOffsetFactor(); + boolean hoverPane = event.getMouseX() < width * neu.overlay.getInfoPaneOffsetFactor() || + event.getMouseX() > width * neu.overlay.getItemPaneOffsetFactor(); - if(event.gui instanceof GuiContainer) { + if (event.gui instanceof GuiContainer) { try { - int xSize = ((GuiContainer)event.gui).xSize; - int ySize = ((GuiContainer)event.gui).ySize; - int guiLeft = ((GuiContainer)event.gui).guiLeft; - int guiTop = ((GuiContainer)event.gui).guiTop; + int xSize = ((GuiContainer) event.gui).xSize; + int ySize = ((GuiContainer) event.gui).ySize; + int guiLeft = ((GuiContainer) event.gui).guiLeft; + int guiTop = ((GuiContainer) event.gui).guiTop; hoverInv = event.getMouseX() > guiLeft && event.getMouseX() < guiLeft + xSize && event.getMouseY() > guiTop && event.getMouseY() < guiTop + ySize; - if(hoverPane) { - if(!hoverInv) focusInv = false; + if (hoverPane) { + if (!hoverInv) focusInv = false; } else { focusInv = true; } - } catch(NullPointerException npe) { + } catch (NullPointerException npe) { focusInv = !hoverPane; } } - if(event.gui instanceof GuiItemRecipe) { - GuiItemRecipe guiItemRecipe = ((GuiItemRecipe)event.gui); + if (event.gui instanceof GuiItemRecipe) { + GuiItemRecipe guiItemRecipe = ((GuiItemRecipe) event.gui); hoverInv = event.getMouseX() > guiItemRecipe.guiLeft && event.getMouseX() < guiItemRecipe.guiLeft + guiItemRecipe.xSize && event.getMouseY() > guiItemRecipe.guiTop && event.getMouseY() < guiItemRecipe.guiTop + guiItemRecipe.ySize; - if(hoverPane) { - if(!hoverInv) focusInv = false; + if (hoverPane) { + if (!hoverInv) focusInv = false; } else { focusInv = true; } } - if(focusInv) { + if (focusInv) { try { neu.overlay.render(hoverInv); - } catch(ConcurrentModificationException e) {e.printStackTrace();} + } catch (ConcurrentModificationException e) { + e.printStackTrace(); + } GL11.glTranslatef(0, 0, 10); } - if(hoverInv) { + if (hoverInv) { renderDungeonChestOverlay(event.gui); - if(NotEnoughUpdates.INSTANCE.config.accessoryBag.enableOverlay) { + if (NotEnoughUpdates.INSTANCE.config.accessoryBag.enableOverlay) { AccessoryBagOverlay.renderOverlay(); } } @@ -945,12 +953,12 @@ public class NEUEventListener { public void onGuiScreenDrawPre(GuiScreenEvent.DrawScreenEvent.Pre event) { doInventoryButtons = false; - if(AuctionSearchOverlay.shouldReplace()) { + if (AuctionSearchOverlay.shouldReplace()) { AuctionSearchOverlay.render(); event.setCanceled(true); return; } - if(RancherBootOverlay.shouldReplace()) { + if (RancherBootOverlay.shouldReplace()) { RancherBootOverlay.render(); event.setCanceled(true); return; @@ -958,13 +966,13 @@ public class NEUEventListener { String containerName = null; GuiScreen guiScreen = Minecraft.getMinecraft().currentScreen; - if(guiScreen instanceof GuiChest) { + if (guiScreen instanceof GuiChest) { GuiChest eventGui = (GuiChest) guiScreen; ContainerChest cc = (ContainerChest) eventGui.inventorySlots; containerName = cc.getLowerChestInventory().getDisplayName().getUnformattedText(); } - if(GuiCustomEnchant.getInstance().shouldOverride(containerName)) { + if (GuiCustomEnchant.getInstance().shouldOverride(containerName)) { GuiCustomEnchant.getInstance().render(event.renderPartialTicks); event.setCanceled(true); return; @@ -974,13 +982,13 @@ public class NEUEventListener { boolean storageOverlayActive = StorageManager.getInstance().shouldRenderStorageOverlay(containerName); boolean customAhActive = event.gui instanceof CustomAHGui || neu.manager.auctionManager.customAH.isRenderOverAuctionView(); - if(storageOverlayActive) { + if (storageOverlayActive) { StorageOverlay.getInstance().render(); event.setCanceled(true); return; } - if(tradeWindowActive || customAhActive) { + if (tradeWindowActive || customAhActive) { event.setCanceled(true); ScaledResolution scaledResolution = new ScaledResolution(Minecraft.getMinecraft()); @@ -990,25 +998,25 @@ public class NEUEventListener { //Dark background Utils.drawGradientRect(0, 0, width, height, -1072689136, -804253680); - if(event.mouseX < width*neu.overlay.getWidthMult()/3 || event.mouseX > width-width*neu.overlay.getWidthMult()/3) { - if(customAhActive) { + if (event.mouseX < width * neu.overlay.getWidthMult() / 3 || event.mouseX > width - width * neu.overlay.getWidthMult() / 3) { + if (customAhActive) { neu.manager.auctionManager.customAH.drawScreen(event.mouseX, event.mouseY); - } else if(tradeWindowActive) { + } else if (tradeWindowActive) { TradeWindow.render(event.mouseX, event.mouseY); } neu.overlay.render(false); } else { neu.overlay.render(false); - if(customAhActive) { + if (customAhActive) { neu.manager.auctionManager.customAH.drawScreen(event.mouseX, event.mouseY); - } else if(tradeWindowActive) { + } else if (tradeWindowActive) { TradeWindow.render(event.mouseX, event.mouseY); } } } - if(CalendarOverlay.isEnabled() || event.isCanceled()) return; - if(NotEnoughUpdates.INSTANCE.hasSkyblockScoreboard() && shouldRenderOverlay(event.gui) + if (CalendarOverlay.isEnabled() || event.isCanceled()) return; + if (NotEnoughUpdates.INSTANCE.hasSkyblockScoreboard() && shouldRenderOverlay(event.gui) && event.gui instanceof GuiContainer) { doInventoryButtons = true; @@ -1060,11 +1068,11 @@ public class NEUEventListener { private static boolean shouldRenderOverlay(Gui gui) { boolean validGui = gui instanceof GuiContainer || gui instanceof GuiItemRecipe; - if(gui instanceof GuiChest) { + if (gui instanceof GuiChest) { GuiChest eventGui = (GuiChest) gui; ContainerChest cc = (ContainerChest) eventGui.inventorySlots; String containerName = cc.getLowerChestInventory().getDisplayName().getUnformattedText(); - if(containerName.trim().equals("Fast Travel")) { + if (containerName.trim().equals("Fast Travel")) { validGui = false; } } @@ -1079,6 +1087,7 @@ public class NEUEventListener { /** * Will draw the NEUOverlay over the inventory if focusInv == false. (z-translation of 300 is so that NEUOverlay * will draw over Items in the inventory (which render at a z value of about 250)) + * * @param event */ @SubscribeEvent @@ -1088,7 +1097,7 @@ public class NEUEventListener { String containerName = null; GuiScreen guiScreen = Minecraft.getMinecraft().currentScreen; - if(guiScreen instanceof GuiChest) { + if (guiScreen instanceof GuiChest) { GuiChest eventGui = (GuiChest) guiScreen; ContainerChest cc = (ContainerChest) eventGui.inventorySlots; containerName = cc.getLowerChestInventory().getDisplayName().getUnformattedText(); @@ -1097,7 +1106,7 @@ public class NEUEventListener { } } - if(GuiCustomEnchant.getInstance().shouldOverride(containerName)) { + if (GuiCustomEnchant.getInstance().shouldOverride(containerName)) { return; } @@ -1105,10 +1114,10 @@ public class NEUEventListener { boolean storageOverlayActive = StorageManager.getInstance().shouldRenderStorageOverlay(containerName); boolean customAhActive = event.gui instanceof CustomAHGui || neu.manager.auctionManager.customAH.isRenderOverAuctionView(); - if(!(tradeWindowActive || storageOverlayActive || customAhActive)) { - if(shouldRenderOverlay(event.gui) && neu.isOnSkyblock()) { + if (!(tradeWindowActive || storageOverlayActive || customAhActive)) { + if (shouldRenderOverlay(event.gui) && neu.isOnSkyblock()) { GlStateManager.pushMatrix(); - if(!focusInv) { + if (!focusInv) { GL11.glTranslatef(0, 0, 300); neu.overlay.render(hoverInv && focusInv); GL11.glTranslatef(0, 0, -300); @@ -1117,16 +1126,16 @@ public class NEUEventListener { } } - if(shouldRenderOverlay(event.gui) && neu.isOnSkyblock() && !hoverInv) { + if (shouldRenderOverlay(event.gui) && neu.isOnSkyblock() && !hoverInv) { renderDungeonChestOverlay(event.gui); - if(NotEnoughUpdates.INSTANCE.config.accessoryBag.enableOverlay) { + if (NotEnoughUpdates.INSTANCE.config.accessoryBag.enableOverlay) { AccessoryBagOverlay.renderOverlay(); } } boolean hoveringButton = false; - if(!doInventoryButtons) return; - if(NotEnoughUpdates.INSTANCE.hasSkyblockScoreboard() && shouldRenderOverlay(event.gui) && + if (!doInventoryButtons) return; + if (NotEnoughUpdates.INSTANCE.hasSkyblockScoreboard() && shouldRenderOverlay(event.gui) && event.gui instanceof GuiContainer) { int xSize = ((GuiContainer) event.gui).xSize; int ySize = ((GuiContainer) event.gui).ySize; @@ -1179,91 +1188,92 @@ public class NEUEventListener { } } } - if(!hoveringButton) buttonHovered = null; + if (!hoveringButton) buttonHovered = null; - if(AuctionBINWarning.getInstance().shouldShow()) { + if (AuctionBINWarning.getInstance().shouldShow()) { AuctionBINWarning.getInstance().render(); } } private void renderDungeonChestOverlay(GuiScreen gui) { - if(NotEnoughUpdates.INSTANCE.config.dungeons.profitDisplayLoc == 3) return; + if (NotEnoughUpdates.INSTANCE.config.dungeons.profitDisplayLoc == 3) return; - if(gui instanceof GuiChest && NotEnoughUpdates.INSTANCE.config.dungeons.profitDisplayLoc != 2) { + if (gui instanceof GuiChest && NotEnoughUpdates.INSTANCE.config.dungeons.profitDisplayLoc != 2) { try { - int xSize = ((GuiContainer)gui).xSize; - int ySize = ((GuiContainer)gui).ySize; - int guiLeft = ((GuiContainer)gui).guiLeft; - int guiTop = ((GuiContainer)gui).guiTop; + int xSize = ((GuiContainer) gui).xSize; + int ySize = ((GuiContainer) gui).ySize; + int guiLeft = ((GuiContainer) gui).guiLeft; + int guiTop = ((GuiContainer) gui).guiTop; GuiChest eventGui = (GuiChest) gui; ContainerChest cc = (ContainerChest) eventGui.inventorySlots; IInventory lower = cc.getLowerChestInventory(); ItemStack rewardChest = lower.getStackInSlot(31); - if (rewardChest != null && rewardChest.getDisplayName().endsWith(EnumChatFormatting.GREEN+"Open Reward Chest")) { + if (rewardChest != null && rewardChest.getDisplayName().endsWith(EnumChatFormatting.GREEN + "Open Reward Chest")) { int chestCost = 0; try { String line6 = Utils.cleanColour(neu.manager.getLoreFromNBT(rewardChest.getTagCompound())[6]); StringBuilder cost = new StringBuilder(); - for(int i=0; i= 0) { + if ("0123456789".indexOf(c) >= 0) { cost.append(c); } } - if(cost.length() > 0) { + if (cost.length() > 0) { chestCost = Integer.parseInt(cost.toString()); } - } catch(Exception ignored) {} + } catch (Exception ignored) { + } String missingItem = null; int totalValue = 0; HashMap itemValues = new HashMap<>(); - for(int i=0; i<5; i++) { - ItemStack item = lower.getStackInSlot(11+i); + for (int i = 0; i < 5; i++) { + ItemStack item = lower.getStackInSlot(11 + i); String internal = neu.manager.getInternalNameForItem(item); - if(internal != null) { + if (internal != null) { internal = internal.replace("\u00CD", "I").replace("\u0130", "I"); float bazaarPrice = -1; JsonObject bazaarInfo = neu.manager.auctionManager.getBazaarInfo(internal); - if(bazaarInfo != null && bazaarInfo.has("curr_sell")) { + if (bazaarInfo != null && bazaarInfo.has("curr_sell")) { bazaarPrice = bazaarInfo.get("curr_sell").getAsFloat(); } - if(bazaarPrice < 5000000 && internal.equals("RECOMBOBULATOR_3000")) bazaarPrice = 5000000; + if (bazaarPrice < 5000000 && internal.equals("RECOMBOBULATOR_3000")) bazaarPrice = 5000000; float worth = -1; - if(bazaarPrice > 0) { + if (bazaarPrice > 0) { worth = bazaarPrice; } else { - switch(NotEnoughUpdates.INSTANCE.config.dungeons.profitType) { + switch (NotEnoughUpdates.INSTANCE.config.dungeons.profitType) { case 1: worth = neu.manager.auctionManager.getItemAvgBin(internal); break; case 2: JsonObject auctionInfo = neu.manager.auctionManager.getItemAuctionInfo(internal); - if(auctionInfo != null) { - if(auctionInfo.has("clean_price")) { - worth = (int)auctionInfo.get("clean_price").getAsFloat(); + if (auctionInfo != null) { + if (auctionInfo.has("clean_price")) { + worth = (int) auctionInfo.get("clean_price").getAsFloat(); } else { - worth = (int)(auctionInfo.get("price").getAsFloat() / auctionInfo.get("count").getAsFloat()); + worth = (int) (auctionInfo.get("price").getAsFloat() / auctionInfo.get("count").getAsFloat()); } } break; default: worth = neu.manager.auctionManager.getLowestBin(internal); } - if(worth <= 0) { + if (worth <= 0) { worth = neu.manager.auctionManager.getLowestBin(internal); - if(worth <= 0) { + if (worth <= 0) { worth = neu.manager.auctionManager.getItemAvgBin(internal); - if(worth <= 0) { + if (worth <= 0) { JsonObject auctionInfo = neu.manager.auctionManager.getItemAuctionInfo(internal); - if(auctionInfo != null) { - if(auctionInfo.has("clean_price")) { - worth = (int)auctionInfo.get("clean_price").getAsFloat(); + if (auctionInfo != null) { + if (auctionInfo.has("clean_price")) { + worth = (int) auctionInfo.get("clean_price").getAsFloat(); } else { - worth = (int)(auctionInfo.get("price").getAsFloat() / auctionInfo.get("count").getAsFloat()); + worth = (int) (auctionInfo.get("price").getAsFloat() / auctionInfo.get("count").getAsFloat()); } } } @@ -1271,21 +1281,21 @@ public class NEUEventListener { } } - if(worth > 0 && totalValue >= 0) { + if (worth > 0 && totalValue >= 0) { totalValue += worth; String display = item.getDisplayName(); - if(display.contains("Enchanted Book")) { + if (display.contains("Enchanted Book")) { NBTTagCompound tag = item.getTagCompound(); - if(tag != null && tag.hasKey("ExtraAttributes", 10)) { + if (tag != null && tag.hasKey("ExtraAttributes", 10)) { NBTTagCompound ea = tag.getCompoundTag("ExtraAttributes"); NBTTagCompound enchants = ea.getCompoundTag("enchantments"); int highestLevel = -1; - for(String enchname : enchants.getKeySet()) { + for (String enchname : enchants.getKeySet()) { int level = enchants.getInteger(enchname); - if(level > highestLevel) { - display = EnumChatFormatting.BLUE+WordUtils.capitalizeFully( + if (level > highestLevel) { + display = EnumChatFormatting.BLUE + WordUtils.capitalizeFully( enchname.replace("_", " ") .replace("Ultimate", "") .trim()) + " " + level; @@ -1296,7 +1306,7 @@ public class NEUEventListener { itemValues.put(display, worth); } else { - if(totalValue != -1) { + if (totalValue != -1) { missingItem = internal; } totalValue = -1; @@ -1307,32 +1317,32 @@ public class NEUEventListener { NumberFormat format = NumberFormat.getInstance(Locale.US); String valueStringBIN1; String valueStringBIN2; - if(totalValue >= 0) { - valueStringBIN1 = EnumChatFormatting.YELLOW+"Value (BIN): "; + if (totalValue >= 0) { + valueStringBIN1 = EnumChatFormatting.YELLOW + "Value (BIN): "; valueStringBIN2 = EnumChatFormatting.GOLD + format.format(totalValue) + " coins"; } else { - valueStringBIN1 = EnumChatFormatting.YELLOW+"Can't find BIN: "; + valueStringBIN1 = EnumChatFormatting.YELLOW + "Can't find BIN: "; valueStringBIN2 = missingItem; } int profitLossBIN = totalValue - chestCost; - String profitPrefix = EnumChatFormatting.DARK_GREEN.toString(); + String profitPrefix = EnumChatFormatting.DARK_GREEN.toString(); String lossPrefix = EnumChatFormatting.RED.toString(); String prefix = profitLossBIN >= 0 ? profitPrefix : lossPrefix; String plStringBIN; - if(profitLossBIN >= 0) { + if (profitLossBIN >= 0) { plStringBIN = prefix + "+" + format.format(profitLossBIN) + " coins"; } else { plStringBIN = prefix + "-" + format.format(-profitLossBIN) + " coins"; } - if(NotEnoughUpdates.INSTANCE.config.dungeons.profitDisplayLoc == 1 && !valueStringBIN2.equals(missingItem)) { + if (NotEnoughUpdates.INSTANCE.config.dungeons.profitDisplayLoc == 1 && !valueStringBIN2.equals(missingItem)) { int w = Minecraft.getMinecraft().fontRendererObj.getStringWidth(plStringBIN); GlStateManager.disableLighting(); GlStateManager.translate(0, 0, 200); - Minecraft.getMinecraft().fontRendererObj.drawString(plStringBIN, guiLeft+xSize-5-w, guiTop+5, + Minecraft.getMinecraft().fontRendererObj.drawString(plStringBIN, guiLeft + xSize - 5 - w, guiTop + 5, 0xffffffff, true); GlStateManager.translate(0, 0, -200); return; @@ -1341,36 +1351,36 @@ public class NEUEventListener { Minecraft.getMinecraft().getTextureManager().bindTexture(dungeon_chest_worth); GL11.glColor4f(1, 1, 1, 1); GlStateManager.disableLighting(); - Utils.drawTexturedRect(guiLeft+xSize+4, guiTop, 180, 101, 0, 180/256f, 0, 101/256f, GL11.GL_NEAREST); + Utils.drawTexturedRect(guiLeft + xSize + 4, guiTop, 180, 101, 0, 180 / 256f, 0, 101 / 256f, GL11.GL_NEAREST); Utils.renderAlignedString(valueStringBIN1, valueStringBIN2, - guiLeft+xSize+4+10, guiTop+14, 160); - if(totalValue >= 0) { - Utils.renderAlignedString(EnumChatFormatting.YELLOW+"Profit/Loss: ", plStringBIN, - guiLeft+xSize+4+10, guiTop+24, 160); + guiLeft + xSize + 4 + 10, guiTop + 14, 160); + if (totalValue >= 0) { + Utils.renderAlignedString(EnumChatFormatting.YELLOW + "Profit/Loss: ", plStringBIN, + guiLeft + xSize + 4 + 10, guiTop + 24, 160); } - int index=0; - for(Map.Entry entry : itemValues.entrySet()) { - Utils.renderAlignedString(entry.getKey(), prefix+ + int index = 0; + for (Map.Entry entry : itemValues.entrySet()) { + Utils.renderAlignedString(entry.getKey(), prefix + format.format(entry.getValue().intValue()), - guiLeft+xSize+4+10, guiTop+29+(++index)*10, 160); + guiLeft + xSize + 4 + 10, guiTop + 29 + (++index) * 10, 160); } } - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); } } } public void drawStringShadow(String str, float x, float y, int len) { - for(int xOff=-2; xOff<=2; xOff++) { - for(int yOff=-2; yOff<=2; yOff++) { - if(Math.abs(xOff) != Math.abs(yOff)) { + for (int xOff = -2; xOff <= 2; xOff++) { + for (int yOff = -2; yOff <= 2; yOff++) { + if (Math.abs(xOff) != Math.abs(yOff)) { Utils.drawStringCenteredScaledMaxWidth(Utils.cleanColourNotModifiers(str), Minecraft.getMinecraft().fontRendererObj, - x+xOff/2f, y+yOff/2f, false, len, - new Color(20, 20, 20, 100/Math.max(Math.abs(xOff), Math.abs(yOff))).getRGB()); + x + xOff / 2f, y + yOff / 2f, false, len, + new Color(20, 20, 20, 100 / Math.max(Math.abs(xOff), Math.abs(yOff))).getRGB()); } } } @@ -1384,11 +1394,12 @@ public class NEUEventListener { /** * Sends a mouse event to NEUOverlay if the inventory isn't hovered AND focused. * Will also cancel the event if if NEUOverlay#mouseInput returns true. + * * @param event */ @SubscribeEvent(priority = EventPriority.LOW) public void onGuiScreenMouse(GuiScreenEvent.MouseInputEvent.Pre event) { - if(Mouse.getEventButtonState() && StorageManager.getInstance().onAnyClick()) { + if (Mouse.getEventButtonState() && StorageManager.getInstance().onAnyClick()) { event.setCanceled(true); return; } @@ -1399,21 +1410,21 @@ public class NEUEventListener { int mouseX = Mouse.getX() * scaledWidth / Minecraft.getMinecraft().displayWidth; int mouseY = scaledHeight - Mouse.getY() * scaledHeight / Minecraft.getMinecraft().displayHeight - 1; - if(AuctionBINWarning.getInstance().shouldShow()) { + if (AuctionBINWarning.getInstance().shouldShow()) { AuctionBINWarning.getInstance().mouseInput(mouseX, mouseY); event.setCanceled(true); return; } - if(!event.isCanceled()) { + if (!event.isCanceled()) { Utils.scrollTooltip(Mouse.getEventDWheel()); } - if(AuctionSearchOverlay.shouldReplace()) { + if (AuctionSearchOverlay.shouldReplace()) { AuctionSearchOverlay.mouseEvent(); event.setCanceled(true); return; } - if(RancherBootOverlay.shouldReplace()) { + if (RancherBootOverlay.shouldReplace()) { RancherBootOverlay.mouseEvent(); event.setCanceled(true); return; @@ -1421,17 +1432,17 @@ public class NEUEventListener { String containerName = null; GuiScreen guiScreen = Minecraft.getMinecraft().currentScreen; - if(guiScreen instanceof GuiChest) { + if (guiScreen instanceof GuiChest) { GuiChest eventGui = (GuiChest) guiScreen; ContainerChest cc = (ContainerChest) eventGui.inventorySlots; containerName = cc.getLowerChestInventory().getDisplayName().getUnformattedText(); - if(containerName.contains(" Profile") && BetterContainers.profileViewerStackIndex != -1 && + if (containerName.contains(" Profile") && BetterContainers.profileViewerStackIndex != -1 && eventGui.isMouseOverSlot(cc.inventorySlots.get(BetterContainers.profileViewerStackIndex), mouseX, mouseY) && Mouse.getEventButton() >= 0) { event.setCanceled(true); - if(Mouse.getEventButtonState() && eventGui.inventorySlots.inventorySlots.get(22).getStack() != null && - eventGui.inventorySlots.inventorySlots.get(22).getStack().getTagCompound() != null){ + if (Mouse.getEventButtonState() && eventGui.inventorySlots.inventorySlots.get(22).getStack() != null && + eventGui.inventorySlots.inventorySlots.get(22).getStack().getTagCompound() != null) { NBTTagCompound tag = eventGui.inventorySlots.inventorySlots.get(22).getStack().getTagCompound(); - if(tag.hasKey("SkullOwner") && tag.getCompoundTag("SkullOwner").hasKey("Name")){ + if (tag.hasKey("SkullOwner") && tag.getCompoundTag("SkullOwner").hasKey("Name")) { String username = tag.getCompoundTag("SkullOwner").getString("Name"); Utils.playPressSound(); NotEnoughUpdates.INSTANCE.commands.viewProfileRunnable.processCommand(null, new String[]{username}); @@ -1440,7 +1451,7 @@ public class NEUEventListener { } } - if(GuiCustomEnchant.getInstance().shouldOverride(containerName) && + if (GuiCustomEnchant.getInstance().shouldOverride(containerName) && GuiCustomEnchant.getInstance().mouseInput(mouseX, mouseY)) { event.setCanceled(true); return; @@ -1450,28 +1461,28 @@ public class NEUEventListener { boolean storageOverlayActive = StorageManager.getInstance().shouldRenderStorageOverlay(containerName); boolean customAhActive = event.gui instanceof CustomAHGui || neu.manager.auctionManager.customAH.isRenderOverAuctionView(); - if(storageOverlayActive) { - if(StorageOverlay.getInstance().mouseInput(mouseX, mouseY)) { + if (storageOverlayActive) { + if (StorageOverlay.getInstance().mouseInput(mouseX, mouseY)) { event.setCanceled(true); } return; } - if(tradeWindowActive || customAhActive) { + if (tradeWindowActive || customAhActive) { event.setCanceled(true); - if(customAhActive) { + if (customAhActive) { neu.manager.auctionManager.customAH.handleMouseInput(); - } else if(tradeWindowActive) { + } else if (tradeWindowActive) { TradeWindow.handleMouseInput(); } neu.overlay.mouseInput(); return; } - if(shouldRenderOverlay(event.gui) && neu.isOnSkyblock()) { - if(!NotEnoughUpdates.INSTANCE.config.accessoryBag.enableOverlay || !AccessoryBagOverlay.mouseClick()) { - if(!(hoverInv && focusInv)) { - if(neu.overlay.mouseInput()) { + if (shouldRenderOverlay(event.gui) && neu.isOnSkyblock()) { + if (!NotEnoughUpdates.INSTANCE.config.accessoryBag.enableOverlay || !AccessoryBagOverlay.mouseClick()) { + if (!(hoverInv && focusInv)) { + if (neu.overlay.mouseInput()) { event.setCanceled(true); } } else { @@ -1479,15 +1490,15 @@ public class NEUEventListener { } } } - if(event.isCanceled()) return; - if(!doInventoryButtons) return; - if(NotEnoughUpdates.INSTANCE.hasSkyblockScoreboard() && shouldRenderOverlay(event.gui) && Mouse.getEventButton() >= 0 + if (event.isCanceled()) return; + if (!doInventoryButtons) return; + if (NotEnoughUpdates.INSTANCE.hasSkyblockScoreboard() && shouldRenderOverlay(event.gui) && Mouse.getEventButton() >= 0 && event.gui instanceof GuiContainer) { - int xSize = ((GuiContainer)event.gui).xSize; - int ySize = ((GuiContainer)event.gui).ySize; - int guiLeft = ((GuiContainer)event.gui).guiLeft; - int guiTop = ((GuiContainer)event.gui).guiTop; - if(!NEUApi.disableInventoryButtons) { + int xSize = ((GuiContainer) event.gui).xSize; + int ySize = ((GuiContainer) event.gui).ySize; + int guiLeft = ((GuiContainer) event.gui).guiLeft; + int guiTop = ((GuiContainer) event.gui).guiTop; + if (!NEUApi.disableInventoryButtons) { for (NEUConfig.InventoryButton button : NotEnoughUpdates.INSTANCE.config.hidden.inventoryButtons) { if (!button.isActive()) continue; if (button.playerInvOnly && !(event.gui instanceof GuiInventory)) continue; @@ -1538,18 +1549,18 @@ public class NEUEventListener { */ @SubscribeEvent public void onGuiScreenKeyboard(GuiScreenEvent.KeyboardInputEvent.Pre event) { - if(AuctionBINWarning.getInstance().shouldShow()) { + if (AuctionBINWarning.getInstance().shouldShow()) { AuctionBINWarning.getInstance().keyboardInput(); event.setCanceled(true); return; } - if(AuctionSearchOverlay.shouldReplace()) { + if (AuctionSearchOverlay.shouldReplace()) { AuctionSearchOverlay.keyEvent(); event.setCanceled(true); return; } - if(RancherBootOverlay.shouldReplace()) { + if (RancherBootOverlay.shouldReplace()) { RancherBootOverlay.keyEvent(); event.setCanceled(true); return; @@ -1557,16 +1568,16 @@ public class NEUEventListener { String containerName = null; GuiScreen guiScreen = Minecraft.getMinecraft().currentScreen; - if(guiScreen instanceof GuiChest) { + if (guiScreen instanceof GuiChest) { GuiChest eventGui = (GuiChest) guiScreen; ContainerChest cc = (ContainerChest) eventGui.inventorySlots; containerName = cc.getLowerChestInventory().getDisplayName().getUnformattedText(); - if(CraftingOverlay.shouldRender && containerName.equals("Craft Item")){ + if (CraftingOverlay.shouldRender && containerName.equals("Craft Item")) { CraftingOverlay.keyInput(); } } - if(GuiCustomEnchant.getInstance().shouldOverride(containerName) && + if (GuiCustomEnchant.getInstance().shouldOverride(containerName) && GuiCustomEnchant.getInstance().keyboardInput()) { event.setCanceled(true); return; @@ -1576,24 +1587,24 @@ public class NEUEventListener { boolean storageOverlayActive = StorageManager.getInstance().shouldRenderStorageOverlay(containerName); boolean customAhActive = event.gui instanceof CustomAHGui || neu.manager.auctionManager.customAH.isRenderOverAuctionView(); - if(storageOverlayActive) { - if(StorageOverlay.getInstance().keyboardInput()) { + if (storageOverlayActive) { + if (StorageOverlay.getInstance().keyboardInput()) { event.setCanceled(true); return; } } - if(tradeWindowActive || customAhActive) { - if(customAhActive) { - if(neu.manager.auctionManager.customAH.keyboardInput()) { + if (tradeWindowActive || customAhActive) { + if (customAhActive) { + if (neu.manager.auctionManager.customAH.keyboardInput()) { event.setCanceled(true); Minecraft.getMinecraft().dispatchKeypresses(); - } else if(neu.overlay.keyboardInput(focusInv)) { + } else if (neu.overlay.keyboardInput(focusInv)) { event.setCanceled(true); } - } else if(tradeWindowActive) { + } else if (tradeWindowActive) { TradeWindow.keyboardInput(); - if(Keyboard.getEventKey() != Keyboard.KEY_ESCAPE) { + if (Keyboard.getEventKey() != Keyboard.KEY_ESCAPE) { event.setCanceled(true); Minecraft.getMinecraft().dispatchKeypresses(); neu.overlay.keyboardInput(focusInv); @@ -1602,58 +1613,58 @@ public class NEUEventListener { return; } - if(shouldRenderOverlay(event.gui) && neu.isOnSkyblock()) { - if(neu.overlay.keyboardInput(focusInv)) { + if (shouldRenderOverlay(event.gui) && neu.isOnSkyblock()) { + if (neu.overlay.keyboardInput(focusInv)) { event.setCanceled(true); } } - if(NotEnoughUpdates.INSTANCE.config.hidden.dev && NotEnoughUpdates.INSTANCE.config.hidden.enableItemEditing && Minecraft.getMinecraft().theWorld != null && + if (NotEnoughUpdates.INSTANCE.config.hidden.dev && NotEnoughUpdates.INSTANCE.config.hidden.enableItemEditing && Minecraft.getMinecraft().theWorld != null && Keyboard.getEventKey() == Keyboard.KEY_N && Keyboard.getEventKeyState()) { GuiScreen gui = Minecraft.getMinecraft().currentScreen; - if(gui instanceof GuiChest) { + if (gui instanceof GuiChest) { GuiChest eventGui = (GuiChest) event.gui; ContainerChest cc = (ContainerChest) eventGui.inventorySlots; IInventory lower = cc.getLowerChestInventory(); - if(!lower.getDisplayName().getUnformattedText().endsWith("Essence")) return; + if (!lower.getDisplayName().getUnformattedText().endsWith("Essence")) return; - for(int i=0; i= '0' && c <= '9') { + for (char c : after.toCharArray()) { + if (c >= '0' && c <= '9') { costS.append(c); } } int cost = Integer.parseInt(costS.toString()); String[] afterSplit = after.split(" "); - String type = afterSplit[afterSplit.length-2]; + String type = afterSplit[afterSplit.length - 2]; - if(!essenceJson.has(internalname)) { + if (!essenceJson.has(internalname)) { essenceJson.add(internalname, new JsonObject()); } JsonObject obj = essenceJson.get(internalname).getAsJsonObject(); obj.addProperty("type", type); - if(line.startsWith("\u00A77Convert to Dungeon Item")) { + if (line.startsWith("\u00A77Convert to Dungeon Item")) { obj.addProperty("dungeonize", cost); - } else if(line.startsWith("\u00A77Upgrade to")) { + } else if (line.startsWith("\u00A77Upgrade to")) { int stars = 0; - for(char c : line.toCharArray()) { - if(c == '\u272A') stars++; + for (char c : line.toCharArray()) { + if (c == '\u272A') stars++; } - if(stars > 0) { - obj.addProperty(stars+"", cost); + if (stars > 0) { + obj.addProperty(stars + "", cost); } } } @@ -1663,15 +1674,15 @@ public class NEUEventListener { System.out.println(essenceJson); } } - if(NotEnoughUpdates.INSTANCE.config.hidden.dev && NotEnoughUpdates.INSTANCE.config.hidden.enableItemEditing && Minecraft.getMinecraft().theWorld != null && + if (NotEnoughUpdates.INSTANCE.config.hidden.dev && NotEnoughUpdates.INSTANCE.config.hidden.enableItemEditing && Minecraft.getMinecraft().theWorld != null && Keyboard.getEventKey() == Keyboard.KEY_O && Keyboard.getEventKeyState()) { GuiScreen gui = Minecraft.getMinecraft().currentScreen; - if(gui instanceof GuiChest) { + if (gui instanceof GuiChest) { GuiChest eventGui = (GuiChest) event.gui; ContainerChest cc = (ContainerChest) eventGui.inventorySlots; IInventory lower = cc.getLowerChestInventory(); - if(lower.getStackInSlot(23) != null && + if (lower.getStackInSlot(23) != null && lower.getStackInSlot(23).getDisplayName().endsWith("Crafting Table")) { ItemStack res = lower.getStackInSlot(25); String resInternalname = neu.manager.getInternalNameForItem(res); @@ -1685,27 +1696,27 @@ public class NEUEventListener { JOptionPane.PLAIN_MESSAGE, null, new String[]{"Enter"}, "Enter"); resInternalname = tf.getText(); - if(resInternalname.trim().length() == 0) { + if (resInternalname.trim().length() == 0) { return; } JsonObject recipe = new JsonObject(); - String[] x = {"1","2","3"}; - String[] y = {"A","B","C"}; + String[] x = {"1", "2", "3"}; + String[] y = {"A", "B", "C"}; - for(int i=0; i<=18; i+=9) { - for(int j=0; j<3; j++) { - ItemStack stack = lower.getStackInSlot(10+i+j); + for (int i = 0; i <= 18; i += 9) { + for (int j = 0; j < 3; j++) { + ItemStack stack = lower.getStackInSlot(10 + i + j); String internalname = ""; - if(stack != null) { + if (stack != null) { internalname = neu.manager.getInternalNameForItem(stack); - if(!neu.manager.getItemInformation().containsKey(internalname)) { + if (!neu.manager.getItemInformation().containsKey(internalname)) { neu.manager.writeItemToFile(stack); } - internalname += ":"+stack.stackSize; + internalname += ":" + stack.stackSize; } - recipe.addProperty(y[i/9]+x[j], internalname); + recipe.addProperty(y[i / 9] + x[j], internalname); } } @@ -1716,17 +1727,16 @@ public class NEUEventListener { json.addProperty("modver", NotEnoughUpdates.VERSION); try { Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("Added: " + resInternalname)); - neu.manager.writeJsonDefaultDir(json, resInternalname+".json"); + neu.manager.writeJsonDefaultDir(json, resInternalname + ".json"); neu.manager.loadItem(resInternalname); - } catch(IOException e) {} + } catch (IOException ignored) {} } } } } + private final HashSet percentStats = new HashSet<>(); - - private HashSet percentStats = new HashSet<>(); { percentStats.add("bonus_attack_speed"); percentStats.add("crit_damage"); @@ -1744,9 +1754,10 @@ public class NEUEventListener { //just to try and optimize it a bit private int sbaloaded = -1; - private boolean isSbaloaded(){ - if(sbaloaded == -1){ - if(Loader.isModLoaded("skyblockaddons")) { + + private boolean isSbaloaded() { + if (sbaloaded == -1) { + if (Loader.isModLoaded("skyblockaddons")) { sbaloaded = 1; } else { sbaloaded = 0; @@ -1757,33 +1768,34 @@ public class NEUEventListener { @SubscribeEvent(priority = EventPriority.LOW) public void onItemTooltipLow(ItemTooltipEvent event) { - if(!NotEnoughUpdates.INSTANCE.isOnSkyblock()) return; + if (!NotEnoughUpdates.INSTANCE.isOnSkyblock()) return; String internalname = NotEnoughUpdates.INSTANCE.manager.getInternalNameForItem(event.itemStack); - if(internalname == null) { + if (internalname == null) { onItemToolTipInternalNameNull(event); return; } boolean hasEnchantments = event.itemStack.getTagCompound().getCompoundTag("ExtraAttributes").hasKey("enchantments", 10); Set enchantIds = new HashSet<>(); - if(hasEnchantments) enchantIds = event.itemStack.getTagCompound().getCompoundTag("ExtraAttributes").getCompoundTag("enchantments").getKeySet(); + if (hasEnchantments) + enchantIds = event.itemStack.getTagCompound().getCompoundTag("ExtraAttributes").getCompoundTag("enchantments").getKeySet(); JsonObject enchantsConst = Constants.ENCHANTS; JsonArray allItemEnchs = null; Set ignoreFromPool = new HashSet<>(); - if(enchantsConst != null && hasEnchantments && NotEnoughUpdates.INSTANCE.config.tooltipTweaks.missingEnchantList) { + if (enchantsConst != null && hasEnchantments && NotEnoughUpdates.INSTANCE.config.tooltipTweaks.missingEnchantList) { try { JsonArray enchantPools = enchantsConst.get("enchant_pools").getAsJsonArray(); - for(JsonElement element : enchantPools) { + for (JsonElement element : enchantPools) { Set currentPool = new HashSet<>(); - for(JsonElement poolElement : element.getAsJsonArray()) { + for (JsonElement poolElement : element.getAsJsonArray()) { String poolS = poolElement.getAsString(); currentPool.add(poolS); } - for(JsonElement poolElement : element.getAsJsonArray()) { + for (JsonElement poolElement : element.getAsJsonArray()) { String poolS = poolElement.getAsString(); - if(enchantIds.contains(poolS)) { + if (enchantIds.contains(poolS)) { ignoreFromPool.addAll(currentPool); break; } @@ -1792,16 +1804,16 @@ public class NEUEventListener { JsonObject enchantsObj = enchantsConst.get("enchants").getAsJsonObject(); NBTTagCompound tag = event.itemStack.getTagCompound(); - if(tag != null) { + if (tag != null) { NBTTagCompound display = tag.getCompoundTag("display"); if (display.hasKey("Lore", 9)) { NBTTagList list = display.getTagList("Lore", 8); out: for (int i = list.tagCount(); i >= 0; i--) { String line = list.getStringTagAt(i); - for(int j=0; j entry : enchantsObj.entrySet()) { - if(line.contains(Utils.rarityArrC[j] + " " + entry.getKey()) || line.contains(Utils.rarityArrC[j] + " DUNGEON " + entry.getKey())) { + for (int j = 0; j < Utils.rarityArrC.length; j++) { + for (Map.Entry entry : enchantsObj.entrySet()) { + if (line.contains(Utils.rarityArrC[j] + " " + entry.getKey()) || line.contains(Utils.rarityArrC[j] + " DUNGEON " + entry.getKey())) { allItemEnchs = entry.getValue().getAsJsonArray(); break out; } @@ -1810,7 +1822,7 @@ public class NEUEventListener { } } } - } catch(Exception e) {} + } catch (Exception ignored) {} } boolean gotToEnchants = false; @@ -1820,42 +1832,41 @@ public class NEUEventListener { int index = 0; List newTooltip = new ArrayList<>(); - for(String line : event.toolTip) { - if(line.endsWith(EnumChatFormatting.DARK_GRAY+"Reforge Stone") && NotEnoughUpdates.INSTANCE.config.tooltipTweaks.showReforgeStats) { + for (String line : event.toolTip) { + if (line.endsWith(EnumChatFormatting.DARK_GRAY + "Reforge Stone") && NotEnoughUpdates.INSTANCE.config.tooltipTweaks.showReforgeStats) { JsonObject reforgeStones = Constants.REFORGESTONES; - - if(reforgeStones != null && reforgeStones.has(internalname)) { + if (reforgeStones != null && reforgeStones.has(internalname)) { boolean shift = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); - if(!pressedShiftLast && shift) { + if (!pressedShiftLast && shift) { showReforgeStoneStats = !showReforgeStoneStats; } pressedShiftLast = shift; newTooltip.add(line); newTooltip.add(""); - if(!showReforgeStoneStats) { - newTooltip.add(EnumChatFormatting.DARK_GRAY+"[Press SHIFT to show extra info]"); + if (!showReforgeStoneStats) { + newTooltip.add(EnumChatFormatting.DARK_GRAY + "[Press SHIFT to show extra info]"); } else { - newTooltip.add(EnumChatFormatting.DARK_GRAY+"[Press SHIFT to hide extra info]"); + newTooltip.add(EnumChatFormatting.DARK_GRAY + "[Press SHIFT to hide extra info]"); } JsonObject reforgeInfo = reforgeStones.get(internalname).getAsJsonObject(); JsonArray requiredRaritiesArray = reforgeInfo.get("requiredRarities").getAsJsonArray(); - if(showReforgeStoneStats && requiredRaritiesArray.size() > 0) { + if (showReforgeStoneStats && requiredRaritiesArray.size() > 0) { String reforgeName = Utils.getElementAsString(reforgeInfo.get("reforgeName"), ""); String[] requiredRarities = new String[requiredRaritiesArray.size()]; - for(int i=0; i= requiredRarities.length) rarityIndex = requiredRarities.length-1; + if (rarityIndex < 0) rarityIndex = 0; + if (rarityIndex >= requiredRarities.length) rarityIndex = requiredRarities.length - 1; currentRarity = requiredRarities[rarityIndex]; rarity = currentRarity; } @@ -1879,7 +1890,6 @@ public class NEUEventListener { JsonElement statsE = reforgeInfo.get("reforgeStats"); - String rarityFormatted = Utils.rarityArrMap.getOrDefault(rarity, rarity); JsonElement reforgeAbilityE = reforgeInfo.get("reforgeAbility"); @@ -1908,7 +1918,7 @@ public class NEUEventListener { newTooltip.add(EnumChatFormatting.BLUE + "Stats for " + rarityFormatted + "\u00a79: [\u00a7l\u00a7m< \u00a79Switch\u00a7l\u27a1\u00a79]"); - if(statsE != null && statsE.isJsonObject()) { + if (statsE != null && statsE.isJsonObject()) { JsonObject stats = statsE.getAsJsonObject(); JsonElement statsRarE = stats.get(rarity); @@ -1960,50 +1970,49 @@ public class NEUEventListener { } - continue; } - } else if(line.contains("\u00A7cR\u00A76a\u00A7ei\u00A7an\u00A7bb\u00A79o\u00A7dw\u00A79 Rune")) { + } else if (line.contains("\u00A7cR\u00A76a\u00A7ei\u00A7an\u00A7bb\u00A79o\u00A7dw\u00A79 Rune")) { line = line.replace("\u00A7cR\u00A76a\u00A7ei\u00A7an\u00A7bb\u00A79o\u00A7dw\u00A79 Rune", - Utils.chromaString("Rainbow Rune", index, false)+EnumChatFormatting.BLUE); - } else if(hasEnchantments) { - if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && NotEnoughUpdates.INSTANCE.config.tooltipTweaks.missingEnchantList) { + Utils.chromaString("Rainbow Rune", index, false) + EnumChatFormatting.BLUE); + } else if (hasEnchantments) { + if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && NotEnoughUpdates.INSTANCE.config.tooltipTweaks.missingEnchantList) { boolean lineHasEnch = false; - for(String s : enchantIds) { + for (String s : enchantIds) { String enchantName = WordUtils.capitalizeFully(s.replace("_", " ")); - if(line.contains(enchantName)) { + if (line.contains(enchantName)) { lineHasEnch = true; break; } } - if(lineHasEnch) { + if (lineHasEnch) { gotToEnchants = true; } else { - if(gotToEnchants && !passedEnchants && Utils.cleanColour(line).trim().length() == 0) { - if(enchantsConst != null && allItemEnchs != null) { + if (gotToEnchants && !passedEnchants && Utils.cleanColour(line).trim().length() == 0) { + if (enchantsConst != null && allItemEnchs != null) { List missing = new ArrayList<>(); - for(JsonElement enchIdElement : allItemEnchs) { + for (JsonElement enchIdElement : allItemEnchs) { String enchId = enchIdElement.getAsString(); - if(!enchId.startsWith("ultimate_") && !ignoreFromPool.contains(enchId) && !enchantIds.contains(enchId)) { + if (!enchId.startsWith("ultimate_") && !ignoreFromPool.contains(enchId) && !enchantIds.contains(enchId)) { missing.add(enchId); } } newTooltip.add(""); - StringBuilder currentLine = new StringBuilder(EnumChatFormatting.RED+"Missing: "+EnumChatFormatting.GRAY); - for(int i=0; i 40) { + if (currentLine.length() != 0 && (Utils.cleanColour(currentLine.toString()).length() + enchName.length()) > 40) { newTooltip.add(currentLine.toString()); currentLine = new StringBuilder(); } - if(currentLine.length() != 0 && i != 0) { + if (currentLine.length() != 0 && i != 0) { currentLine.append(", ").append(enchName); } else { currentLine.append(EnumChatFormatting.GRAY).append(enchName); } } - if(currentLine.length() != 0) { + if (currentLine.length() != 0) { newTooltip.add(currentLine.toString()); } } @@ -2011,7 +2020,7 @@ public class NEUEventListener { } } } - for(String op : NotEnoughUpdates.INSTANCE.config.hidden.enchantColours) { + for (String op : NotEnoughUpdates.INSTANCE.config.hidden.enchantColours) { List colourOps = GuiEnchantColour.splitter.splitToList(op); String enchantName = GuiEnchantColour.getColourOpIndex(colourOps, 0); String comparator = GuiEnchantColour.getColourOpIndex(colourOps, 1); @@ -2021,21 +2030,23 @@ public class NEUEventListener { int modifierI = GuiEnchantColour.getIntModifier(modifier); - if(enchantName.length() == 0) continue; - if(comparator.length() == 0) continue; - if(comparison.length() == 0) continue; - if(colourCode.length() == 0) continue; + if (enchantName.length() == 0) continue; + if (comparator.length() == 0) continue; + if (comparison.length() == 0) continue; + if (colourCode.length() == 0) continue; int comparatorI = ">=<".indexOf(comparator.charAt(0)); int levelToFind = -1; try { levelToFind = Integer.parseInt(comparison); - } catch(Exception e) { continue; } + } catch (Exception e) { + continue; + } - if(comparatorI < 0) continue; + if (comparatorI < 0) continue; String regexText = "0123456789abcdefz"; - if(isSbaloaded()) { + if (isSbaloaded()) { regexText = regexText + "Z"; } @@ -2045,118 +2056,142 @@ public class NEUEventListener { //9([a-zA-Z ]+?) ([0-9]+|(I|II|III|IV|V|VI|VII|VIII|IX|X))(,|$) Pattern pattern; try { - pattern = Pattern.compile("(\\u00A79|\\u00A7(9|l)\\u00A7d\\u00A7l)(?"+enchantName+") " + + pattern = Pattern.compile("(\\u00A79|\\u00A7(9|l)\\u00A7d\\u00A7l)(?" + enchantName + ") " + "(?[0-9]+|(I|II|III|IV|V|VI|VII|VIII|IX|X|XI|XII|XIII|XIV|XV|XVI|XVII|XVIII|XIX|XX))((\\u00A79)?,|( \\u00A78(?:,?[0-9]+)*)?$)"); - } catch(Exception e) {continue;} //malformed regex + } catch (Exception e) { + continue; + } //malformed regex Matcher matcher = pattern.matcher(line); int matchCount = 0; - while(matcher.find() && matchCount < 5) { - if(Utils.cleanColour(matcher.group("enchantName")).startsWith(" ")) continue; - + while (matcher.find() && matchCount < 5) { + if (Utils.cleanColour(matcher.group("enchantName")).startsWith(" ")) continue; matchCount++; int level = -1; String levelStr = matcher.group("level"); - if(levelStr == null) continue; + if (levelStr == null) continue; try { level = Integer.parseInt(levelStr); - } catch(Exception e) { - switch(levelStr) { + } catch (Exception e) { + switch (levelStr) { case "I": - level = 1; break; + level = 1; + break; case "II": - level = 2; break; + level = 2; + break; case "III": - level = 3; break; + level = 3; + break; case "IV": - level = 4; break; + level = 4; + break; case "V": - level = 5; break; + level = 5; + break; case "VI": - level = 6; break; + level = 6; + break; case "VII": - level = 7; break; + level = 7; + break; case "VIII": - level = 8; break; + level = 8; + break; case "IX": - level = 9; break; + level = 9; + break; case "X": - level = 10; break; + level = 10; + break; case "XI": - level = 11; break; + level = 11; + break; case "XII": - level = 12; break; + level = 12; + break; case "XIII": - level = 13; break; + level = 13; + break; case "XIV": - level = 14; break; + level = 14; + break; case "XV": - level = 15; break; + level = 15; + break; case "XVI": - level = 16; break; + level = 16; + break; case "XVII": - level = 17; break; + level = 17; + break; case "XVIII": - level = 18; break; + level = 18; + break; case "XIX": - level = 19; break; + level = 19; + break; case "XX": - level = 20; break; + level = 20; + break; } } boolean matches = false; - if(level > 0) { - switch(comparator) { + if (level > 0) { + switch (comparator) { case ">": - matches = level > levelToFind; break; + matches = level > levelToFind; + break; case "=": - matches = level == levelToFind; break; + matches = level == levelToFind; + break; case "<": - matches = level < levelToFind; break; + matches = level < levelToFind; + break; } } - if(matches) { + if (matches) { String enchantText = matcher.group("enchantName"); StringBuilder extraModifiersBuilder = new StringBuilder(); - if((modifierI & GuiEnchantColour.BOLD_MODIFIER) != 0) { + if ((modifierI & GuiEnchantColour.BOLD_MODIFIER) != 0) { extraModifiersBuilder.append(EnumChatFormatting.BOLD); } - if((modifierI & GuiEnchantColour.ITALIC_MODIFIER) != 0) { + if ((modifierI & GuiEnchantColour.ITALIC_MODIFIER) != 0) { extraModifiersBuilder.append(EnumChatFormatting.ITALIC); } - if((modifierI & GuiEnchantColour.UNDERLINE_MODIFIER) != 0) { + if ((modifierI & GuiEnchantColour.UNDERLINE_MODIFIER) != 0) { extraModifiersBuilder.append(EnumChatFormatting.UNDERLINE); } - if((modifierI & GuiEnchantColour.OBFUSCATED_MODIFIER) != 0) { + if ((modifierI & GuiEnchantColour.OBFUSCATED_MODIFIER) != 0) { extraModifiersBuilder.append(EnumChatFormatting.OBFUSCATED); } - if((modifierI & GuiEnchantColour.STRIKETHROUGH_MODIFIER) != 0) { + if ((modifierI & GuiEnchantColour.STRIKETHROUGH_MODIFIER) != 0) { extraModifiersBuilder.append(EnumChatFormatting.STRIKETHROUGH); } String extraMods = extraModifiersBuilder.toString(); - if(!colourCode.equals("z")) { - line = line.replace("\u00A79"+enchantText, - "\u00A7"+colourCode+extraMods+enchantText); - line = line.replace("\u00A79\u00A7d\u00A7l"+enchantText, - "\u00A7"+colourCode+extraMods+enchantText); - line = line.replace("\u00A7l\u00A7d\u00A7l"+enchantText, - "\u00A7"+colourCode+extraMods+enchantText); + if (!colourCode.equals("z")) { + line = line.replace("\u00A79" + enchantText, + "\u00A7" + colourCode + extraMods + enchantText); + line = line.replace("\u00A79\u00A7d\u00A7l" + enchantText, + "\u00A7" + colourCode + extraMods + enchantText); + line = line.replace("\u00A7l\u00A7d\u00A7l" + enchantText, + "\u00A7" + colourCode + extraMods + enchantText); } else { int offset = Minecraft.getMinecraft().fontRendererObj.getStringWidth(line.replaceAll( - "\\u00A79"+enchantText+".*", "")); - line = line.replace("\u00A79"+enchantText, Utils.chromaString(enchantText, offset/12f+index, false)); + "\\u00A79" + enchantText + ".*", "")); + line = line.replace("\u00A79" + enchantText, Utils.chromaString(enchantText, offset / 12f + index, false)); offset = Minecraft.getMinecraft().fontRendererObj.getStringWidth(line.replaceAll( - "\\u00A79\\u00A7d\\u00A7l"+enchantText+".*", "")); - line = line.replace("\u00A79\u00A7d\u00A7l"+enchantText, Utils.chromaString(enchantText, - offset/12f+index, true)); + "\\u00A79\\u00A7d\\u00A7l" + enchantText + ".*", "")); + line = line.replace("\u00A79\u00A7d\u00A7l" + enchantText, Utils.chromaString(enchantText, + offset / 12f + index, true)); offset = Minecraft.getMinecraft().fontRendererObj.getStringWidth(line.replaceAll( - "\\u00A7l\\u00A7d\\u00A7l"+enchantText+".*", "")); - line = line.replace("\u00A7l\u00A7d\u00A7l"+enchantText, Utils.chromaString(enchantText, - offset/12f+index, true)); + "\\u00A7l\\u00A7d\\u00A7l" + enchantText + ".*", "")); + line = line.replace("\u00A7l\u00A7d\u00A7l" + enchantText, Utils.chromaString(enchantText, + offset / 12f + index, true)); } } } @@ -2165,25 +2200,24 @@ public class NEUEventListener { newTooltip.add(line); + if (NotEnoughUpdates.INSTANCE.config.tooltipTweaks.showPriceInfoAucItem) { + if (line.contains(EnumChatFormatting.GRAY + "Buy it now: ") || + line.contains(EnumChatFormatting.GRAY + "Bidder: ") || + line.contains(EnumChatFormatting.GRAY + "Starting bid: ")) { - if(NotEnoughUpdates.INSTANCE.config.tooltipTweaks.showPriceInfoAucItem) { - if(line.contains(EnumChatFormatting.GRAY+"Buy it now: ") || - line.contains(EnumChatFormatting.GRAY+"Bidder: ") || - line.contains(EnumChatFormatting.GRAY+"Starting bid: ")) { - - if(!Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && !Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) { + if (!Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && !Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) { newTooltip.add(""); - newTooltip.add(EnumChatFormatting.GRAY+"[SHIFT for Price Info]"); + newTooltip.add(EnumChatFormatting.GRAY + "[SHIFT for Price Info]"); } else { ItemPriceInformation.addToTooltip(newTooltip, internalname, event.itemStack); } } } - if(NotEnoughUpdates.INSTANCE.config.dungeons.profitDisplayLoc == 2 && Minecraft.getMinecraft().currentScreen instanceof GuiChest) { - if(line.contains(EnumChatFormatting.GREEN+"Open Reward Chest")) { + if (NotEnoughUpdates.INSTANCE.config.dungeons.profitDisplayLoc == 2 && Minecraft.getMinecraft().currentScreen instanceof GuiChest) { + if (line.contains(EnumChatFormatting.GREEN + "Open Reward Chest")) { dungeonProfit = true; - } else if(index == 7 && dungeonProfit) { + } else if (index == 7 && dungeonProfit) { GuiChest eventGui = (GuiChest) Minecraft.getMinecraft().currentScreen; ContainerChest cc = (ContainerChest) eventGui.inventorySlots; IInventory lower = cc.getLowerChestInventory(); @@ -2192,64 +2226,64 @@ public class NEUEventListener { try { String line6 = Utils.cleanColour(line); StringBuilder cost = new StringBuilder(); - for(int i=0; i= 0) { + if ("0123456789".indexOf(c) >= 0) { cost.append(c); } } - if(cost.length() > 0) { + if (cost.length() > 0) { chestCost = Integer.parseInt(cost.toString()); } - } catch(Exception ignored) {} + } catch (Exception ignored) {} String missingItem = null; int totalValue = 0; HashMap itemValues = new HashMap<>(); - for(int i=0; i<5; i++) { - ItemStack item = lower.getStackInSlot(11+i); + for (int i = 0; i < 5; i++) { + ItemStack item = lower.getStackInSlot(11 + i); String internal = neu.manager.getInternalNameForItem(item); - if(internal != null) { + if (internal != null) { internal = internal.replace("\u00CD", "I").replace("\u0130", "I"); float bazaarPrice = -1; JsonObject bazaarInfo = neu.manager.auctionManager.getBazaarInfo(internal); - if(bazaarInfo != null && bazaarInfo.has("curr_sell")) { + if (bazaarInfo != null && bazaarInfo.has("curr_sell")) { bazaarPrice = bazaarInfo.get("curr_sell").getAsFloat(); } - if(bazaarPrice < 5000000 && internal.equals("RECOMBOBULATOR_3000")) bazaarPrice = 5000000; + if (bazaarPrice < 5000000 && internal.equals("RECOMBOBULATOR_3000")) bazaarPrice = 5000000; float worth = -1; - if(bazaarPrice > 0) { + if (bazaarPrice > 0) { worth = bazaarPrice; } else { - switch(NotEnoughUpdates.INSTANCE.config.dungeons.profitType) { + switch (NotEnoughUpdates.INSTANCE.config.dungeons.profitType) { case 1: worth = neu.manager.auctionManager.getItemAvgBin(internal); break; case 2: JsonObject auctionInfo = neu.manager.auctionManager.getItemAuctionInfo(internal); - if(auctionInfo != null) { - if(auctionInfo.has("clean_price")) { - worth = (int)auctionInfo.get("clean_price").getAsFloat(); + if (auctionInfo != null) { + if (auctionInfo.has("clean_price")) { + worth = (int) auctionInfo.get("clean_price").getAsFloat(); } else { - worth = (int)(auctionInfo.get("price").getAsFloat() / auctionInfo.get("count").getAsFloat()); + worth = (int) (auctionInfo.get("price").getAsFloat() / auctionInfo.get("count").getAsFloat()); } } break; default: worth = neu.manager.auctionManager.getLowestBin(internal); } - if(worth <= 0) { + if (worth <= 0) { worth = neu.manager.auctionManager.getLowestBin(internal); - if(worth <= 0) { + if (worth <= 0) { worth = neu.manager.auctionManager.getItemAvgBin(internal); - if(worth <= 0) { + if (worth <= 0) { JsonObject auctionInfo = neu.manager.auctionManager.getItemAuctionInfo(internal); - if(auctionInfo != null) { - if(auctionInfo.has("clean_price")) { - worth = (int)auctionInfo.get("clean_price").getAsFloat(); + if (auctionInfo != null) { + if (auctionInfo.has("clean_price")) { + worth = (int) auctionInfo.get("clean_price").getAsFloat(); } else { - worth = (int)(auctionInfo.get("price").getAsFloat() / auctionInfo.get("count").getAsFloat()); + worth = (int) (auctionInfo.get("price").getAsFloat() / auctionInfo.get("count").getAsFloat()); } } } @@ -2257,22 +2291,22 @@ public class NEUEventListener { } } - if(worth > 0 && totalValue >= 0) { + if (worth > 0 && totalValue >= 0) { totalValue += worth; String display = item.getDisplayName(); - if(display.contains("Enchanted Book")) { + if (display.contains("Enchanted Book")) { NBTTagCompound tag = item.getTagCompound(); - if(tag != null && tag.hasKey("ExtraAttributes", 10)) { + if (tag != null && tag.hasKey("ExtraAttributes", 10)) { NBTTagCompound ea = tag.getCompoundTag("ExtraAttributes"); NBTTagCompound enchants = ea.getCompoundTag("enchantments"); int highestLevel = -1; - for(String enchname : enchants.getKeySet()) { + for (String enchname : enchants.getKeySet()) { int level = enchants.getInteger(enchname); - if(level > highestLevel) { - display = EnumChatFormatting.BLUE+WordUtils.capitalizeFully( + if (level > highestLevel) { + display = EnumChatFormatting.BLUE + WordUtils.capitalizeFully( enchname.replace("_", " ") .replace("Ultimate", "") .trim()) + " " + level; @@ -2283,7 +2317,7 @@ public class NEUEventListener { itemValues.put(display, worth); } else { - if(totalValue != -1) { + if (totalValue != -1) { missingItem = internal; } totalValue = -1; @@ -2294,35 +2328,35 @@ public class NEUEventListener { NumberFormat format = NumberFormat.getInstance(Locale.US); String valueStringBIN1; String valueStringBIN2; - if(totalValue >= 0) { - valueStringBIN1 = EnumChatFormatting.YELLOW+"Value (BIN): "; + if (totalValue >= 0) { + valueStringBIN1 = EnumChatFormatting.YELLOW + "Value (BIN): "; valueStringBIN2 = EnumChatFormatting.GOLD + format.format(totalValue) + " coins"; } else { - valueStringBIN1 = EnumChatFormatting.YELLOW+"Can't find BIN: "; + valueStringBIN1 = EnumChatFormatting.YELLOW + "Can't find BIN: "; valueStringBIN2 = missingItem; } int profitLossBIN = totalValue - chestCost; - String profitPrefix = EnumChatFormatting.DARK_GREEN.toString(); + String profitPrefix = EnumChatFormatting.DARK_GREEN.toString(); String lossPrefix = EnumChatFormatting.RED.toString(); String prefix = profitLossBIN >= 0 ? profitPrefix : lossPrefix; String plStringBIN; - if(profitLossBIN >= 0) { + if (profitLossBIN >= 0) { plStringBIN = prefix + "+" + format.format(profitLossBIN) + " coins"; } else { - plStringBIN = prefix + "-"+ format.format(-profitLossBIN) + " coins"; + plStringBIN = prefix + "-" + format.format(-profitLossBIN) + " coins"; } String neu = EnumChatFormatting.YELLOW + "[NEU] "; newTooltip.add(neu + valueStringBIN1 + " " + valueStringBIN2); - if(totalValue >= 0) { - newTooltip.add(neu + EnumChatFormatting.YELLOW+"Profit/Loss: " + plStringBIN); + if (totalValue >= 0) { + newTooltip.add(neu + EnumChatFormatting.YELLOW + "Profit/Loss: " + plStringBIN); } - for(Map.Entry entry : itemValues.entrySet()) { - newTooltip.add(neu + entry.getKey() + prefix+"+"+ + for (Map.Entry entry : itemValues.entrySet()) { + newTooltip.add(neu + entry.getKey() + prefix + "+" + format.format(entry.getValue().intValue())); } } @@ -2331,14 +2365,14 @@ public class NEUEventListener { index++; } - for (int i = newTooltip.size()-1; i >=0; i--) { + for (int i = newTooltip.size() - 1; i >= 0; i--) { String line = Utils.cleanColour(newTooltip.get(i)); for (int i1 = 0; i1 < Utils.rarityArr.length; i1++) { - if(line.equals(Utils.rarityArr[i1])){ - if(i-2 <0){ + if (line.equals(Utils.rarityArr[i1])) { + if (i - 2 < 0) { break; } - newTooltip.addAll(i-1, petToolTipXPExtend(event)); + newTooltip.addAll(i - 1, petToolTipXPExtend(event)); break; } } @@ -2360,27 +2394,23 @@ public class NEUEventListener { hypixelOrder.add("reforge_bonus"); hypixelOrder.add("rarity"); - if(NotEnoughUpdates.INSTANCE.config.tooltipTweaks.showPriceInfoInvItem) { + if (NotEnoughUpdates.INSTANCE.config.tooltipTweaks.showPriceInfoInvItem) { ItemPriceInformation.addToTooltip(event.toolTip, internalname, event.itemStack); } - - - - } - private Pattern xpLevelPattern = Pattern.compile("(.*) (\\xA7e(.*)\\xA76/\\xA7e(.*))"); + private final Pattern xpLevelPattern = Pattern.compile("(.*) (\\xA7e(.*)\\xA76/\\xA7e(.*))"); - private void onItemToolTipInternalNameNull(ItemTooltipEvent event){ + private void onItemToolTipInternalNameNull(ItemTooltipEvent event) { petToolTipXPExtendPetMenu(event); } private List petToolTipXPExtend(ItemTooltipEvent event) { - List tooltipText = new ArrayList(); + List tooltipText = new ArrayList<>(); if (NotEnoughUpdates.INSTANCE.config.tooltipTweaks.petExtendExp) { - if(event.itemStack.getTagCompound().hasKey("DisablePetExp")){ - if(event.itemStack.getTagCompound().getBoolean("DisablePetExp")){ + if (event.itemStack.getTagCompound().hasKey("DisablePetExp")) { + if (event.itemStack.getTagCompound().getBoolean("DisablePetExp")) { return tooltipText; } } @@ -2399,7 +2429,7 @@ public class NEUEventListener { if (petInfo.has("exp") && petInfo.get("exp").isJsonPrimitive()) { JsonPrimitive exp = petInfo.getAsJsonPrimitive("exp"); String petName = NotEnoughUpdates.INSTANCE.manager.getInternalNameForItem(event.itemStack); - //Utils.getRarityFromInt(Utils.checkItemTypePet(event.toolTip))).getAsInt(); + //Utils.getRarityFromInt(Utils.checkItemTypePet(event.toolTip))).getAsInt(); petlevel = GuiProfileViewer.getPetLevel(petName, Utils.getRarityFromInt(Utils.checkItemTypePet(event.toolTip)), exp.getAsLong()); } } @@ -2407,13 +2437,13 @@ public class NEUEventListener { if (petlevel != null) { tooltipText.add(""); - if(petlevel.totalXp > petlevel.maxXP) { - tooltipText.add(EnumChatFormatting.AQUA + "" + EnumChatFormatting.BOLD +"MAX LEVEL"); + if (petlevel.totalXp > petlevel.maxXP) { + tooltipText.add(EnumChatFormatting.AQUA + "" + EnumChatFormatting.BOLD + "MAX LEVEL"); } else { - tooltipText.add(EnumChatFormatting.GRAY+"Progress to Level "+(int)Math.floor(petlevel.level+1)+": "+EnumChatFormatting.YELLOW+Utils.round(petlevel.levelPercentage*100, 1)+"%"); - int levelpercentage = Math.round(petlevel.levelPercentage*20); - tooltipText.add(EnumChatFormatting.DARK_GREEN+String.join("", Collections.nCopies(levelpercentage, "-"))+EnumChatFormatting.WHITE+String.join("", Collections.nCopies(20-levelpercentage, "-"))); - tooltipText.add(EnumChatFormatting.GRAY + "EXP: " + EnumChatFormatting.YELLOW + myFormatter.format(petlevel.levelXp) + + tooltipText.add(EnumChatFormatting.GRAY + "Progress to Level " + (int) Math.floor(petlevel.level + 1) + ": " + EnumChatFormatting.YELLOW + Utils.round(petlevel.levelPercentage * 100, 1) + "%"); + int levelpercentage = Math.round(petlevel.levelPercentage * 20); + tooltipText.add(EnumChatFormatting.DARK_GREEN + String.join("", Collections.nCopies(levelpercentage, "-")) + EnumChatFormatting.WHITE + String.join("", Collections.nCopies(20 - levelpercentage, "-"))); + tooltipText.add(EnumChatFormatting.GRAY + "EXP: " + EnumChatFormatting.YELLOW + myFormatter.format(petlevel.levelXp) + EnumChatFormatting.GOLD + "/" + EnumChatFormatting.YELLOW + myFormatter.format(petlevel.currentLevelRequirement) + " EXP"); } } @@ -2422,7 +2452,7 @@ public class NEUEventListener { } return tooltipText; } - + private static final String petToolTipRegex = "((Farming)|(Combat)|(Fishing)|(Mining)|(Foraging)|(Enchanting)|(Alchemy)) ((Mount)|(Pet)|(Morph)).*"; private void petToolTipXPExtendPetMenu(ItemTooltipEvent event) { @@ -2450,11 +2480,11 @@ public class NEUEventListener { } petlevel = pet.petLevel; - if (petlevel == null||xpLine==-1) { + if (petlevel == null || xpLine == -1) { return; } - event.toolTip.add(xpLine+1, EnumChatFormatting.GRAY + "EXP: " + EnumChatFormatting.YELLOW + myFormatter.format(petlevel.levelXp) + + event.toolTip.add(xpLine + 1, EnumChatFormatting.GRAY + "EXP: " + EnumChatFormatting.YELLOW + myFormatter.format(petlevel.levelXp) + EnumChatFormatting.GOLD + "/" + EnumChatFormatting.YELLOW + myFormatter.format(petlevel.currentLevelRequirement)); } @@ -2466,11 +2496,12 @@ public class NEUEventListener { /** * This makes it so that holding LCONTROL while hovering over an item with NBT will show the NBT of the item. + * * @param event */ @SubscribeEvent public void onItemTooltip(ItemTooltipEvent event) { - if(!neu.isOnSkyblock()) return; + if (!neu.isOnSkyblock()) return; /*if(NotEnoughUpdates.INSTANCE.config.improvedSBMenu.hideEmptyPanes && event.itemStack.getItem().equals(Item.getItemFromBlock(Blocks.stained_glass_pane))) { String first = Utils.cleanColour(event.toolTip.get(0)); @@ -2528,37 +2559,37 @@ public class NEUEventListener { } } }*/ - if(Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) && NotEnoughUpdates.INSTANCE.config.hidden.dev && - event.toolTip.size()>0&&event.toolTip.get(event.toolTip.size()-1).startsWith(EnumChatFormatting.DARK_GRAY + "NBT: ")) { - event.toolTip.remove(event.toolTip.size()-1); + if (Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) && NotEnoughUpdates.INSTANCE.config.hidden.dev && + event.toolTip.size() > 0 && event.toolTip.get(event.toolTip.size() - 1).startsWith(EnumChatFormatting.DARK_GRAY + "NBT: ")) { + event.toolTip.remove(event.toolTip.size() - 1); StringBuilder sb = new StringBuilder(); String nbt = event.itemStack.getTagCompound().toString(); int indent = 0; - for(char c : nbt.toCharArray()) { + for (char c : nbt.toCharArray()) { boolean newline = false; - if(c == '{' || c == '[') { + if (c == '{' || c == '[') { indent++; newline = true; - } else if(c == '}' || c == ']') { + } else if (c == '}' || c == ']') { indent--; sb.append("\n"); - for(int i=0; i itemMap = new TreeMap<>(); + private final TreeMap itemMap = new TreeMap<>(); - private TreeMap>> titleWordMap = new TreeMap<>(); - private TreeMap>> loreWordMap = new TreeMap<>(); + private final TreeMap>> titleWordMap = new TreeMap<>(); + private final TreeMap>> loreWordMap = new TreeMap<>(); public final KeyBinding keybindGive = new KeyBinding("Add item to inventory (Creative-only)", Keyboard.KEY_L, "NotEnoughUpdates"); public final KeyBinding keybindFavourite = new KeyBinding("Set item as favourite", Keyboard.KEY_F, "NotEnoughUpdates"); @@ -52,23 +52,23 @@ public class NEUManager { public final KeyBinding keybindToggleDisplay = new KeyBinding("Toggle NEU overlay", 0, "NotEnoughUpdates"); public final KeyBinding keybindClosePanes = new KeyBinding("Close NEU panes", 0, "NotEnoughUpdates"); public final KeyBinding keybindItemSelect = new KeyBinding("Select Item", -98 /*middle*/, "NotEnoughUpdates"); - public final KeyBinding[] keybinds = new KeyBinding[]{ keybindGive, keybindFavourite, keybindViewUsages, keybindViewRecipe, + public final KeyBinding[] keybinds = new KeyBinding[]{keybindGive, keybindFavourite, keybindViewUsages, keybindViewRecipe, keybindToggleDisplay, keybindClosePanes, keybindItemSelect}; public String viewItemAttemptID = null; public long viewItemAttemptTime = 0; private String currentProfile = ""; - private String currentProfileBackup = ""; + private final String currentProfileBackup = ""; public final HypixelApi hypixelApi = new HypixelApi(); - private Map itemstackCache = new HashMap<>(); + private final Map itemstackCache = new HashMap<>(); - private ExecutorService repoLoaderES = Executors.newSingleThreadExecutor(); + private final ExecutorService repoLoaderES = Executors.newSingleThreadExecutor(); private static String GIT_COMMITS_URL; - private HashMap> usagesMap = new HashMap<>(); + private final HashMap> usagesMap = new HashMap<>(); public String latestRepoCommit = null; @@ -97,25 +97,33 @@ public class NEUManager { } public T getJsonFromFile(File file, Class clazz) { - try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { T obj = gson.fromJson(reader, clazz); return obj; - } catch(Exception e) { return null; } + } catch (Exception e) { + return null; + } } /** * Parses a file in to a JsonObject. */ public JsonObject getJsonFromFile(File file) { - try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { JsonObject json = gson.fromJson(reader, JsonObject.class); return json; - } catch(Exception e) { return null; } + } catch (Exception e) { + return null; + } } public void resetRepo() { - try { Utils.recursiveDelete(new File(configLocation, "repo")); } catch(Exception e) {} - try { new File(configLocation, "currentCommit.json").delete(); } catch(Exception e) {} + try { + Utils.recursiveDelete(new File(configLocation, "repo")); + } catch (Exception ignored) {} + try { + new File(configLocation, "currentCommit.json").delete(); + } catch (Exception ignored) {} } /** @@ -158,27 +166,27 @@ public class NEUManager { repoLoaderES.submit(() -> { JDialog dialog = null; try { - if(NotEnoughUpdates.INSTANCE.config.hidden.autoupdate) { + if (NotEnoughUpdates.INSTANCE.config.hidden.autoupdate) { JOptionPane pane = new JOptionPane("Getting items to download from remote repository."); dialog = pane.createDialog("NotEnoughUpdates Remote Sync"); dialog.setModal(false); - if(NotEnoughUpdates.INSTANCE.config.hidden.dev) dialog.setVisible(true); + if (NotEnoughUpdates.INSTANCE.config.hidden.dev) dialog.setVisible(true); if (Display.isActive()) dialog.toFront(); JsonObject currentCommitJSON = getJsonFromFile(new File(configLocation, "currentCommit.json")); latestRepoCommit = null; - try(Reader inReader = new InputStreamReader(new URL(GIT_COMMITS_URL).openStream())) { + try (Reader inReader = new InputStreamReader(new URL(GIT_COMMITS_URL).openStream())) { JsonObject commits = gson.fromJson(inReader, JsonObject.class); latestRepoCommit = commits.get("sha").getAsString(); } catch (Exception e) { e.printStackTrace(); } - if(latestRepoCommit == null || latestRepoCommit.isEmpty()) return; + if (latestRepoCommit == null || latestRepoCommit.isEmpty()) return; - if(new File(configLocation, "repo").exists() && new File(configLocation, "repo/items").exists()) { - if(currentCommitJSON != null && currentCommitJSON.get("sha").getAsString().equals(latestRepoCommit)) { + if (new File(configLocation, "repo").exists() && new File(configLocation, "repo/items").exists()) { + if (currentCommitJSON != null && currentCommitJSON.get("sha").getAsString().equals(latestRepoCommit)) { dialog.setVisible(false); return; } @@ -189,12 +197,11 @@ public class NEUManager { Utils.recursiveDelete(repoLocation); repoLocation.mkdirs(); - String dlUrl = neu.config.hidden.repoURL; pane.setMessage("Downloading NEU Master Archive. (DL# >20)"); dialog.pack(); - if(NotEnoughUpdates.INSTANCE.config.hidden.dev) dialog.setVisible(true); + if (NotEnoughUpdates.INSTANCE.config.hidden.dev) dialog.setVisible(true); if (Display.isActive()) dialog.toFront(); File itemsZip = new File(repoLocation, "neu-items-master.zip"); @@ -204,13 +211,12 @@ public class NEUManager { return; } - URL url = new URL(dlUrl); URLConnection urlConnection = url.openConnection(); urlConnection.setConnectTimeout(15000); urlConnection.setReadTimeout(30000); - try(InputStream is = urlConnection.getInputStream()) { + try (InputStream is = urlConnection.getInputStream()) { FileUtils.copyInputStreamToFile(is, itemsZip); } catch (IOException e) { dialog.dispose(); @@ -237,29 +243,28 @@ public class NEUManager { unzipIgnoreFirstFolder(itemsZip.getAbsolutePath(), repoLocation.getAbsolutePath()); - if(currentCommitJSON == null || !currentCommitJSON.get("sha").getAsString().equals(latestRepoCommit)) { + if (currentCommitJSON == null || !currentCommitJSON.get("sha").getAsString().equals(latestRepoCommit)) { JsonObject newCurrentCommitJSON = new JsonObject(); newCurrentCommitJSON.addProperty("sha", latestRepoCommit); try { writeJson(newCurrentCommitJSON, new File(configLocation, "currentCommit.json")); - } catch (IOException e) { - } + } catch (IOException ignored) {} } } - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); } finally { - if(dialog != null) dialog.dispose(); + if (dialog != null) dialog.dispose(); } File items = new File(repoLocation, "items"); - if(items.exists()) { + if (items.exists()) { File[] itemFiles = new File(repoLocation, "items").listFiles(); - if(itemFiles != null) { - for(File f : itemFiles) { - String internalname = f.getName().substring(0, f.getName().length()-5); - synchronized(itemMap) { - if(!itemMap.keySet().contains(internalname)) { + if (itemFiles != null) { + for (File f : itemFiles) { + String internalname = f.getName().substring(0, f.getName().length() - 5); + synchronized (itemMap) { + if (!itemMap.containsKey(internalname)) { loadItem(internalname); } } @@ -269,19 +274,19 @@ public class NEUManager { try { Constants.reload(); - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); } }); File items = new File(repoLocation, "items"); - if(items.exists()) { + if (items.exists()) { File[] itemFiles = new File(repoLocation, "items").listFiles(); - if(itemFiles != null) { - for(File f : itemFiles) { - String internalname = f.getName().substring(0, f.getName().length()-5); - synchronized(itemMap) { - if(!itemMap.keySet().contains(internalname)) { + if (itemFiles != null) { + for (File f : itemFiles) { + String internalname = f.getName().substring(0, f.getName().length() - 5); + synchronized (itemMap) { + if (!itemMap.containsKey(internalname)) { loadItem(internalname); } } @@ -291,7 +296,7 @@ public class NEUManager { try { Constants.reload(); - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); } } @@ -299,41 +304,42 @@ public class NEUManager { /** * Loads the item in to the itemMap and also stores various words associated with this item * in to titleWordMap and loreWordMap. These maps are used in the searching algorithm. + * * @param internalName */ public void loadItem(String internalName) { itemstackCache.remove(internalName); try { JsonObject json = getJsonFromFile(new File(new File(repoLocation, "items"), internalName + ".json")); - if(json == null) { + if (json == null) { return; } - if(json.get("itemid") == null) return; + if (json.get("itemid") == null) return; String itemid = json.get("itemid").getAsString(); Item mcitem = Item.getByNameOrId(itemid); - if(mcitem != null) { + if (mcitem != null) { itemid = mcitem.getRegistryName(); } json.addProperty("itemid", itemid); itemMap.put(internalName, json); - if(json.has("recipe")) { - synchronized(usagesMap) { + if (json.has("recipe")) { + synchronized (usagesMap) { JsonObject recipe = json.get("recipe").getAsJsonObject(); - String[] x = {"1","2","3"}; - String[] y = {"A","B","C"}; - for(int i=0; i<9; i++) { - String name = y[i/3]+x[i%3]; + String[] x = {"1", "2", "3"}; + String[] y = {"A", "B", "C"}; + for (int i = 0; i < 9; i++) { + String name = y[i / 3] + x[i % 3]; String itemS = recipe.get(name).getAsString(); - if(itemS != null && itemS.split(":").length == 2) { + if (itemS != null && itemS.split(":").length == 2) { itemS = itemS.split(":")[0]; } - if(!usagesMap.containsKey(itemS)) { + if (!usagesMap.containsKey(itemS)) { usagesMap.put(itemS, new HashSet<>()); } usagesMap.get(itemS).add(internalName); @@ -341,15 +347,15 @@ public class NEUManager { } } - if(json.has("displayname")) { - synchronized(titleWordMap) { - int wordIndex=0; - for(String str : json.get("displayname").getAsString().split(" ")) { + if (json.has("displayname")) { + synchronized (titleWordMap) { + int wordIndex = 0; + for (String str : json.get("displayname").getAsString().split(" ")) { str = clean(str); - if(!titleWordMap.containsKey(str)) { + if (!titleWordMap.containsKey(str)) { titleWordMap.put(str, new HashMap<>()); } - if(!titleWordMap.get(str).containsKey(internalName)) { + if (!titleWordMap.get(str).containsKey(internalName)) { titleWordMap.get(str).put(internalName, new ArrayList<>()); } titleWordMap.get(str).get(internalName).add(wordIndex); @@ -358,16 +364,16 @@ public class NEUManager { } } - if(json.has("lore")) { - synchronized(loreWordMap) { - int wordIndex=0; - for(JsonElement element : json.get("lore").getAsJsonArray()) { - for(String str : element.getAsString().split(" ")) { + if (json.has("lore")) { + synchronized (loreWordMap) { + int wordIndex = 0; + for (JsonElement element : json.get("lore").getAsJsonArray()) { + for (String str : element.getAsString().split(" ")) { str = clean(str); - if(!loreWordMap.containsKey(str)) { + if (!loreWordMap.containsKey(str)) { loreWordMap.put(str, new HashMap<>()); } - if(!loreWordMap.get(str).containsKey(internalName)) { + if (!loreWordMap.get(str).containsKey(internalName)) { loreWordMap.get(str).put(internalName, new ArrayList<>()); } loreWordMap.get(str).get(internalName).add(wordIndex); @@ -376,11 +382,11 @@ public class NEUManager { } } } - } catch(Exception e) { - synchronized(loreWordMap) { + } catch (Exception e) { + synchronized (loreWordMap) { System.out.println("loreWordMap is : " + loreWordMap); } - synchronized(titleWordMap) { + synchronized (titleWordMap) { System.out.println("titleWordMap is : " + titleWordMap); } System.out.println("internalName is : " + internalName); @@ -399,9 +405,9 @@ public class NEUManager { query = clean(query).toLowerCase(); String[] splitToSeach = toSearch.split(" "); out: - for(String s : query.split(" ")) { - for(int i=0; i search(String query, boolean multi) { - if(multi) { + if (multi) { Set result = new HashSet<>(); StringBuilder query2 = new StringBuilder(); char lastOp = '|'; - for(char c : query.toCharArray()) { - if(c == '|' || c == '&') { - if(lastOp == '|') { + for (char c : query.toCharArray()) { + if (c == '|' || c == '&') { + if (lastOp == '|') { result.addAll(search(query2.toString())); - } else if(lastOp == '&') { + } else if (lastOp == '&') { result.retainAll(search(query2.toString())); } @@ -493,9 +499,9 @@ public class NEUManager { query2.append(c); } } - if(lastOp == '|') { + if (lastOp == '|') { result.addAll(search(query2.toString())); - } else if(lastOp == '&') { + } else if (lastOp == '&') { result.retainAll(search(query2.toString())); } @@ -543,22 +549,22 @@ public class NEUManager { public Set search(String query) { query = query.trim(); boolean negate = query.startsWith("!"); - if(negate) query = query.substring(1); + if (negate) query = query.substring(1); LinkedHashSet results = new LinkedHashSet<>(); - if(query.startsWith("title:")) { + if (query.startsWith("title:")) { query = query.substring(6); results.addAll(new TreeSet<>(search(query, titleWordMap))); - } else if(query.startsWith("desc:")) { + } else if (query.startsWith("desc:")) { query = query.substring(5); results.addAll(new TreeSet<>(search(query, loreWordMap))); - } else if(query.startsWith("id:")) { + } else if (query.startsWith("id:")) { query = query.substring(3); results.addAll(new TreeSet<>(subMapWithKeysThatAreSuffixes(query.toUpperCase(), itemMap).keySet())); } else { - if(!query.trim().contains(" ")) { + if (!query.trim().contains(" ")) { StringBuilder sb = new StringBuilder(); - for(char c : query.toCharArray()) { + for (char c : query.toCharArray()) { sb.append(c).append(" "); } results.addAll(new TreeSet<>(search(sb.toString(), titleWordMap))); @@ -566,11 +572,11 @@ public class NEUManager { results.addAll(new TreeSet<>(search(query, titleWordMap))); results.addAll(new TreeSet<>(search(query, loreWordMap))); } - if(!negate) { + if (!negate) { return results; } else { Set negatedResults = new HashSet<>(); - for(String internalname : itemMap.keySet()) { + for (String internalname : itemMap.keySet()) { negatedResults.add(internalname); } negatedResults.removeAll(results); @@ -589,24 +595,24 @@ public class NEUManager { HashMap> matches = null; query = clean(query).toLowerCase(); - for(String queryWord : query.split(" ")) { + for (String queryWord : query.split(" ")) { HashMap> matchesToKeep = new HashMap<>(); - for(HashMap> wordMatches : subMapWithKeysThatAreSuffixes(queryWord, wordMap).values()) { - if(wordMatches != null && !wordMatches.isEmpty()) { - if(matches == null) { + for (HashMap> wordMatches : subMapWithKeysThatAreSuffixes(queryWord, wordMap).values()) { + if (wordMatches != null && !wordMatches.isEmpty()) { + if (matches == null) { //Copy all wordMatches to titleMatches - for(String internalname : wordMatches.keySet()) { - if(!matchesToKeep.containsKey(internalname)) { + for (String internalname : wordMatches.keySet()) { + if (!matchesToKeep.containsKey(internalname)) { matchesToKeep.put(internalname, new ArrayList<>()); } matchesToKeep.get(internalname).addAll(wordMatches.get(internalname)); } } else { - for(String internalname : matches.keySet()) { - if(wordMatches.containsKey(internalname)) { - for(Integer newIndex : wordMatches.get(internalname)) { - if(matches.get(internalname).contains(newIndex-1)) { - if(!matchesToKeep.containsKey(internalname)) { + for (String internalname : matches.keySet()) { + if (wordMatches.containsKey(internalname)) { + for (Integer newIndex : wordMatches.get(internalname)) { + if (matches.get(internalname).contains(newIndex - 1)) { + if (!matchesToKeep.containsKey(internalname)) { matchesToKeep.put(internalname, new ArrayList<>()); } matchesToKeep.get(internalname).add(newIndex); @@ -617,7 +623,7 @@ public class NEUManager { } } } - if(matchesToKeep.isEmpty()) return new HashSet<>(); + if (matchesToKeep.isEmpty()) return new HashSet<>(); matches = matchesToKeep; } @@ -634,11 +640,11 @@ public class NEUManager { } public String createLexicographicallyNextStringOfTheSameLength(String input) { - final int lastCharPosition = input.length()-1; + final int lastCharPosition = input.length() - 1; String inputWithoutLastChar = input.substring(0, lastCharPosition); - char lastChar = input.charAt(lastCharPosition) ; + char lastChar = input.charAt(lastCharPosition); char incrementedLastChar = (char) (lastChar + 1); - return inputWithoutLastChar+incrementedLastChar; + return inputWithoutLastChar + incrementedLastChar; } public JsonObject getJsonFromItemBytes(String item_bytes) { @@ -646,7 +652,7 @@ public class NEUManager { NBTTagCompound tag = CompressedStreamTools.readCompressed(new ByteArrayInputStream(Base64.getDecoder().decode(item_bytes))); //System.out.println(tag.toString()); return getJsonFromNBT(tag); - } catch(IOException e) { + } catch (IOException e) { return null; } } @@ -665,41 +671,47 @@ public class NEUManager { public String getInternalnameFromNBT(NBTTagCompound tag) { String internalname = null; - if(tag != null && tag.hasKey("ExtraAttributes", 10)) { + if (tag != null && tag.hasKey("ExtraAttributes", 10)) { NBTTagCompound ea = tag.getCompoundTag("ExtraAttributes"); - if(ea.hasKey("id", 8)) { + if (ea.hasKey("id", 8)) { internalname = ea.getString("id").replaceAll(":", "-"); } else { return null; } - if("PET".equals(internalname)) { + if ("PET".equals(internalname)) { String petInfo = ea.getString("petInfo"); - if(petInfo.length() > 0) { + if (petInfo.length() > 0) { JsonObject petInfoObject = gson.fromJson(petInfo, JsonObject.class); internalname = petInfoObject.get("type").getAsString(); String tier = petInfoObject.get("tier").getAsString(); - switch(tier) { + switch (tier) { case "COMMON": - internalname += ";0"; break; + internalname += ";0"; + break; case "UNCOMMON": - internalname += ";1"; break; + internalname += ";1"; + break; case "RARE": - internalname += ";2"; break; + internalname += ";2"; + break; case "EPIC": - internalname += ";3"; break; + internalname += ";3"; + break; case "LEGENDARY": - internalname += ";4"; break; + internalname += ";4"; + break; case "MYTHIC": - internalname += ";5"; break; + internalname += ";5"; + break; } } } - if("ENCHANTED_BOOK".equals(internalname)) { + if ("ENCHANTED_BOOK".equals(internalname)) { NBTTagCompound enchants = ea.getCompoundTag("enchantments"); - for(String enchname : enchants.getKeySet()) { + for (String enchname : enchants.getKeySet()) { internalname = enchname.toUpperCase() + ";" + enchants.getInteger(enchname); break; } @@ -713,10 +725,10 @@ public class NEUManager { String[] lore = new String[0]; NBTTagCompound display = tag.getCompoundTag("display"); - if(display.hasKey("Lore", 9)) { + if (display.hasKey("Lore", 9)) { NBTTagList list = display.getTagList("Lore", 8); lore = new String[list.tagCount()]; - for(int k=0; k 0) { + if (lore != null && lore.length > 0) { JsonArray jsonLore = new JsonArray(); for (String line : lore) { jsonLore.add(new JsonPrimitive(line)); @@ -788,7 +800,7 @@ public class NEUManager { } item.addProperty("damage", damage); - if(count > 1) item.addProperty("count", count); + if (count > 1) item.addProperty("count", count); item.addProperty("nbttag", tag.toString()); return item; @@ -800,22 +812,22 @@ public class NEUManager { public void showRecipe(JsonObject item) { ContainerChest container = null; - if(Minecraft.getMinecraft().thePlayer.openContainer instanceof ContainerChest) + if (Minecraft.getMinecraft().thePlayer.openContainer instanceof ContainerChest) container = (ContainerChest) Minecraft.getMinecraft().thePlayer.openContainer; if (item.has("recipe") && container != null && container.getLowerChestInventory().getDisplayName().getUnformattedText().equals("Craft Item")) { CraftingOverlay.updateItem(item); - } else if(item.has("useneucraft") && item.get("useneucraft").getAsBoolean()) { + } else if (item.has("useneucraft") && item.get("useneucraft").getAsBoolean()) { displayGuiItemRecipe(item.get("internalname").getAsString(), ""); - } else if(item.has("clickcommand")) { + } else if (item.has("clickcommand")) { String clickcommand = item.get("clickcommand").getAsString(); - if(clickcommand.equals("viewrecipe")) { + if (clickcommand.equals("viewrecipe")) { neu.sendChatMessage( "/" + clickcommand + " " + item.get("internalname").getAsString().split(";")[0]); viewItemAttemptID = item.get("internalname").getAsString(); viewItemAttemptTime = System.currentTimeMillis(); - } else if(clickcommand.equals("viewpotion")) { + } else if (clickcommand.equals("viewpotion")) { neu.sendChatMessage( "/" + clickcommand + " " + item.get("internalname").getAsString().split(";")[0].toLowerCase()); @@ -833,26 +845,26 @@ public class NEUManager { //Item lore String[] lore = new String[0]; - if(tag.hasKey("display", 10)) { + if (tag.hasKey("display", 10)) { NBTTagCompound display = tag.getCompoundTag("display"); - if(display.hasKey("Lore", 9)) { + if (display.hasKey("Lore", 9)) { NBTTagList list = display.getTagList("Lore", 8); lore = new String[list.tagCount()]; - for(int i=0; i 0 && (lore[lore.length-1].contains("Click to view recipes!") || - lore[lore.length-1].contains("Click to view recipe!"))) { - String[] lore2 = new String[lore.length-2]; - System.arraycopy(lore, 0, lore2, 0, lore.length-2); + if (lore.length > 0 && (lore[lore.length - 1].contains("Click to view recipes!") || + lore[lore.length - 1].contains("Click to view recipe!"))) { + String[] lore2 = new String[lore.length - 2]; + System.arraycopy(lore, 0, lore2, 0, lore.length - 2); lore = lore2; } @@ -863,7 +875,7 @@ public class NEUManager { json.addProperty("damage", stack.getItemDamage()); JsonArray jsonlore = new JsonArray(); - for(String line : lore) { + for (String line : lore) { jsonlore.add(new JsonPrimitive(line)); } json.add("lore", jsonlore); @@ -872,13 +884,13 @@ public class NEUManager { } public String getInternalNameForItem(ItemStack stack) { - if(stack == null) return null; + if (stack == null) return null; NBTTagCompound tag = stack.getTagCompound(); return getInternalnameFromNBT(tag); } public String getUUIDForItem(ItemStack stack) { - if(stack == null) return null; + if (stack == null) return null; NBTTagCompound tag = stack.getTagCompound(); return getUUIDFromNBT(tag); } @@ -886,7 +898,7 @@ public class NEUManager { public void writeItemToFile(ItemStack stack) { String internalname = getInternalNameForItem(stack); - if(internalname == null) { + if (internalname == null) { return; } @@ -896,8 +908,8 @@ public class NEUManager { json.addProperty("modver", NotEnoughUpdates.VERSION); try { - writeJson(json, new File(new File(repoLocation, "items"), internalname+".json")); - } catch (IOException e) {} + writeJson(json, new File(new File(repoLocation, "items"), internalname + ".json")); + } catch (IOException ignored) {} loadItem(internalname); } @@ -907,33 +919,33 @@ public class NEUManager { */ public boolean displayGuiItemUsages(String internalName) { List craftMatrices = new ArrayList<>(); - List results = new ArrayList<>(); + List results = new ArrayList<>(); - if(!usagesMap.containsKey(internalName)) { + if (!usagesMap.containsKey(internalName)) { return false; } - for(String internalNameResult : usagesMap.get(internalName)) { + for (String internalNameResult : usagesMap.get(internalName)) { JsonObject item = getItemInformation().get(internalNameResult); results.add(item); - if(item != null && item.has("recipe")) { + if (item != null && item.has("recipe")) { JsonObject recipe = item.get("recipe").getAsJsonObject(); ItemStack[] craftMatrix = new ItemStack[9]; - String[] x = {"1","2","3"}; - String[] y = {"A","B","C"}; - for(int i=0; i<9; i++) { - String name = y[i/3]+x[i%3]; + String[] x = {"1", "2", "3"}; + String[] y = {"A", "B", "C"}; + for (int i = 0; i < 9; i++) { + String name = y[i / 3] + x[i % 3]; String itemS = recipe.get(name).getAsString(); int count = 1; - if(itemS != null && itemS.split(":").length == 2) { - count = Integer.valueOf(itemS.split(":")[1]); + if (itemS != null && itemS.split(":").length == 2) { + count = Integer.parseInt(itemS.split(":")[1]); itemS = itemS.split(":")[0]; } JsonObject craft = getItemInformation().get(itemS); - if(craft != null) { + if (craft != null) { ItemStack stack = jsonToStack(craft); stack.stackSize = count; craftMatrix[i] = stack; @@ -944,7 +956,7 @@ public class NEUManager { } } - if(craftMatrices.size() > 0) { + if (craftMatrices.size() > 0) { Minecraft.getMinecraft().displayGuiScreen(new GuiItemRecipe("Item Usages", craftMatrices, results, this)); return true; } @@ -956,23 +968,23 @@ public class NEUManager { */ public boolean displayGuiItemRecipe(String internalName, String text) { JsonObject item = getItemInformation().get(internalName); - if(item != null && item.has("recipe")) { + if (item != null && item.has("recipe")) { JsonObject recipe = item.get("recipe").getAsJsonObject(); ItemStack[] craftMatrix = new ItemStack[9]; - String[] x = {"1","2","3"}; - String[] y = {"A","B","C"}; - for(int i=0; i<9; i++) { - String name = y[i/3]+x[i%3]; + String[] x = {"1", "2", "3"}; + String[] y = {"A", "B", "C"}; + for (int i = 0; i < 9; i++) { + String name = y[i / 3] + x[i % 3]; String itemS = recipe.get(name).getAsString(); int count = 1; - if(itemS != null && itemS.split(":").length == 2) { - count = Integer.valueOf(itemS.split(":")[1]); + if (itemS != null && itemS.split(":").length == 2) { + count = Integer.parseInt(itemS.split(":")[1]); itemS = itemS.split(":")[0]; } JsonObject craft = getItemInformation().get(itemS); - if(craft != null) { + if (craft != null) { ItemStack stack = jsonToStack(craft); stack.stackSize = count; craftMatrix[i] = stack; @@ -981,7 +993,7 @@ public class NEUManager { Minecraft.getMinecraft().thePlayer.sendQueue.addToSendQueue(new C0DPacketCloseWindow( Minecraft.getMinecraft().thePlayer.openContainer.windowId)); - Minecraft.getMinecraft().displayGuiScreen(new GuiItemRecipe(text!=null?text:"Item Recipe", + Minecraft.getMinecraft().displayGuiScreen(new GuiItemRecipe(text != null ? text : "Item Recipe", Lists.newArrayList(craftMatrix), Lists.newArrayList(item), this)); return true; } @@ -993,8 +1005,8 @@ public class NEUManager { * unlocked. See NotEnoughUpdates#onGuiChat for where this method is called. */ public boolean failViewItem(String text) { - if(viewItemAttemptID != null && !viewItemAttemptID.isEmpty()) { - if(System.currentTimeMillis() - viewItemAttemptTime < 500) { + if (viewItemAttemptID != null && !viewItemAttemptID.isEmpty()) { + if (System.currentTimeMillis() - viewItemAttemptTime < 500) { return displayGuiItemRecipe(viewItemAttemptID, text); } } @@ -1005,8 +1017,8 @@ public class NEUManager { * Downloads a web file, appending some HTML attributes that makes wikia give us the raw wiki syntax. */ public File getWebFile(String url) { - File f = new File(configLocation, "tmp/"+Base64.getEncoder().encodeToString(url.getBytes())+".html"); - if(f.exists()) { + File f = new File(configLocation, "tmp/" + Base64.getEncoder().encodeToString(url.getBytes()) + ".html"); + if (f.exists()) { return f; } @@ -1017,9 +1029,9 @@ public class NEUManager { } catch (IOException e) { return null; } - try (BufferedInputStream inStream = new BufferedInputStream(new URL(url+"?action=raw&templates=expand").openStream()); + try (BufferedInputStream inStream = new BufferedInputStream(new URL(url + "?action=raw&templates=expand").openStream()); FileOutputStream fileOutputStream = new FileOutputStream(f)) { - byte dataBuffer[] = new byte[1024]; + byte[] dataBuffer = new byte[1024]; int bytesRead; while ((bytesRead = inStream.read(dataBuffer, 0, 1024)) != -1) { fileOutputStream.write(dataBuffer, 0, bytesRead); @@ -1032,14 +1044,13 @@ public class NEUManager { return f; } - /** * Modified from https://www.journaldev.com/960/java-unzip-file-example */ private static void unzipIgnoreFirstFolder(String zipFilePath, String destDir) { File dir = new File(destDir); // create output directory if it doesn't exist - if(!dir.exists()) dir.mkdirs(); + if (!dir.exists()) dir.mkdirs(); FileInputStream fis; //buffer for read and write data to file byte[] buffer = new byte[1024]; @@ -1047,10 +1058,10 @@ public class NEUManager { fis = new FileInputStream(zipFilePath); ZipInputStream zis = new ZipInputStream(fis); ZipEntry ze = zis.getNextEntry(); - while(ze != null){ - if(!ze.isDirectory()) { + while (ze != null) { + if (!ze.isDirectory()) { String fileName = ze.getName(); - fileName = fileName.substring(fileName.split("/")[0].length()+1); + fileName = fileName.substring(fileName.split("/")[0].length() + 1); File newFile = new File(destDir + File.separator + fileName); //create directories for sub directories in zip new File(newFile.getParent()).mkdirs(); @@ -1083,8 +1094,8 @@ public class NEUManager { try { ZipInputStream zis = new ZipInputStream(src); ZipEntry ze = zis.getNextEntry(); - while(ze != null){ - if(!ze.isDirectory()) { + while (ze != null) { + if (!ze.isDirectory()) { String fileName = ze.getName(); File newFile = new File(dest, fileName); //create directories for sub directories in zip @@ -1121,7 +1132,7 @@ public class NEUManager { public JsonObject createItemJson(JsonObject base, String internalname, String itemid, String displayname, String[] lore, String crafttext, String infoType, String[] info, String clickcommand, int damage, NBTTagCompound nbttag) { - if(internalname == null || internalname.isEmpty()) { + if (internalname == null || internalname.isEmpty()) { return null; } @@ -1134,9 +1145,9 @@ public class NEUManager { json.addProperty("damage", damage); json.addProperty("nbttag", nbttag.toString()); json.addProperty("modver", NotEnoughUpdates.VERSION); - json.addProperty("infoType", infoType.toString()); + json.addProperty("infoType", infoType); - if(info != null && info.length > 0) { + if (info != null && info.length > 0) { JsonArray jsoninfo = new JsonArray(); for (String line : info) { jsoninfo.add(new JsonPrimitive(line)); @@ -1145,7 +1156,7 @@ public class NEUManager { } JsonArray jsonlore = new JsonArray(); - for(String line : lore) { + for (String line : lore) { jsonlore.add(new JsonPrimitive(line)); } json.add("lore", jsonlore); @@ -1161,13 +1172,13 @@ public class NEUManager { public boolean writeItemJson(JsonObject base, String internalname, String itemid, String displayname, String[] lore, String crafttext, String infoType, String[] info, String clickcommand, int damage, NBTTagCompound nbttag) { JsonObject json = createItemJson(base, internalname, itemid, displayname, lore, crafttext, infoType, info, clickcommand, damage, nbttag); - if(json == null) { + if (json == null) { return false; } try { - writeJsonDefaultDir(json, internalname+".json"); - } catch(IOException e) { + writeJsonDefaultDir(json, internalname + ".json"); + } catch (IOException e) { return false; } @@ -1178,7 +1189,7 @@ public class NEUManager { public void writeJson(JsonObject json, File file) throws IOException { file.createNewFile(); - try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) { + try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) { writer.write(gson.toJson(json)); } } @@ -1193,8 +1204,8 @@ public class NEUManager { } public String removeUnusedDecimal(double num) { - if(num % 1 == 0) { - return String.valueOf((int)num); + if (num % 1 == 0) { + return String.valueOf((int) num); } else { return String.valueOf(num); } @@ -1202,58 +1213,57 @@ public class NEUManager { public HashMap getLoreReplacements(String petname, String tier, int level) { JsonObject petnums = null; - if(petname != null && tier != null) { + if (petname != null && tier != null) { petnums = Constants.PETNUMS; } HashMap replacements = new HashMap<>(); - if(level < 1) { - if (Constants.PETS.has("custom_pet_leveling") && Constants.PETS.getAsJsonObject("custom_pet_leveling").has(petname) && Constants.PETS.getAsJsonObject("custom_pet_leveling").getAsJsonObject(petname).has("max_level")){ + if (level < 1) { + if (Constants.PETS.has("custom_pet_leveling") && Constants.PETS.getAsJsonObject("custom_pet_leveling").has(petname) && Constants.PETS.getAsJsonObject("custom_pet_leveling").getAsJsonObject(petname).has("max_level")) { int maxLvl = Constants.PETS.getAsJsonObject("custom_pet_leveling").getAsJsonObject(petname).get("max_level").getAsInt(); - replacements.put("LVL", "1\u27A1"+maxLvl); + replacements.put("LVL", "1\u27A1" + maxLvl); } else { replacements.put("LVL", "1\u27A1100"); } } else { - replacements.put("LVL", ""+level); + replacements.put("LVL", "" + level); } - - if(petnums != null) { - if(petnums.has(petname)) { + if (petnums != null) { + if (petnums.has(petname)) { JsonObject petInfo = petnums.get(petname).getAsJsonObject(); - if(petInfo.has(tier)) { + if (petInfo.has(tier)) { JsonObject petInfoTier = petInfo.get(tier).getAsJsonObject(); - if(petInfoTier == null || !petInfoTier.has("1") || !petInfoTier.has("100")) { + if (petInfoTier == null || !petInfoTier.has("1") || !petInfoTier.has("100")) { return replacements; } JsonObject min = petInfoTier.get("1").getAsJsonObject(); JsonObject max = petInfoTier.get("100").getAsJsonObject(); - if(level < 1) { + if (level < 1) { JsonArray otherNumsMin = min.get("otherNums").getAsJsonArray(); JsonArray otherNumsMax = max.get("otherNums").getAsJsonArray(); boolean addZero = false; - if(petInfoTier.has("stats_levelling_curve")){ + if (petInfoTier.has("stats_levelling_curve")) { String[] stringArray = petInfoTier.get("stats_levelling_curve").getAsString().split(":"); - if(stringArray.length == 3) { + if (stringArray.length == 3) { int type = Integer.parseInt(stringArray[2]); - if(type == 1){ + if (type == 1) { addZero = true; } } } - for(int i=0; i entry : max.get("statNums").getAsJsonObject().entrySet()) { - int statMax = (int)Math.floor(entry.getValue().getAsFloat()); - int statMin = (int)Math.floor(min.get("statNums").getAsJsonObject().get(entry.getKey()).getAsFloat()); - String statStr = (statMin>0?"+":"")+statMin+"\u27A1"+statMax; - statStr = (addZero?"0\u27A1":"")+statStr; + for (Map.Entry entry : max.get("statNums").getAsJsonObject().entrySet()) { + int statMax = (int) Math.floor(entry.getValue().getAsFloat()); + int statMin = (int) Math.floor(min.get("statNums").getAsJsonObject().get(entry.getKey()).getAsFloat()); + String statStr = (statMin > 0 ? "+" : "") + statMin + "\u27A1" + statMax; + statStr = (addZero ? "0\u27A1" : "") + statStr; replacements.put(entry.getKey(), statStr); } } else { @@ -1264,8 +1274,7 @@ public class NEUManager { int statsLevel = level; - - if(petInfoTier.has("stats_levelling_curve")) { + if (petInfoTier.has("stats_levelling_curve")) { String[] stringArray = petInfoTier.get("stats_levelling_curve").getAsString().split(":"); if (stringArray.length == 3) { minStatsLevel = Integer.parseInt(stringArray[0]); @@ -1287,22 +1296,22 @@ public class NEUManager { } } } - float minMix = (maxStatsLevel-(minStatsLevel-(statsLevelingType==-1?0:1))-statsLevel)/99f; - float maxMix = (statsLevel-1)/99f; + float minMix = (maxStatsLevel - (minStatsLevel - (statsLevelingType == -1 ? 0 : 1)) - statsLevel) / 99f; + float maxMix = (statsLevel - 1) / 99f; JsonArray otherNumsMin = min.get("otherNums").getAsJsonArray(); JsonArray otherNumsMax = max.get("otherNums").getAsJsonArray(); - for(int i=0; i entry : max.get("statNums").getAsJsonObject().entrySet()) { - if(statsLevelingType == 1 && level < minStatsLevel) { + for (Map.Entry entry : max.get("statNums").getAsJsonObject().entrySet()) { + if (statsLevelingType == 1 && level < minStatsLevel) { replacements.put(entry.getKey(), "0"); } else { float statMax = entry.getValue().getAsFloat(); @@ -1323,27 +1332,32 @@ public class NEUManager { public HashMap getLoreReplacements(NBTTagCompound tag, int level) { String petname = null; String tier = null; - if(tag != null && tag.hasKey("ExtraAttributes")) { + if (tag != null && tag.hasKey("ExtraAttributes")) { NBTTagCompound ea = tag.getCompoundTag("ExtraAttributes"); - if(ea.hasKey("petInfo")) { + if (ea.hasKey("petInfo")) { String petInfoStr = ea.getString("petInfo"); JsonObject petInfo = gson.fromJson(petInfoStr, JsonObject.class); petname = petInfo.get("type").getAsString(); tier = petInfo.get("tier").getAsString(); - if(petInfo.has("heldItem")) { + if (petInfo.has("heldItem")) { String heldItem = petInfo.get("heldItem").getAsString(); - if(heldItem.equals("PET_ITEM_TIER_BOOST")) { - switch(tier) { + if (heldItem.equals("PET_ITEM_TIER_BOOST")) { + switch (tier) { case "COMMON": - tier = "UNCOMMON"; break; + tier = "UNCOMMON"; + break; case "UNCOMMON": - tier = "RARE"; break; + tier = "RARE"; + break; case "RARE": - tier = "EPIC"; break; + tier = "EPIC"; + break; case "EPIC": - tier = "LEGENDARY"; break; + tier = "LEGENDARY"; + break; case "LEGENDARY": - tier = "MYTHIC"; break; + tier = "MYTHIC"; + break; } } } @@ -1354,12 +1368,12 @@ public class NEUManager { public NBTTagList processLore(JsonArray lore, HashMap replacements) { NBTTagList nbtLore = new NBTTagList(); - for(JsonElement line : lore) { + for (JsonElement line : lore) { String lineStr = line.getAsString(); - if(!lineStr.contains("Click to view recipes!") && + if (!lineStr.contains("Click to view recipes!") && !lineStr.contains("Click to view recipe!")) { - for(Map.Entry entry : replacements.entrySet()) { - lineStr = lineStr.replace("{"+entry.getKey()+"}", entry.getValue()); + for (Map.Entry entry : replacements.entrySet()) { + lineStr = lineStr.replace("{" + entry.getKey() + "}", entry.getValue()); } nbtLore.appendTag(new NBTTagString(lineStr)); } @@ -1380,13 +1394,13 @@ public class NEUManager { } public ItemStack jsonToStack(JsonObject json, boolean useCache, boolean useReplacements, boolean copyStack) { - if(json == null) return new ItemStack(Items.painting, 1, 10); + if (json == null) return new ItemStack(Items.painting, 1, 10); String internalname = json.get("internalname").getAsString(); - if(useCache) { + if (useCache) { ItemStack stack = itemstackCache.get(internalname); - if(stack != null) { - if(copyStack) { + if (stack != null) { + if (copyStack) { return stack.copy(); } else { return stack; @@ -1397,40 +1411,39 @@ public class NEUManager { ItemStack stack = new ItemStack(Item.itemRegistry.getObject( new ResourceLocation(json.get("itemid").getAsString()))); - if(json.has("count")) { + if (json.has("count")) { stack.stackSize = json.get("count").getAsInt(); } - if(stack.getItem() == null) { + if (stack.getItem() == null) { stack = new ItemStack(Item.getItemFromBlock(Blocks.stone), 0, 255); //Purple broken texture item } else { - if(json.has("damage")) { + if (json.has("damage")) { stack.setItemDamage(json.get("damage").getAsInt()); } - if(json.has("nbttag")) { + if (json.has("nbttag")) { try { NBTTagCompound tag = JsonToNBT.getTagFromJson(json.get("nbttag").getAsString()); stack.setTagCompound(tag); - } catch(NBTException e) { - } + } catch (NBTException ignored) {} } HashMap replacements = new HashMap<>(); - if(useReplacements) { + if (useReplacements) { replacements = getLoreReplacements(stack.getTagCompound(), -1); String displayname = json.get("displayname").getAsString(); - for(Map.Entry entry : replacements.entrySet()) { - displayname = displayname.replace("{"+entry.getKey()+"}", entry.getValue()); + for (Map.Entry entry : replacements.entrySet()) { + displayname = displayname.replace("{" + entry.getKey() + "}", entry.getValue()); } stack.setStackDisplayName(displayname); } - if(json.has("lore")) { + if (json.has("lore")) { NBTTagCompound display = new NBTTagCompound(); - if(stack.getTagCompound() != null && stack.getTagCompound().hasKey("display")) { + if (stack.getTagCompound() != null && stack.getTagCompound().hasKey("display")) { display = stack.getTagCompound().getCompoundTag("display"); } display.setTag("Lore", processLore(json.get("lore").getAsJsonArray(), replacements)); @@ -1440,8 +1453,8 @@ public class NEUManager { } } - if(useCache) itemstackCache.put(internalname, stack); - if(copyStack) { + if (useCache) itemstackCache.put(internalname, stack); + if (copyStack) { return stack.copy(); } else { return stack; diff --git a/src/main/java/io/github/moulberry/notenoughupdates/NEUOverlay.java b/src/main/java/io/github/moulberry/notenoughupdates/NEUOverlay.java index 080353a7..f40c60cd 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/NEUOverlay.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/NEUOverlay.java @@ -8,7 +8,10 @@ import io.github.moulberry.notenoughupdates.auction.CustomAHGui; import io.github.moulberry.notenoughupdates.core.BackgroundBlur; import io.github.moulberry.notenoughupdates.core.GuiScreenElementWrapper; import io.github.moulberry.notenoughupdates.core.util.lerp.LerpingInteger; -import io.github.moulberry.notenoughupdates.infopanes.*; +import io.github.moulberry.notenoughupdates.infopanes.DevInfoPane; +import io.github.moulberry.notenoughupdates.infopanes.HTMLInfoPane; +import io.github.moulberry.notenoughupdates.infopanes.InfoPane; +import io.github.moulberry.notenoughupdates.infopanes.TextInfoPane; import io.github.moulberry.notenoughupdates.itemeditor.NEUItemEditor; import io.github.moulberry.notenoughupdates.mbgui.MBAnchorPoint; import io.github.moulberry.notenoughupdates.mbgui.MBGuiElement; @@ -16,9 +19,14 @@ import io.github.moulberry.notenoughupdates.mbgui.MBGuiGroupAligned; import io.github.moulberry.notenoughupdates.mbgui.MBGuiGroupFloating; import io.github.moulberry.notenoughupdates.miscfeatures.SunTzu; import io.github.moulberry.notenoughupdates.options.NEUConfigEditor; -import io.github.moulberry.notenoughupdates.util.*; +import io.github.moulberry.notenoughupdates.util.Constants; +import io.github.moulberry.notenoughupdates.util.LerpingFloat; +import io.github.moulberry.notenoughupdates.util.SpecialColour; +import io.github.moulberry.notenoughupdates.util.Utils; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.*; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.*; import net.minecraft.client.renderer.block.model.BakedQuad; @@ -66,22 +74,22 @@ public class NEUOverlay extends Gui { private static final ResourceLocation SEARCH_BAR = new ResourceLocation("notenoughupdates:search_bar.png"); private static final ResourceLocation SEARCH_BAR_GOLD = new ResourceLocation("notenoughupdates:search_bar_gold.png"); - private NEUManager manager; + private final NEUManager manager; - private String mobRegex = ".*?((_MONSTER)|(_ANIMAL)|(_MINIBOSS)|(_BOSS)|(_SC))$"; - private String petRegex = ".*?;[0-5]$"; + private final String mobRegex = ".*?((_MONSTER)|(_ANIMAL)|(_MINIBOSS)|(_BOSS)|(_SC))$"; + private final String petRegex = ".*?;[0-5]$"; - private ResourceLocation[] sortIcons = new ResourceLocation[] { - sort_all, sort_mob, sort_pet, sort_tool, sort_armor, sort_accessory + private final ResourceLocation[] sortIcons = new ResourceLocation[]{ + sort_all, sort_mob, sort_pet, sort_tool, sort_armor, sort_accessory }; - private ResourceLocation[] sortIconsActive = new ResourceLocation[] { + private final ResourceLocation[] sortIconsActive = new ResourceLocation[]{ sort_all_active, sort_mob_active, sort_pet_active, sort_tool_active, sort_armor_active, sort_accessory_active }; - private ResourceLocation[] orderIcons = new ResourceLocation[] { + private final ResourceLocation[] orderIcons = new ResourceLocation[]{ order_alphabetical, order_rarity, order_value }; - private ResourceLocation[] orderIconsActive = new ResourceLocation[] { + private final ResourceLocation[] orderIconsActive = new ResourceLocation[]{ order_alphabetical_active, order_rarity_active, order_value_active }; @@ -95,7 +103,7 @@ public class NEUOverlay extends Gui { public static final int ITEM_SIZE = 16; private Color bg = new Color(90, 90, 140, 50); - private Color fg = new Color(100,100,100, 255); + private Color fg = new Color(100, 100, 100, 255); private InfoPane activeInfoPane = null; @@ -113,9 +121,9 @@ public class NEUOverlay extends Gui { private int page = 0; - private LerpingFloat itemPaneOffsetFactor = new LerpingFloat(1); - private LerpingInteger itemPaneTabOffset = new LerpingInteger(20, 50); - private LerpingFloat infoPaneOffsetFactor = new LerpingFloat(0); + private final LerpingFloat itemPaneOffsetFactor = new LerpingFloat(1); + private final LerpingInteger itemPaneTabOffset = new LerpingInteger(20, 50); + private final LerpingFloat infoPaneOffsetFactor = new LerpingFloat(0); public boolean searchMode = false; private long millisLastLeftClick = 0; @@ -131,7 +139,7 @@ public class NEUOverlay extends Gui { private boolean redrawItems = false; private boolean searchBarHasFocus = false; - private GuiTextField textField = new GuiTextField(0, null, 0, 0, 0, 0); + private final GuiTextField textField = new GuiTextField(0, null, 0, 0, 0, 0); private static final int COMPARE_MODE_ALPHABETICAL = 0; private static final int COMPARE_MODE_RARITY = 1; @@ -167,27 +175,27 @@ public class NEUOverlay extends Gui { public int getWidth() { int paddingUnscaled = getPaddingUnscaled(); - return getSearchBarXSize() + 2*paddingUnscaled; + return getSearchBarXSize() + 2 * paddingUnscaled; } public int getHeight() { int paddingUnscaled = getPaddingUnscaled(); - return getSearchBarYSize() + 2*paddingUnscaled; + return getSearchBarYSize() + 2 * paddingUnscaled; } @Override public void mouseClick(float x, float y, int mouseX, int mouseY) { - if(!NotEnoughUpdates.INSTANCE.config.toolbar.searchBar) { + if (!NotEnoughUpdates.INSTANCE.config.toolbar.searchBar) { return; } - if(Mouse.getEventButtonState()) { + if (Mouse.getEventButtonState()) { setSearchBarFocus(true); - if(Mouse.getEventButton() == 1) { //Right mouse button down + if (Mouse.getEventButton() == 1) { //Right mouse button down textField.setText(""); updateSearch(); } else { - if(System.currentTimeMillis() - millisLastLeftClick < 300) { + if (System.currentTimeMillis() - millisLastLeftClick < 300) { searchMode = !searchMode; if (searchMode && NotEnoughUpdates.INSTANCE.config.hidden.firstTimeSearchFocus) { NEUEventListener.displayNotification(Lists.newArrayList( @@ -215,14 +223,14 @@ public class NEUOverlay extends Gui { @Override public void render(float x, float y) { - if(!NotEnoughUpdates.INSTANCE.config.toolbar.searchBar) { + if (!NotEnoughUpdates.INSTANCE.config.toolbar.searchBar) { return; } FontRenderer fr = Minecraft.getMinecraft().fontRendererObj; int paddingUnscaled = getPaddingUnscaled(); GlStateManager.color(1, 1, 1, 1); - if(searchMode) { + if (searchMode) { Minecraft.getMinecraft().getTextureManager().bindTexture(SEARCH_BAR_GOLD); } else { Minecraft.getMinecraft().getTextureManager().bindTexture(SEARCH_BAR); @@ -231,36 +239,36 @@ public class NEUOverlay extends Gui { int w = getWidth(); int h = getHeight(); - for(int yIndex=0; yIndex<=2; yIndex++) { - for(int xIndex=0; xIndex<=2; xIndex++) { + for (int yIndex = 0; yIndex <= 2; yIndex++) { + for (int xIndex = 0; xIndex <= 2; xIndex++) { float uMin = 0; - float uMax = 4/20f; - int partX = (int)x; + float uMax = 4 / 20f; + int partX = (int) x; int partW = 4; - if(xIndex == 1) { + if (xIndex == 1) { partX += 4; - uMin = 4/20f; - uMax = 16/20f; - partW = w-8; - } else if(xIndex == 2) { - partX += w-4; - uMin = 16/20f; - uMax = 20/20f; + uMin = 4 / 20f; + uMax = 16 / 20f; + partW = w - 8; + } else if (xIndex == 2) { + partX += w - 4; + uMin = 16 / 20f; + uMax = 20 / 20f; } float vMin = 0; - float vMax = 4/20f; - int partY = (int)y; + float vMax = 4 / 20f; + int partY = (int) y; int partH = 4; - if(yIndex == 1) { + if (yIndex == 1) { partY += 4; - vMin = 4/20f; - vMax = 16/20f; - partH = h-8; - } else if(yIndex == 2) { - partY += h-4; - vMin = 16/20f; - vMax = 20/20f; + vMin = 4 / 20f; + vMax = 16 / 20f; + partH = h - 8; + } else if (yIndex == 2) { + partY += h - 4; + vMin = 16 / 20f; + vMax = 20 / 20f; } Utils.drawTexturedRect(partX, partY, partW, partH, uMin, uMax, vMin, vMax, GL11.GL_NEAREST); @@ -268,35 +276,35 @@ public class NEUOverlay extends Gui { } //Search bar text - fr.drawString(textField.getText(), (int)x + 5, - (int) y-4 + getHeight()/2, Color.WHITE.getRGB()); + fr.drawString(textField.getText(), (int) x + 5, + (int) y - 4 + getHeight() / 2, Color.WHITE.getRGB()); //Determines position of cursor. Cursor blinks on and off every 500ms. - if(searchBarHasFocus && System.currentTimeMillis()%1000>500) { + if (searchBarHasFocus && System.currentTimeMillis() % 1000 > 500) { String textBeforeCursor = textField.getText().substring(0, textField.getCursorPosition()); int textBeforeCursorWidth = fr.getStringWidth(textBeforeCursor); - drawRect((int)x + 5 + textBeforeCursorWidth, - (int)y-5 + getHeight()/2, - (int)x + 5 + textBeforeCursorWidth+1, - (int)y-4+9 + getHeight()/2, Color.WHITE.getRGB()); + drawRect((int) x + 5 + textBeforeCursorWidth, + (int) y - 5 + getHeight() / 2, + (int) x + 5 + textBeforeCursorWidth + 1, + (int) y - 4 + 9 + getHeight() / 2, Color.WHITE.getRGB()); } String selectedText = textField.getSelectedText(); - if(!selectedText.isEmpty()) { + if (!selectedText.isEmpty()) { int selectionWidth = fr.getStringWidth(selectedText); int leftIndex = Math.min(textField.getCursorPosition(), textField.getSelectionEnd()); String textBeforeSelection = textField.getText().substring(0, leftIndex); int textBeforeSelectionWidth = fr.getStringWidth(textBeforeSelection); - drawRect((int)x + 5 + textBeforeSelectionWidth, - (int)y-5 + getHeight()/2, - (int)x + 5 + textBeforeSelectionWidth + selectionWidth, - (int)y-4+9 + getHeight()/2, Color.LIGHT_GRAY.getRGB()); + drawRect((int) x + 5 + textBeforeSelectionWidth, + (int) y - 5 + getHeight() / 2, + (int) x + 5 + textBeforeSelectionWidth + selectionWidth, + (int) y - 4 + 9 + getHeight() / 2, Color.LIGHT_GRAY.getRGB()); fr.drawString(selectedText, - (int)x + 5 + textBeforeSelectionWidth, - (int)y-4 + getHeight()/2, Color.BLACK.getRGB()); + (int) x + 5 + textBeforeSelectionWidth, + (int) y - 4 + getHeight() / 2, Color.BLACK.getRGB()); } } @@ -311,7 +319,7 @@ public class NEUOverlay extends Gui { return new MBGuiElement() { @Override public int getWidth() { - return getSearchBarYSize()+getPaddingUnscaled()*2; + return getSearchBarYSize() + getPaddingUnscaled() * 2; } @Override @@ -325,10 +333,10 @@ public class NEUOverlay extends Gui { @Override public void mouseClick(float x, float y, int mouseX, int mouseY) { - if(!NotEnoughUpdates.INSTANCE.config.toolbar.enableSettingsButton) { + if (!NotEnoughUpdates.INSTANCE.config.toolbar.enableSettingsButton) { return; } - if(Mouse.getEventButtonState()) { + if (Mouse.getEventButtonState()) { NotEnoughUpdates.INSTANCE.openGui = new GuiScreenElementWrapper(NEUConfigEditor.editor); } } @@ -342,8 +350,7 @@ public class NEUOverlay extends Gui { int paddingUnscaled = getPaddingUnscaled(); int searchYSize = getSearchBarYSize(); - - if(!NotEnoughUpdates.INSTANCE.config.toolbar.enableSettingsButton) { + if (!NotEnoughUpdates.INSTANCE.config.toolbar.enableSettingsButton) { return; } Minecraft.getMinecraft().getTextureManager().bindTexture(quickcommand_background); @@ -365,7 +372,7 @@ public class NEUOverlay extends Gui { return new MBGuiElement() { @Override public int getWidth() { - return getSearchBarYSize()+getPaddingUnscaled()*2; + return getSearchBarYSize() + getPaddingUnscaled() * 2; } @Override @@ -379,10 +386,10 @@ public class NEUOverlay extends Gui { @Override public void mouseClick(float x, float y, int mouseX, int mouseY) { - if(!NotEnoughUpdates.INSTANCE.config.toolbar.enableHelpButton){ + if (!NotEnoughUpdates.INSTANCE.config.toolbar.enableHelpButton) { return; } - if(Mouse.getEventButtonState()) { + if (Mouse.getEventButtonState()) { //displayInformationPane(HTMLInfoPane.createFromWikiUrl(overlay, manager, "Help", // "https://moulberry.github.io/files/neu_help.html")); //Minecraft.getMinecraft().displayGuiScreen(new HelpGUI()); @@ -400,7 +407,7 @@ public class NEUOverlay extends Gui { int paddingUnscaled = getPaddingUnscaled(); int searchYSize = getSearchBarYSize(); - if(!NotEnoughUpdates.INSTANCE.config.toolbar.enableHelpButton) { + if (!NotEnoughUpdates.INSTANCE.config.toolbar.enableHelpButton) { return; } @@ -423,7 +430,7 @@ public class NEUOverlay extends Gui { return new MBGuiElement() { @Override public int getWidth() { - return getSearchBarYSize()+getPaddingUnscaled()*2; + return getSearchBarYSize() + getPaddingUnscaled() * 2; } @Override @@ -437,16 +444,16 @@ public class NEUOverlay extends Gui { @Override public void mouseClick(float x, float y, int mouseX, int mouseY) { - if(!NotEnoughUpdates.INSTANCE.config.toolbar.quickCommands) return; + if (!NotEnoughUpdates.INSTANCE.config.toolbar.quickCommands) return; - if((NotEnoughUpdates.INSTANCE.config.toolbar.quickCommandsClickType != 0 && Mouse.getEventButtonState()) || + if ((NotEnoughUpdates.INSTANCE.config.toolbar.quickCommandsClickType != 0 && Mouse.getEventButtonState()) || (NotEnoughUpdates.INSTANCE.config.toolbar.quickCommandsClickType == 0 && !Mouse.getEventButtonState() && Mouse.getEventButton() != -1)) { - if(quickCommandStr.contains(":")) { + if (quickCommandStr.contains(":")) { String command = quickCommandStr.split(":")[0].trim(); - if(command.startsWith("/")) { + if (command.startsWith("/")) { NotEnoughUpdates.INSTANCE.sendChatMessage(command); } else { - ClientCommandHandler.instance.executeCommand(Minecraft.getMinecraft().thePlayer, "/"+command); + ClientCommandHandler.instance.executeCommand(Minecraft.getMinecraft().thePlayer, "/" + command); } Utils.playPressSound(); } @@ -459,19 +466,19 @@ public class NEUOverlay extends Gui { @Override public void render(float x, float y) { - if(!NotEnoughUpdates.INSTANCE.config.toolbar.quickCommands) return; + if (!NotEnoughUpdates.INSTANCE.config.toolbar.quickCommands) return; int paddingUnscaled = getPaddingUnscaled(); int bigItemSize = getSearchBarYSize(); String[] quickCommandStrSplit = quickCommandStr.split(":"); - if(quickCommandStrSplit.length!=3) { + if (quickCommandStrSplit.length != 3) { return; } String display = quickCommandStrSplit[2]; ItemStack render = null; float extraScale = 1; - if(display.length() > 20) { //Custom head + if (display.length() > 20) { //Custom head render = new ItemStack(Items.skull, 1, 3); NBTTagCompound nbt = new NBTTagCompound(); NBTTagCompound skullOwner = new NBTTagCompound(); @@ -492,15 +499,15 @@ public class NEUOverlay extends Gui { render.setTagCompound(nbt); extraScale = 1.3f; - } else if(manager.getItemInformation().containsKey(display)) { + } else if (manager.getItemInformation().containsKey(display)) { render = manager.jsonToStack(manager.getItemInformation().get(display), true, true); } else { Item item = Item.itemRegistry.getObject(new ResourceLocation(display.toLowerCase())); - if(item != null) { + if (item != null) { render = new ItemStack(item); } } - if(render != null) { + if (render != null) { NBTTagCompound tag = render.getTagCompound() != null ? render.getTagCompound() : new NBTTagCompound(); tag.setString("qc_id", quickCommandStrSplit[0].toLowerCase().trim()); render.setTagCompound(tag); @@ -508,24 +515,24 @@ public class NEUOverlay extends Gui { Minecraft.getMinecraft().getTextureManager().bindTexture(quickcommand_background); GlStateManager.color(1, 1, 1, 1); Utils.drawTexturedRect(x, y, - bigItemSize + paddingUnscaled*2, bigItemSize + paddingUnscaled*2, GL11.GL_NEAREST); + bigItemSize + paddingUnscaled * 2, bigItemSize + paddingUnscaled * 2, GL11.GL_NEAREST); int mouseX = Mouse.getX() * Utils.peekGuiScale().getScaledWidth() / Minecraft.getMinecraft().displayWidth; int mouseY = Utils.peekGuiScale().getScaledHeight() - Mouse.getY() * Utils.peekGuiScale().getScaledHeight() / Minecraft.getMinecraft().displayHeight - 1; - if(mouseX > x && mouseX < x+bigItemSize) { - if(mouseY > y && mouseY < y+bigItemSize) { + if (mouseX > x && mouseX < x + bigItemSize) { + if (mouseY > y && mouseY < y + bigItemSize) { textToDisplay = new ArrayList<>(); - textToDisplay.add(EnumChatFormatting.GRAY+quickCommandStrSplit[1]); + textToDisplay.add(EnumChatFormatting.GRAY + quickCommandStrSplit[1]); } } GlStateManager.enableDepth(); - float itemScale = bigItemSize/(float)ITEM_SIZE*extraScale; + float itemScale = bigItemSize / (float) ITEM_SIZE * extraScale; GlStateManager.pushMatrix(); GlStateManager.scale(itemScale, itemScale, 1); - GlStateManager.translate((x-(extraScale-1)*bigItemSize/2+paddingUnscaled) /itemScale, - (y-(extraScale-1)*bigItemSize/2+paddingUnscaled)/itemScale, 0f); + GlStateManager.translate((x - (extraScale - 1) * bigItemSize / 2 + paddingUnscaled) / itemScale, + (y - (extraScale - 1) * bigItemSize / 2 + paddingUnscaled) / itemScale, 0f); Utils.drawItemStack(render, 0, 0); GlStateManager.popMatrix(); } @@ -535,12 +542,12 @@ public class NEUOverlay extends Gui { private MBGuiGroupAligned createQuickCommandGroup() { List children = new ArrayList<>(); - for(String quickCommand : NotEnoughUpdates.INSTANCE.config.hidden.quickCommands) { + for (String quickCommand : NotEnoughUpdates.INSTANCE.config.hidden.quickCommands) { children.add(createQuickCommand(quickCommand)); } return new MBGuiGroupAligned(children, false) { public int getPadding() { - return getPaddingUnscaled()*4; + return getPaddingUnscaled() * 4; } }; } @@ -549,7 +556,7 @@ public class NEUOverlay extends Gui { List children = Lists.newArrayList(createSettingsButton(this), createSearchBar(), createHelpButton(this)); return new MBGuiGroupAligned(children, false) { public int getPadding() { - return getPaddingUnscaled()*4; + return getPaddingUnscaled() * 4; } }; } @@ -564,7 +571,7 @@ public class NEUOverlay extends Gui { new MBAnchorPoint(MBAnchorPoint.AnchorPoint.BOTMID, new Vector2f(0, -searchBarYOffset)); quickCommandAnchor = quickCommandAnchor != null ? quickCommandAnchor : new MBAnchorPoint(MBAnchorPoint.AnchorPoint.BOTMID, new Vector2f(0, - -searchBarYOffset-getSearchBarYSize()-getPaddingUnscaled()*4)); + -searchBarYOffset - getSearchBarYSize() - getPaddingUnscaled() * 4)); map.put(createSearchBarGroup(), searchBarAnchor); map.put(createQuickCommandGroup(), quickCommandAnchor); @@ -576,32 +583,31 @@ public class NEUOverlay extends Gui { MBAnchorPoint searchBarAnchor = MBAnchorPoint.createFromString(NotEnoughUpdates.INSTANCE.config.hidden.overlaySearchBar); MBAnchorPoint quickCommandAnchor = MBAnchorPoint.createFromString(NotEnoughUpdates.INSTANCE.config.hidden.overlayQuickCommand); - if(onlyIfNull) { + if (onlyIfNull) { searchBarAnchor = searchBarAnchor != null ? null : new MBAnchorPoint(MBAnchorPoint.AnchorPoint.BOTMID, new Vector2f(0, -searchBarYOffset)); quickCommandAnchor = quickCommandAnchor != null ? null : new MBAnchorPoint(MBAnchorPoint.AnchorPoint.BOTMID, new Vector2f(0, - -searchBarYOffset-getSearchBarYSize()-getPaddingUnscaled()*4)); + -searchBarYOffset - getSearchBarYSize() - getPaddingUnscaled() * 4)); } else { searchBarAnchor = searchBarAnchor != null ? searchBarAnchor : new MBAnchorPoint(MBAnchorPoint.AnchorPoint.BOTMID, new Vector2f(0, -searchBarYOffset)); quickCommandAnchor = quickCommandAnchor != null ? quickCommandAnchor : new MBAnchorPoint(MBAnchorPoint.AnchorPoint.BOTMID, new Vector2f(0, - -searchBarYOffset-getSearchBarYSize()-getPaddingUnscaled()*4)); + -searchBarYOffset - getSearchBarYSize() - getPaddingUnscaled() * 4)); } - int index = 0; Set set = new LinkedHashSet<>(guiGroup.getChildrenMap().keySet()); - for(MBGuiElement element : set) { - switch(index) { + for (MBGuiElement element : set) { + switch (index) { case 0: - if(searchBarAnchor == null) continue; + if (searchBarAnchor == null) continue; guiGroup.getChildrenMap().get(element).anchorPoint = searchBarAnchor.anchorPoint; guiGroup.getChildrenMap().get(element).offset = searchBarAnchor.offset; break; case 1: - if(quickCommandAnchor == null) continue; + if (quickCommandAnchor == null) continue; guiGroup.getChildrenMap().get(element).anchorPoint = quickCommandAnchor.anchorPoint; guiGroup.getChildrenMap().get(element).offset = quickCommandAnchor.offset; break; @@ -615,12 +621,12 @@ public class NEUOverlay extends Gui { */ public void reset() { searchBarHasFocus = false; - if(!(searchMode || (NotEnoughUpdates.INSTANCE.config.itemlist.keepopen && itemPaneOpen))) { + if (!(searchMode || (NotEnoughUpdates.INSTANCE.config.itemlist.keepopen && itemPaneOpen))) { itemPaneOpen = false; itemPaneOffsetFactor.setValue(1); itemPaneTabOffset.setValue(20); } - if(activeInfoPane != null) activeInfoPane.reset(); + if (activeInfoPane != null) activeInfoPane.reset(); guiGroup.recalculate(); } @@ -628,7 +634,7 @@ public class NEUOverlay extends Gui { * Calls #displayInformationPane with a HTMLInfoPane created from item.info and item.infoType. */ public void showInfo(JsonObject item) { - if(item.has("info") && item.has("infoType")) { + if (item.has("info") && item.has("infoType")) { JsonArray lore = item.get("info").getAsJsonArray(); String[] loreA = new String[lore.size()]; for (int i = 0; i < lore.size(); i++) loreA[i] = lore.get(i).getAsString(); @@ -636,7 +642,7 @@ public class NEUOverlay extends Gui { String internalname = item.get("internalname").getAsString(); String name = item.get("displayname").getAsString(); - switch(item.get("infoType").getAsString()) { + switch (item.get("infoType").getAsString()) { case "WIKI_URL": displayInformationPane(HTMLInfoPane.createFromWikiUrl(this, manager, name, loreS)); return; @@ -652,13 +658,13 @@ public class NEUOverlay extends Gui { } public void mouseInputInv() { - if(Minecraft.getMinecraft().currentScreen instanceof GuiContainer) { - if(Mouse.getEventButton() == manager.keybindItemSelect.getKeyCode()+100 && NotEnoughUpdates.INSTANCE.config.toolbar.searchBar) { - Slot slot = Utils.getSlotUnderMouse((GuiContainer)Minecraft.getMinecraft().currentScreen); - if(slot != null) { + if (Minecraft.getMinecraft().currentScreen instanceof GuiContainer) { + if (Mouse.getEventButton() == manager.keybindItemSelect.getKeyCode() + 100 && NotEnoughUpdates.INSTANCE.config.toolbar.searchBar) { + Slot slot = Utils.getSlotUnderMouse((GuiContainer) Minecraft.getMinecraft().currentScreen); + if (slot != null) { ItemStack hover = slot.getStack(); - if(hover != null) { - textField.setText("id:"+manager.getInternalNameForItem(hover)); + if (hover != null) { + textField.setText("id:" + manager.getInternalNameForItem(hover)); itemPaneOpen = true; updateSearch(); } @@ -671,7 +677,7 @@ public class NEUOverlay extends Gui { * Handles the mouse input, cancelling the forge event if a NEU gui element is clicked. */ public boolean mouseInput() { - if(disabled) { + if (disabled) { return false; } @@ -689,30 +695,30 @@ public class NEUOverlay extends Gui { lastMouseX = mouseX; lastMouseY = mouseY; - if(Mouse.getEventButtonState()) { + if (Mouse.getEventButtonState()) { mouseDown = true; - } else if(Mouse.getEventButton() != -1) { + } else if (Mouse.getEventButton() != -1) { mouseDown = false; } //Unfocuses the search bar by default. Search bar is focused if the click is on the bar itself. - if(Mouse.getEventButtonState()) setSearchBarFocus(false); + if (Mouse.getEventButtonState()) setSearchBarFocus(false); guiGroup.mouseClick(0, 0, mouseX, mouseY); - if(selectedItemGroup != null) { - int selectedX = Math.min(selectedItemGroupX, width-getBoxPadding()-18*selectedItemGroup.size()); - if(mouseY > selectedItemGroupY+17 && mouseY < selectedItemGroupY+35) { - for(int i=0; i= selectedX-1+18*i && mouseX <= selectedX+17+18*i) { + if (selectedItemGroup != null) { + int selectedX = Math.min(selectedItemGroupX, width - getBoxPadding() - 18 * selectedItemGroup.size()); + if (mouseY > selectedItemGroupY + 17 && mouseY < selectedItemGroupY + 35) { + for (int i = 0; i < selectedItemGroup.size(); i++) { + if (mouseX >= selectedX - 1 + 18 * i && mouseX <= selectedX + 17 + 18 * i) { JsonObject item = selectedItemGroup.get(i); if (item != null) { - if(Mouse.getEventButton() == 0) { + if (Mouse.getEventButton() == 0) { manager.showRecipe(item); - } else if(Mouse.getEventButton() == 1) { + } else if (Mouse.getEventButton() == 1) { showInfo(item); - } else if(Mouse.getEventButton() == manager.keybindItemSelect.getKeyCode()+100 && NotEnoughUpdates.INSTANCE.config.toolbar.searchBar) { - textField.setText("id:"+item.get("internalname").getAsString()); + } else if (Mouse.getEventButton() == manager.keybindItemSelect.getKeyCode() + 100 && NotEnoughUpdates.INSTANCE.config.toolbar.searchBar) { + textField.setText("id:" + item.get("internalname").getAsString()); updateSearch(); searchMode = true; } @@ -725,8 +731,8 @@ public class NEUOverlay extends Gui { } //Item selection (right) gui - if(mouseX > width*getItemPaneOffsetFactor()) { - if(!Mouse.getEventButtonState()) { + if (mouseX > width * getItemPaneOffsetFactor()) { + if (!Mouse.getEventButtonState()) { Utils.pushGuiScale(-1); return true; //End early if the mouse isn't pressed, but still cancel event. } @@ -734,18 +740,18 @@ public class NEUOverlay extends Gui { AtomicBoolean clickedItem = new AtomicBoolean(false); iterateItemSlots(new ItemSlotConsumer() { public void consume(int x, int y, int id) { - if(mouseX >= x-1 && mouseX <= x+ITEM_SIZE+1) { - if(mouseY >= y-1 && mouseY <= y+ITEM_SIZE+1) { + if (mouseX >= x - 1 && mouseX <= x + ITEM_SIZE + 1) { + if (mouseY >= y - 1 && mouseY <= y + ITEM_SIZE + 1) { clickedItem.set(true); JsonObject item = getSearchedItemPage(id); if (item != null) { - if(Mouse.getEventButton() == 0) { + if (Mouse.getEventButton() == 0) { manager.showRecipe(item); - } else if(Mouse.getEventButton() == 1) { + } else if (Mouse.getEventButton() == 1) { showInfo(item); - } else if(Mouse.getEventButton() == manager.keybindItemSelect.getKeyCode()+100 && NotEnoughUpdates.INSTANCE.config.toolbar.searchBar) { - textField.setText("id:"+item.get("internalname").getAsString()); + } else if (Mouse.getEventButton() == manager.keybindItemSelect.getKeyCode() + 100 && NotEnoughUpdates.INSTANCE.config.toolbar.searchBar) { + textField.setText("id:" + item.get("internalname").getAsString()); updateSearch(); searchMode = true; } @@ -754,52 +760,52 @@ public class NEUOverlay extends Gui { } } }); - if(!clickedItem.get()) { - int paneWidth = (int)(width/3*getWidthMult()); - int leftSide = (int)(width*getItemPaneOffsetFactor()); - int rightSide = leftSide+paneWidth-getBoxPadding()-getItemBoxXPadding(); - leftSide = leftSide+getBoxPadding()+getItemBoxXPadding(); + if (!clickedItem.get()) { + int paneWidth = (int) (width / 3 * getWidthMult()); + int leftSide = (int) (width * getItemPaneOffsetFactor()); + int rightSide = leftSide + paneWidth - getBoxPadding() - getItemBoxXPadding(); + leftSide = leftSide + getBoxPadding() + getItemBoxXPadding(); FontRenderer fr = Minecraft.getMinecraft().fontRendererObj; int maxPages = getMaxPages(); - String name = Utils.peekGuiScale().getScaleFactor()<4?"Page: ":""; - float maxStrLen = fr.getStringWidth(EnumChatFormatting.BOLD+name + maxPages + "/" + maxPages); - float maxButtonXSize = (rightSide-leftSide+2 - maxStrLen*0.5f - 10)/2f; - int buttonXSize = (int)Math.min(maxButtonXSize, getSearchBarYSize()*480/160f); - int ySize = (int)(buttonXSize/480f*160); - int yOffset = (int)((getSearchBarYSize()-ySize)/2f); - int top = getBoxPadding()+yOffset; - - if(mouseY >= top && mouseY <= top+ySize) { - int leftPrev = leftSide-1; - if(mouseX > leftPrev && mouseX < leftPrev+buttonXSize) { //"Previous" button - setPage(page-1); + String name = Utils.peekGuiScale().getScaleFactor() < 4 ? "Page: " : ""; + float maxStrLen = fr.getStringWidth(EnumChatFormatting.BOLD + name + maxPages + "/" + maxPages); + float maxButtonXSize = (rightSide - leftSide + 2 - maxStrLen * 0.5f - 10) / 2f; + int buttonXSize = (int) Math.min(maxButtonXSize, getSearchBarYSize() * 480 / 160f); + int ySize = (int) (buttonXSize / 480f * 160); + int yOffset = (int) ((getSearchBarYSize() - ySize) / 2f); + int top = getBoxPadding() + yOffset; + + if (mouseY >= top && mouseY <= top + ySize) { + int leftPrev = leftSide - 1; + if (mouseX > leftPrev && mouseX < leftPrev + buttonXSize) { //"Previous" button + setPage(page - 1); Utils.playPressSound(); } - int leftNext = rightSide+1-buttonXSize; - if(mouseX > leftNext && mouseX < leftNext+buttonXSize) { //"Next" button - setPage(page+1); + int leftNext = rightSide + 1 - buttonXSize; + if (mouseX > leftNext && mouseX < leftNext + buttonXSize) { //"Next" button + setPage(page + 1); Utils.playPressSound(); } } - float sortIconsMinX = (sortIcons.length+orderIcons.length)*(ITEM_SIZE+ITEM_PADDING)+ITEM_SIZE; - float availableX = rightSide-leftSide; + float sortIconsMinX = (sortIcons.length + orderIcons.length) * (ITEM_SIZE + ITEM_PADDING) + ITEM_SIZE; + float availableX = rightSide - leftSide; float sortOrderScaleFactor = Math.min(1, availableX / sortIconsMinX); - int scaledITEM_SIZE = (int)(ITEM_SIZE*sortOrderScaleFactor); - int scaledItemPaddedSize = (int)((ITEM_SIZE+ITEM_PADDING)*sortOrderScaleFactor); - int iconTop = height-getBoxPadding()-(ITEM_SIZE+scaledITEM_SIZE)/2-1; + int scaledITEM_SIZE = (int) (ITEM_SIZE * sortOrderScaleFactor); + int scaledItemPaddedSize = (int) ((ITEM_SIZE + ITEM_PADDING) * sortOrderScaleFactor); + int iconTop = height - getBoxPadding() - (ITEM_SIZE + scaledITEM_SIZE) / 2 - 1; - if(mouseY >= iconTop && mouseY <= iconTop+scaledITEM_SIZE) { - for(int i=0; i= orderIconX && mouseX <= orderIconX+scaledITEM_SIZE) { - if(Mouse.getEventButton() == 0) { + if (mouseY >= iconTop && mouseY <= iconTop + scaledITEM_SIZE) { + for (int i = 0; i < orderIcons.length; i++) { + int orderIconX = leftSide + i * scaledItemPaddedSize; + if (mouseX >= orderIconX && mouseX <= orderIconX + scaledITEM_SIZE) { + if (Mouse.getEventButton() == 0) { NotEnoughUpdates.INSTANCE.config.hidden.compareMode = i; updateSearch(); Utils.playPressSound(); - } else if(Mouse.getEventButton() == 1) { + } else if (Mouse.getEventButton() == 1) { NotEnoughUpdates.INSTANCE.config.hidden.compareAscending.set(i, !NotEnoughUpdates.INSTANCE.config.hidden.compareAscending.get(i)); updateSearch(); @@ -808,9 +814,9 @@ public class NEUOverlay extends Gui { } } - for(int i=0; i= sortIconX && mouseX <= sortIconX+scaledITEM_SIZE) { + for (int i = 0; i < sortIcons.length; i++) { + int sortIconX = rightSide - scaledITEM_SIZE - i * scaledItemPaddedSize; + if (mouseX >= sortIconX && mouseX <= sortIconX + scaledITEM_SIZE) { NotEnoughUpdates.INSTANCE.config.hidden.sortMode = i; updateSearch(); Utils.playPressSound(); @@ -823,9 +829,9 @@ public class NEUOverlay extends Gui { } //Clicking on "close info pane" button - if(mouseX > width*getInfoPaneOffsetFactor()-getBoxPadding()-8 && mouseX < width*getInfoPaneOffsetFactor()-getBoxPadding()+8) { - if(mouseY > getBoxPadding()-8 && mouseY < getBoxPadding()+8) { - if(Mouse.getEventButtonState() && Mouse.getEventButton() < 2) { //Left or right click up + if (mouseX > width * getInfoPaneOffsetFactor() - getBoxPadding() - 8 && mouseX < width * getInfoPaneOffsetFactor() - getBoxPadding() + 8) { + if (mouseY > getBoxPadding() - 8 && mouseY < getBoxPadding() + 8) { + if (Mouse.getEventButtonState() && Mouse.getEventButton() < 2) { //Left or right click up displayInformationPane(null); Utils.pushGuiScale(-1); return true; @@ -833,12 +839,12 @@ public class NEUOverlay extends Gui { } } - if(activeInfoPane != null) { - if(mouseX < width*getInfoPaneOffsetFactor()) { + if (activeInfoPane != null) { + if (mouseX < width * getInfoPaneOffsetFactor()) { activeInfoPane.mouseInput(width, height, mouseX, mouseY, mouseDown); Utils.pushGuiScale(-1); return true; - } else if(Mouse.getEventButton() <= 1 && Mouse.getEventButtonState()) { //Left or right click + } else if (Mouse.getEventButton() <= 1 && Mouse.getEventButtonState()) { //Left or right click activeInfoPane.mouseInputOutside(); } } @@ -848,8 +854,8 @@ public class NEUOverlay extends Gui { } public int getPaddingUnscaled() { - int paddingUnscaled = searchBarPadding/Utils.peekGuiScale().getScaleFactor(); - if(paddingUnscaled < 1) paddingUnscaled = 1; + int paddingUnscaled = searchBarPadding / Utils.peekGuiScale().getScaleFactor(); + if (paddingUnscaled < 1) paddingUnscaled = 1; return paddingUnscaled; } @@ -863,7 +869,7 @@ public class NEUOverlay extends Gui { */ public int getSearchBarXSize() { int searchBarXSize = NotEnoughUpdates.INSTANCE.config.toolbar.searchBarWidth; - if(Utils.peekGuiScale().getScaleFactor()==4) return (int)(searchBarXSize*0.8); + if (Utils.peekGuiScale().getScaleFactor() == 4) return (int) (searchBarXSize * 0.8); return searchBarXSize; } @@ -871,10 +877,10 @@ public class NEUOverlay extends Gui { * Sets the activeInfoPane and sets the target of the infoPaneOffsetFactor to make the infoPane "slide" out. */ public void displayInformationPane(InfoPane pane) { - if(pane == null) { + if (pane == null) { infoPaneOffsetFactor.setTarget(0); } else { - infoPaneOffsetFactor.setTarget(1/3f); + infoPaneOffsetFactor.setTarget(1 / 3f); } infoPaneOffsetFactor.resetTimer(); this.activeInfoPane = pane; @@ -891,15 +897,15 @@ public class NEUOverlay extends Gui { int width = Utils.peekGuiScale().getScaledWidth(); int height = Utils.peekGuiScale().getScaledHeight(); - int xComp = mouseX - (width/2 - getSearchBarXSize()/2 + 5); + int xComp = mouseX - (width / 2 - getSearchBarXSize() / 2 + 5); String trimmed = Minecraft.getMinecraft().fontRendererObj.trimStringToWidth(textField.getText(), xComp); int linePos = trimmed.length(); - if(linePos != textField.getText().length()) { + if (linePos != textField.getText().length()) { char after = textField.getText().charAt(linePos); int trimmedWidth = Minecraft.getMinecraft().fontRendererObj.getStringWidth(trimmed); int charWidth = Minecraft.getMinecraft().fontRendererObj.getCharWidth(after); - if(trimmedWidth + charWidth/2 < xComp-5) { + if (trimmedWidth + charWidth / 2 < xComp - 5) { linePos++; } } @@ -907,7 +913,7 @@ public class NEUOverlay extends Gui { } public void setSearchBarFocus(boolean focus) { - if(focus) { + if (focus) { itemPaneOpen = true; } searchBarHasFocus = focus; @@ -917,64 +923,64 @@ public class NEUOverlay extends Gui { * Handles the keyboard input, cancelling the forge event if the search bar has focus. */ public boolean keyboardInput(boolean hoverInv) { - if(Minecraft.getMinecraft().currentScreen == null) return false; + if (Minecraft.getMinecraft().currentScreen == null) return false; Keyboard.enableRepeatEvents(true); - int keyPressed = Keyboard.getEventKey() == 0 ? Keyboard.getEventCharacter()+256 : Keyboard.getEventKey(); + int keyPressed = Keyboard.getEventKey() == 0 ? Keyboard.getEventCharacter() + 256 : Keyboard.getEventKey(); - if(disabled) { - if(Keyboard.getEventKeyState() && keyPressed == manager.keybindToggleDisplay.getKeyCode()) { + if (disabled) { + if (Keyboard.getEventKeyState() && keyPressed == manager.keybindToggleDisplay.getKeyCode()) { disabled = !disabled; } return false; } - if(Keyboard.isKeyDown(Keyboard.KEY_Y) && NotEnoughUpdates.INSTANCE.config.hidden.dev) { + if (Keyboard.isKeyDown(Keyboard.KEY_Y) && NotEnoughUpdates.INSTANCE.config.hidden.dev) { displayInformationPane(new DevInfoPane(this, manager)); } - if(Keyboard.getEventKeyState()) { - if(!NotEnoughUpdates.INSTANCE.config.toolbar.searchBar) { + if (Keyboard.getEventKeyState()) { + if (!NotEnoughUpdates.INSTANCE.config.toolbar.searchBar) { searchBarHasFocus = false; } - if(searchBarHasFocus) { - if(keyPressed == 1) { + if (searchBarHasFocus) { + if (keyPressed == 1) { searchBarHasFocus = false; } else { - if(textField.textboxKeyTyped(Keyboard.getEventCharacter(), keyPressed)) { + if (textField.textboxKeyTyped(Keyboard.getEventCharacter(), keyPressed)) { updateSearch(); } } } else { - if(activeInfoPane != null) { - if(activeInfoPane.keyboardInput()) { + if (activeInfoPane != null) { + if (activeInfoPane.keyboardInput()) { return true; } } - if(keyPressed == manager.keybindClosePanes.getKeyCode()) { + if (keyPressed == manager.keybindClosePanes.getKeyCode()) { itemPaneOffsetFactor.setValue(1); itemPaneTabOffset.setValue(20); itemPaneOpen = false; displayInformationPane(null); } - if(keyPressed == manager.keybindToggleDisplay.getKeyCode()) { + if (keyPressed == manager.keybindToggleDisplay.getKeyCode()) { disabled = !disabled; return true; } AtomicReference internalname = new AtomicReference<>(null); AtomicReference itemstack = new AtomicReference<>(null); - if(Minecraft.getMinecraft().currentScreen instanceof GuiContainer && - Utils.getSlotUnderMouse((GuiContainer)Minecraft.getMinecraft().currentScreen) != null) { - Slot slot = Utils.getSlotUnderMouse((GuiContainer)Minecraft.getMinecraft().currentScreen); + if (Minecraft.getMinecraft().currentScreen instanceof GuiContainer && + Utils.getSlotUnderMouse((GuiContainer) Minecraft.getMinecraft().currentScreen) != null) { + Slot slot = Utils.getSlotUnderMouse((GuiContainer) Minecraft.getMinecraft().currentScreen); ItemStack hover = slot.getStack(); - if(hover != null) { + if (hover != null) { internalname.set(manager.getInternalNameForItem(hover)); itemstack.set(hover); } - } else if(!hoverInv) { + } else if (!hoverInv) { Utils.pushGuiScale(NotEnoughUpdates.INSTANCE.config.itemlist.paneGuiScale); int width = Utils.peekGuiScale().getScaledWidth(); @@ -1005,39 +1011,38 @@ public class NEUOverlay extends Gui { }); } - Utils.pushGuiScale(-1); } - if(internalname.get() != null) { - if(itemstack.get() != null) { - if(NotEnoughUpdates.INSTANCE.config.hidden.enableItemEditing && Keyboard.getEventCharacter() == 'k') { + if (internalname.get() != null) { + if (itemstack.get() != null) { + if (NotEnoughUpdates.INSTANCE.config.hidden.enableItemEditing && Keyboard.getEventCharacter() == 'k') { Minecraft.getMinecraft().displayGuiScreen(new NEUItemEditor(manager, internalname.get(), manager.getJsonForItem(itemstack.get()))); return true; } } JsonObject item = manager.getItemInformation().get(internalname.get()); - if(item != null) { - if(keyPressed == manager.keybindViewUsages.getKeyCode()) { + if (item != null) { + if (keyPressed == manager.keybindViewUsages.getKeyCode()) { manager.displayGuiItemUsages(internalname.get()); return true; - } else if(keyPressed == manager.keybindFavourite.getKeyCode()) { + } else if (keyPressed == manager.keybindFavourite.getKeyCode()) { toggleFavourite(item.get("internalname").getAsString()); return true; - } else if(keyPressed == manager.keybindViewRecipe.getKeyCode()) { + } else if (keyPressed == manager.keybindViewRecipe.getKeyCode()) { manager.showRecipe(item); return true; - } else if(keyPressed == manager.keybindGive.getKeyCode()) { - if(Minecraft.getMinecraft().thePlayer.capabilities.isCreativeMode) { + } else if (keyPressed == manager.keybindGive.getKeyCode()) { + if (Minecraft.getMinecraft().thePlayer.capabilities.isCreativeMode) { Minecraft.getMinecraft().thePlayer.inventory.addItemStackToInventory( manager.jsonToStack(item)); } - } else if(NotEnoughUpdates.INSTANCE.config.hidden.enableItemEditing && Keyboard.getEventCharacter() == 'k') { + } else if (NotEnoughUpdates.INSTANCE.config.hidden.enableItemEditing && Keyboard.getEventCharacter() == 'k') { Minecraft.getMinecraft().displayGuiScreen(new NEUItemEditor(manager, internalname.get(), item)); return true; - } else if(keyPressed == manager.keybindItemSelect.getKeyCode() && NotEnoughUpdates.INSTANCE.config.toolbar.searchBar) { - textField.setText("id:"+internalname.get()); + } else if (keyPressed == manager.keybindItemSelect.getKeyCode() && NotEnoughUpdates.INSTANCE.config.toolbar.searchBar) { + textField.setText("id:" + internalname.get()); itemPaneOpen = true; updateSearch(); } @@ -1050,7 +1055,7 @@ public class NEUOverlay extends Gui { } public void toggleFavourite(String internalname) { - if(getFavourites().contains(internalname)) { + if (getFavourites().contains(internalname)) { getFavourites().remove(internalname); } else { getFavourites().add(internalname); @@ -1058,14 +1063,14 @@ public class NEUOverlay extends Gui { updateSearch(); } - String[] rarityArr = new String[] { - EnumChatFormatting.WHITE+EnumChatFormatting.BOLD.toString()+"COMMON", - EnumChatFormatting.GREEN+EnumChatFormatting.BOLD.toString()+"UNCOMMON", - EnumChatFormatting.BLUE+EnumChatFormatting.BOLD.toString()+"RARE", - EnumChatFormatting.DARK_PURPLE+EnumChatFormatting.BOLD.toString()+"EPIC", - EnumChatFormatting.GOLD+EnumChatFormatting.BOLD.toString()+"LEGENDARY", - EnumChatFormatting.LIGHT_PURPLE+EnumChatFormatting.BOLD.toString()+"MYTHIC", - EnumChatFormatting.RED+EnumChatFormatting.BOLD.toString()+"SPECIAL", + String[] rarityArr = new String[]{ + EnumChatFormatting.WHITE + EnumChatFormatting.BOLD.toString() + "COMMON", + EnumChatFormatting.GREEN + EnumChatFormatting.BOLD.toString() + "UNCOMMON", + EnumChatFormatting.BLUE + EnumChatFormatting.BOLD.toString() + "RARE", + EnumChatFormatting.DARK_PURPLE + EnumChatFormatting.BOLD.toString() + "EPIC", + EnumChatFormatting.GOLD + EnumChatFormatting.BOLD.toString() + "LEGENDARY", + EnumChatFormatting.LIGHT_PURPLE + EnumChatFormatting.BOLD.toString() + "MYTHIC", + EnumChatFormatting.RED + EnumChatFormatting.BOLD.toString() + "SPECIAL", }; /** @@ -1080,11 +1085,11 @@ public class NEUOverlay extends Gui { * 6 = SPECIAL */ public int getRarity(JsonArray lore) { - for(int i=lore.size()-1; i>=0; i--) { + for (int i = lore.size() - 1; i >= 0; i--) { String line = lore.get(i).getAsString(); - for(int j=0; j getCompareAscending() { return NotEnoughUpdates.INSTANCE.config.hidden.compareAscending; } + private List getFavourites() { return NotEnoughUpdates.INSTANCE.config.hidden.favourites; } @@ -1116,74 +1124,73 @@ public class NEUOverlay extends Gui { return (o1, o2) -> { //1 (mult) if o1 should appear after o2 //-1 (-mult) if o2 should appear after o1 - if(getFavourites().contains(o1.get("internalname").getAsString()) && !getFavourites().contains(o2.get("internalname").getAsString())) { + if (getFavourites().contains(o1.get("internalname").getAsString()) && !getFavourites().contains(o2.get("internalname").getAsString())) { return -1; } - if(!getFavourites().contains(o1.get("internalname").getAsString()) && getFavourites().contains(o2.get("internalname").getAsString())) { + if (!getFavourites().contains(o1.get("internalname").getAsString()) && getFavourites().contains(o2.get("internalname").getAsString())) { return 1; } int mult = getCompareAscending().get(getCompareMode()) ? 1 : -1; - if(getCompareMode() == COMPARE_MODE_RARITY) { + if (getCompareMode() == COMPARE_MODE_RARITY) { int rarity1 = getRarity(o1.get("lore").getAsJsonArray()); int rarity2 = getRarity(o2.get("lore").getAsJsonArray()); - if(rarity1 < rarity2) return mult; - if(rarity1 > rarity2) return -mult; - } else if(getCompareMode() == COMPARE_MODE_VALUE) { + if (rarity1 < rarity2) return mult; + if (rarity1 > rarity2) return -mult; + } else if (getCompareMode() == COMPARE_MODE_VALUE) { String internal1 = o1.get("internalname").getAsString(); String internal2 = o2.get("internalname").getAsString(); float cost1 = manager.auctionManager.getLowestBin(internal1); float cost2 = manager.auctionManager.getLowestBin(internal2); - - if(cost1 < cost2) return mult; - if(cost1 > cost2) return -mult; + if (cost1 < cost2) return mult; + if (cost1 > cost2) return -mult; } String i1 = o1.get("internalname").getAsString(); String[] split1 = i1.split("_"); - String last1 = split1[split1.length-1]; - String start1 = i1.substring(0, i1.length()-last1.length()); + String last1 = split1[split1.length - 1]; + String start1 = i1.substring(0, i1.length() - last1.length()); String i2 = o2.get("internalname").getAsString(); String[] split2 = i2.split("_"); - String last2 = split2[split2.length-1]; - String start2 = i2.substring(0, i2.length()-last2.length()); + String last2 = split2[split2.length - 1]; + String start2 = i2.substring(0, i2.length() - last2.length()); mult = getCompareAscending().get(COMPARE_MODE_ALPHABETICAL) ? 1 : -1; - if(start1.equals(start2)) { - String[] order = new String[]{"HELMET","CHESTPLATE","LEGGINGS","BOOTS"}; + if (start1.equals(start2)) { + String[] order = new String[]{"HELMET", "CHESTPLATE", "LEGGINGS", "BOOTS"}; int type1 = checkItemType(o1.get("lore").getAsJsonArray(), order); int type2 = checkItemType(o2.get("lore").getAsJsonArray(), order); - - if(type1 < type2) return -mult; - if(type1 > type2) return mult; + if (type1 < type2) return -mult; + if (type1 > type2) return mult; } - int nameComp = mult*o1.get("displayname").getAsString().replaceAll("(?i)\\u00A7.", "") - .compareTo(o2.get("displayname").getAsString().replaceAll("(?i)\\u00A7.", "")); - if(nameComp != 0) { + int nameComp = mult * o1.get("displayname").getAsString().replaceAll("(?i)\\u00A7.", "") + .compareTo(o2.get("displayname").getAsString().replaceAll("(?i)\\u00A7.", "")); + if (nameComp != 0) { return nameComp; } - return mult*o1.get("internalname").getAsString().compareTo(o2.get("internalname").getAsString()); + return mult * o1.get("internalname").getAsString().compareTo(o2.get("internalname").getAsString()); }; } /** * Checks whether an item matches a certain type, i.e. whether the item lore ends in "{rarity} {item type}" * eg. "SHOVEL" will return >0 for "COMMON SHOVEL", "EPIC SHOVEL", etc. + * * @return the index of the type that matched, or -1 otherwise. */ public int checkItemType(JsonArray lore, String... typeMatches) { - for(int i=lore.size()-1; i>=0; i--) { + for (int i = lore.size() - 1; i >= 0; i--) { String line = lore.get(i).getAsString(); - for(String rarity : rarityArr) { - for(int j=0; j= 0; - } else if(getSortMode() == SORT_MODE_ARMOR) { + } else if (getSortMode() == SORT_MODE_ARMOR) { return checkItemType(item.get("lore").getAsJsonArray(), "HELMET", "CHESTPLATE", "LEGGINGS", "BOOTS", "DUNGEON HELMET", "DUNGEON CHESTPLATE", "DUNGEON LEGGINGS", "DUNGEON BOOTS") >= 0; - } else if(getSortMode() == SORT_MODE_ACCESSORY) { + } else if (getSortMode() == SORT_MODE_ACCESSORY) { return checkItemType(item.get("lore").getAsJsonArray(), "ACCESSORY", "HATCCESSORY", "DUNGEON ACCESSORY") >= 0; } return true; } - private HashMap parentMap = new HashMap<>(); + private final HashMap parentMap = new HashMap<>(); - private ExecutorService searchES = Executors.newSingleThreadExecutor(); + private final ExecutorService searchES = Executors.newSingleThreadExecutor(); /** * Clears the current item list, creating a new TreeSet if necessary. @@ -1229,7 +1236,7 @@ public class NEUOverlay extends Gui { public void updateSearch() { SunTzu.randomizeQuote(); - if(searchedItems == null) searchedItems = new TreeSet<>(getItemComparator()); + if (searchedItems == null) searchedItems = new TreeSet<>(getItemComparator()); searchES.submit(() -> { TreeSet searchedItems = new TreeSet<>(getItemComparator()); @@ -1237,19 +1244,19 @@ public class NEUOverlay extends Gui { Set removeChildItems = new HashSet<>(); Set itemsMatch = manager.search(textField.getText(), true); - for(String itemname : itemsMatch) { + for (String itemname : itemsMatch) { JsonObject item = manager.getItemInformation().get(itemname); - if(checkMatchesSort(itemname, item)) { - if(Constants.PARENTS != null) { - if(Constants.PARENTS.has(itemname) && Constants.PARENTS.get(itemname).isJsonArray()) { + if (checkMatchesSort(itemname, item)) { + if (Constants.PARENTS != null) { + if (Constants.PARENTS.has(itemname) && Constants.PARENTS.get(itemname).isJsonArray()) { List children = new ArrayList<>(); - for(JsonElement e : Constants.PARENTS.get(itemname).getAsJsonArray()) { - if(e.isJsonPrimitive()) { + for (JsonElement e : Constants.PARENTS.get(itemname).getAsJsonArray()) { + if (e.isJsonPrimitive()) { children.add(e.getAsString()); } } children.retainAll(itemsMatch); - for(String child : children) { + for (String child : children) { removeChildItems.add(manager.getItemInformation().get(child)); } searchedItemsSubgroup.put(itemname, children); @@ -1260,16 +1267,16 @@ public class NEUOverlay extends Gui { } searchedItems.removeAll(removeChildItems); out: - for(Map.Entry> entry : searchedItemsSubgroup.entrySet()) { - if(searchedItems.contains(manager.getItemInformation().get(entry.getKey()))) { + for (Map.Entry> entry : searchedItemsSubgroup.entrySet()) { + if (searchedItems.contains(manager.getItemInformation().get(entry.getKey()))) { continue; } - for(String itemname : entry.getValue()) { + for (String itemname : entry.getValue()) { JsonObject item = manager.getItemInformation().get(itemname); - if(item != null) searchedItems.add(item); + if (item != null) searchedItems.add(item); } } - switch(textField.getText().toLowerCase().trim()) { + switch (textField.getText().toLowerCase().trim()) { case "nullzee": searchedItems.add(CustomItems.NULLZEE); break; @@ -1306,7 +1313,7 @@ public class NEUOverlay extends Gui { this.searchedItems = searchedItems; this.searchedItemsSubgroup = searchedItemsSubgroup; - synchronized(this.searchedItemsArr) { + synchronized (this.searchedItemsArr) { this.searchedItemsArr.clear(); } @@ -1319,13 +1326,13 @@ public class NEUOverlay extends Gui { * Whenever searchedItems is updated in updateSearch(), the array is recreated here. */ public List getSearchedItems() { - if(searchedItems == null) { + if (searchedItems == null) { updateSearch(); return new ArrayList<>(); } - if(searchedItems.size() > 0 && searchedItemsArr.size() == 0) { - synchronized(searchedItemsArr) { + if (searchedItems.size() > 0 && searchedItemsArr.size() == 0) { + synchronized (searchedItemsArr) { searchedItemsArr.addAll(searchedItems); } } @@ -1334,13 +1341,14 @@ public class NEUOverlay extends Gui { /** * Gets the item in searchedItemArr corresponding to the certain index on the current page. + * * @return item, if the item exists. null, otherwise. */ public JsonObject getSearchedItemPage(int index) { - if(index < getSlotsXSize()*getSlotsYSize()) { - int actualIndex = index + getSlotsXSize()*getSlotsYSize()*page; + if (index < getSlotsXSize() * getSlotsYSize()) { + int actualIndex = index + getSlotsXSize() * getSlotsYSize() * page; List searchedItems = getSearchedItems(); - if(actualIndex < searchedItems.size()) { + if (actualIndex < searchedItems.size()) { return searchedItems.get(actualIndex); } else { return null; @@ -1352,22 +1360,22 @@ public class NEUOverlay extends Gui { public int getItemBoxXPadding() { int width = Utils.peekGuiScale().getScaledWidth(); - return (((int)(width/3*getWidthMult())-2*getBoxPadding())%(ITEM_SIZE+ITEM_PADDING)+ITEM_PADDING)/2; + return (((int) (width / 3 * getWidthMult()) - 2 * getBoxPadding()) % (ITEM_SIZE + ITEM_PADDING) + ITEM_PADDING) / 2; } public int getBoxPadding() { double panePadding = Math.max(0, Math.min(20, NotEnoughUpdates.INSTANCE.config.itemlist.panePadding)); - return (int)(panePadding*2/Utils.peekGuiScale().getScaleFactor()+5); + return (int) (panePadding * 2 / Utils.peekGuiScale().getScaleFactor() + 5); } - private abstract class ItemSlotConsumer { + private abstract static class ItemSlotConsumer { public abstract void consume(int x, int y, int id); } public void iterateItemSlots(ItemSlotConsumer itemSlotConsumer) { int width = Utils.peekGuiScale().getScaledWidth(); int itemBoxXPadding = getItemBoxXPadding(); - iterateItemSlots(itemSlotConsumer, (int)(width*getItemPaneOffsetFactor())+getBoxPadding()+itemBoxXPadding); + iterateItemSlots(itemSlotConsumer, (int) (width * getItemPaneOffsetFactor()) + getBoxPadding() + itemBoxXPadding); } /** @@ -1379,18 +1387,18 @@ public class NEUOverlay extends Gui { int width = Utils.peekGuiScale().getScaledWidth(); int height = Utils.peekGuiScale().getScaledHeight(); - int paneWidth = (int)(width/3*getWidthMult()); - int itemBoxYPadding = ((height-getSearchBarYSize()-2*getBoxPadding()-ITEM_SIZE-2)%(ITEM_SIZE+ITEM_PADDING)+ITEM_PADDING)/2; + int paneWidth = (int) (width / 3 * getWidthMult()); + int itemBoxYPadding = ((height - getSearchBarYSize() - 2 * getBoxPadding() - ITEM_SIZE - 2) % (ITEM_SIZE + ITEM_PADDING) + ITEM_PADDING) / 2; - int yStart = getBoxPadding()+getSearchBarYSize()+itemBoxYPadding; + int yStart = getBoxPadding() + getSearchBarYSize() + itemBoxYPadding; int itemBoxXPadding = getItemBoxXPadding(); - int xEnd = xStart+paneWidth-getBoxPadding()*2-ITEM_SIZE-itemBoxXPadding; - int yEnd = height-getBoxPadding()-ITEM_SIZE-2-itemBoxYPadding; + int xEnd = xStart + paneWidth - getBoxPadding() * 2 - ITEM_SIZE - itemBoxXPadding; + int yEnd = height - getBoxPadding() - ITEM_SIZE - 2 - itemBoxYPadding; //Render the items, displaying the tooltip if the cursor is over the item int id = 0; - for(int y = yStart; y < yEnd; y+=ITEM_SIZE+ITEM_PADDING) { - for(int x = xStart; x < xEnd; x+=ITEM_SIZE+ITEM_PADDING) { + for (int y = yStart; y < yEnd; y += ITEM_SIZE + ITEM_PADDING) { + for (int x = xStart; x < xEnd; x += ITEM_SIZE + ITEM_PADDING) { itemSlotConsumer.consume(x, y, id++); } } @@ -1398,9 +1406,10 @@ public class NEUOverlay extends Gui { public float getWidthMult() { float scaleFMult = 1; - if(Utils.peekGuiScale().getScaleFactor()==4) scaleFMult *= 0.9f; - if(manager.auctionManager.customAH.isRenderOverAuctionView() || Minecraft.getMinecraft().currentScreen instanceof CustomAHGui) scaleFMult *= 0.8f; - return (float)Math.max(0.5, Math.min(1.5, NotEnoughUpdates.INSTANCE.config.itemlist.paneWidthMult))*scaleFMult; + if (Utils.peekGuiScale().getScaleFactor() == 4) scaleFMult *= 0.9f; + if (manager.auctionManager.customAH.isRenderOverAuctionView() || Minecraft.getMinecraft().currentScreen instanceof CustomAHGui) + scaleFMult *= 0.8f; + return (float) Math.max(0.5, Math.min(1.5, NotEnoughUpdates.INSTANCE.config.itemlist.paneWidthMult)) * scaleFMult; } /** @@ -1409,12 +1418,12 @@ public class NEUOverlay extends Gui { public int getSlotsXSize() { int width = Utils.peekGuiScale().getScaledWidth(); - int paneWidth = (int)(width/3*getWidthMult()); - int itemBoxXPadding = (((int)(width-width*getItemPaneOffsetFactor())-2*getBoxPadding())%(ITEM_SIZE+ITEM_PADDING)+ITEM_PADDING)/2; - int xStart = (int)(width*getItemPaneOffsetFactor())+getBoxPadding()+itemBoxXPadding; - int xEnd = (int)(width*getItemPaneOffsetFactor())+paneWidth-getBoxPadding()-ITEM_SIZE; + int paneWidth = (int) (width / 3 * getWidthMult()); + int itemBoxXPadding = (((int) (width - width * getItemPaneOffsetFactor()) - 2 * getBoxPadding()) % (ITEM_SIZE + ITEM_PADDING) + ITEM_PADDING) / 2; + int xStart = (int) (width * getItemPaneOffsetFactor()) + getBoxPadding() + itemBoxXPadding; + int xEnd = (int) (width * getItemPaneOffsetFactor()) + paneWidth - getBoxPadding() - ITEM_SIZE; - return (int)Math.ceil((xEnd - xStart)/((float)(ITEM_SIZE+ITEM_PADDING))); + return (int) Math.ceil((xEnd - xStart) / ((float) (ITEM_SIZE + ITEM_PADDING))); } /** @@ -1423,21 +1432,21 @@ public class NEUOverlay extends Gui { public int getSlotsYSize() { int height = Utils.peekGuiScale().getScaledHeight(); - int itemBoxYPadding = ((height-getSearchBarYSize()-2*getBoxPadding()-ITEM_SIZE-2)%(ITEM_SIZE+ITEM_PADDING)+ITEM_PADDING)/2; - int yStart = getBoxPadding()+getSearchBarYSize()+itemBoxYPadding; - int yEnd = height-getBoxPadding()-ITEM_SIZE-2-itemBoxYPadding; + int itemBoxYPadding = ((height - getSearchBarYSize() - 2 * getBoxPadding() - ITEM_SIZE - 2) % (ITEM_SIZE + ITEM_PADDING) + ITEM_PADDING) / 2; + int yStart = getBoxPadding() + getSearchBarYSize() + itemBoxYPadding; + int yEnd = height - getBoxPadding() - ITEM_SIZE - 2 - itemBoxYPadding; - return (int)Math.ceil((yEnd - yStart)/((float)(ITEM_SIZE+ITEM_PADDING))); + return (int) Math.ceil((yEnd - yStart) / ((float) (ITEM_SIZE + ITEM_PADDING))); } public int getMaxPages() { - if(getSearchedItems().size() == 0) return 1; - return (int)Math.ceil(getSearchedItems().size()/(float)getSlotsYSize()/getSlotsXSize()); + if (getSearchedItems().size() == 0) return 1; + return (int) Math.ceil(getSearchedItems().size() / (float) getSlotsYSize() / getSlotsXSize()); } public int getSearchBarYSize() { int searchBarYSize = NotEnoughUpdates.INSTANCE.config.toolbar.searchBarHeight; - return Math.max(searchBarYSize/Utils.peekGuiScale().getScaleFactor(), ITEM_SIZE); + return Math.max(searchBarYSize / Utils.peekGuiScale().getScaleFactor(), ITEM_SIZE); } /** @@ -1447,78 +1456,78 @@ public class NEUOverlay extends Gui { public void renderNavElement(int leftSide, int rightSide, int maxPages, int page, String name) { FontRenderer fr = Minecraft.getMinecraft().fontRendererObj; - String pageText = EnumChatFormatting.BOLD+name + page + "/" + maxPages; + String pageText = EnumChatFormatting.BOLD + name + page + "/" + maxPages; - float maxStrLen = fr.getStringWidth(EnumChatFormatting.BOLD+name + maxPages + "/" + maxPages); - float maxButtonXSize = (rightSide-leftSide+2 - maxStrLen*0.5f - 10)/2f; - int buttonXSize = (int)Math.min(maxButtonXSize, getSearchBarYSize()*480/160f); - int ySize = (int)(buttonXSize/480f*160); - int yOffset = (int)((getSearchBarYSize()-ySize)/2f); - int top = getBoxPadding()+yOffset; + float maxStrLen = fr.getStringWidth(EnumChatFormatting.BOLD + name + maxPages + "/" + maxPages); + float maxButtonXSize = (rightSide - leftSide + 2 - maxStrLen * 0.5f - 10) / 2f; + int buttonXSize = (int) Math.min(maxButtonXSize, getSearchBarYSize() * 480 / 160f); + int ySize = (int) (buttonXSize / 480f * 160); + int yOffset = (int) ((getSearchBarYSize() - ySize) / 2f); + int top = getBoxPadding() + yOffset; int leftPressed = 0; int rightPressed = 0; - if(Mouse.isButtonDown(0) || Mouse.isButtonDown(1)) { + if (Mouse.isButtonDown(0) || Mouse.isButtonDown(1)) { int width = Utils.peekGuiScale().getScaledWidth(); int height = Utils.peekGuiScale().getScaledHeight(); int mouseX = Mouse.getX() * width / Minecraft.getMinecraft().displayWidth; int mouseY = height - Mouse.getY() * height / Minecraft.getMinecraft().displayHeight - 1; - if(mouseY >= top && mouseY <= top+ySize) { - int leftPrev = leftSide-1; - if(mouseX > leftPrev && mouseX < leftPrev+buttonXSize) { //"Previous" button + if (mouseY >= top && mouseY <= top + ySize) { + int leftPrev = leftSide - 1; + if (mouseX > leftPrev && mouseX < leftPrev + buttonXSize) { //"Previous" button leftPressed = 1; } - int leftNext = rightSide+1-buttonXSize; - if(mouseX > leftNext && mouseX < leftNext+buttonXSize) { //"Next" button + int leftNext = rightSide + 1 - buttonXSize; + if (mouseX > leftNext && mouseX < leftNext + buttonXSize) { //"Next" button rightPressed = 1; } } } - drawRect(leftSide-1, top, leftSide-1+buttonXSize, top+ySize, fg.getRGB()); + drawRect(leftSide - 1, top, leftSide - 1 + buttonXSize, top + ySize, fg.getRGB()); GlStateManager.color(1f, 1f, 1f, 1f); Minecraft.getMinecraft().getTextureManager().bindTexture(rightarrow); - Utils.drawTexturedRect(leftSide-1+leftPressed, - top+leftPressed, + Utils.drawTexturedRect(leftSide - 1 + leftPressed, + top + leftPressed, buttonXSize, ySize, 1, 0, 0, 1); Minecraft.getMinecraft().getTextureManager().bindTexture(rightarrow_overlay); - Utils.drawTexturedRect(leftSide-1, + Utils.drawTexturedRect(leftSide - 1, top, - buttonXSize, ySize, 1-leftPressed, leftPressed, 1-leftPressed, leftPressed); + buttonXSize, ySize, 1 - leftPressed, leftPressed, 1 - leftPressed, leftPressed); GlStateManager.bindTexture(0); - Utils.drawStringCenteredScaled(EnumChatFormatting.BOLD+"Prev", fr, - leftSide-1+buttonXSize*300/480f+leftPressed, - top+ySize/2f+leftPressed, false, - (int)(buttonXSize*240/480f), Color.BLACK.getRGB()); + Utils.drawStringCenteredScaled(EnumChatFormatting.BOLD + "Prev", fr, + leftSide - 1 + buttonXSize * 300 / 480f + leftPressed, + top + ySize / 2f + leftPressed, false, + (int) (buttonXSize * 240 / 480f), Color.BLACK.getRGB()); - drawRect(rightSide+1-buttonXSize, top, rightSide+1, top+ySize, fg.getRGB()); + drawRect(rightSide + 1 - buttonXSize, top, rightSide + 1, top + ySize, fg.getRGB()); GlStateManager.color(1f, 1f, 1f, 1f); Minecraft.getMinecraft().getTextureManager().bindTexture(rightarrow); - Utils.drawTexturedRect(rightSide+1-buttonXSize+rightPressed, - top+rightPressed, + Utils.drawTexturedRect(rightSide + 1 - buttonXSize + rightPressed, + top + rightPressed, buttonXSize, ySize); Minecraft.getMinecraft().getTextureManager().bindTexture(rightarrow_overlay); - Utils.drawTexturedRect(rightSide+1-buttonXSize, + Utils.drawTexturedRect(rightSide + 1 - buttonXSize, top, - buttonXSize, ySize, 1-rightPressed, rightPressed, 1-rightPressed, rightPressed); + buttonXSize, ySize, 1 - rightPressed, rightPressed, 1 - rightPressed, rightPressed); GlStateManager.bindTexture(0); - Utils.drawStringCenteredScaled(EnumChatFormatting.BOLD+"Next", fr, - rightSide+1-buttonXSize*300/480f+rightPressed, - top+ySize/2f+rightPressed, false, - (int)(buttonXSize*240/480f), Color.BLACK.getRGB()); + Utils.drawStringCenteredScaled(EnumChatFormatting.BOLD + "Next", fr, + rightSide + 1 - buttonXSize * 300 / 480f + rightPressed, + top + ySize / 2f + rightPressed, false, + (int) (buttonXSize * 240 / 480f), Color.BLACK.getRGB()); - int strMaxLen = rightSide-leftSide-2*buttonXSize-10; + int strMaxLen = rightSide - leftSide - 2 * buttonXSize - 10; - drawRect(leftSide-1+buttonXSize+3, top, rightSide+1-buttonXSize-3, top+ySize, - new Color(177,177,177).getRGB()); - drawRect(leftSide+buttonXSize+3, top+1, rightSide+1-buttonXSize-3, top+ySize, - new Color(50,50,50).getRGB()); - drawRect(leftSide+buttonXSize+3, top+1, rightSide-buttonXSize-3, top+ySize-1, fg.getRGB()); - Utils.drawStringCenteredScaledMaxWidth(pageText, fr,(leftSide+rightSide)/2, - top+ySize/2f, false, strMaxLen, Color.BLACK.getRGB()); + drawRect(leftSide - 1 + buttonXSize + 3, top, rightSide + 1 - buttonXSize - 3, top + ySize, + new Color(177, 177, 177).getRGB()); + drawRect(leftSide + buttonXSize + 3, top + 1, rightSide + 1 - buttonXSize - 3, top + ySize, + new Color(50, 50, 50).getRGB()); + drawRect(leftSide + buttonXSize + 3, top + 1, rightSide - buttonXSize - 3, top + ySize - 1, fg.getRGB()); + Utils.drawStringCenteredScaledMaxWidth(pageText, fr, (leftSide + rightSide) / 2, + top + ySize / 2f, false, strMaxLen, Color.BLACK.getRGB()); } private int limCol(int col) { @@ -1539,11 +1548,11 @@ public class NEUOverlay extends Gui { EntityLivingBase[] entities = new EntityLivingBase[classes.length]; try { EntityLivingBase last = null; - for(int i=0; i clazz = classes[i]; - if(clazz == null) continue; + if (clazz == null) continue; - EntityLivingBase newEnt = clazz.getConstructor(new Class[] {World.class}).newInstance(Minecraft.getMinecraft().theWorld); + EntityLivingBase newEnt = clazz.getConstructor(new Class[]{World.class}).newInstance(Minecraft.getMinecraft().theWorld); //newEnt.renderYawOffset = yaw; //newEnt.rotationYaw = yaw; @@ -1553,7 +1562,7 @@ public class NEUOverlay extends Gui { newEnt.setCustomNameTag(name); - if(last != null) { + if (last != null) { last.riddenByEntity = newEnt; newEnt.ridingEntity = last; last.updateRiderPosition(); @@ -1567,7 +1576,6 @@ public class NEUOverlay extends Gui { return; } - GlStateManager.enableColorMaterial(); GlStateManager.pushMatrix(); GlStateManager.translate(posX, posY, 50.0F); @@ -1584,9 +1592,9 @@ public class NEUOverlay extends Gui { RenderManager rendermanager = Minecraft.getMinecraft().getRenderManager(); rendermanager.setPlayerViewY(180.0F); rendermanager.setRenderShadow(false); - for(EntityLivingBase ent : entities) { - GL11.glColor4f(1,1,1,1); - if(ent != null) rendermanager.renderEntityWithPosYaw(ent, ent.posX, ent.posY, ent.posZ, 0.0F, 1.0F); + for (EntityLivingBase ent : entities) { + GL11.glColor4f(1, 1, 1, 1); + if (ent != null) rendermanager.renderEntityWithPosYaw(ent, ent.posX, ent.posY, ent.posZ, 0.0F, 1.0F); } rendermanager.setRenderShadow(true); @@ -1608,15 +1616,15 @@ public class NEUOverlay extends Gui { /** * Creates a projection matrix that projects from our coordinate space [0->width; 0->height] to OpenGL coordinate * space [-1 -> 1; 1 -> -1] (Note: flipped y-axis). - * + *

* This is so that we can render to and from the framebuffer in a way that is familiar to us, instead of needing to * apply scales and translations manually. */ private Matrix4f createProjectionMatrix(int width, int height) { - Matrix4f projMatrix = new Matrix4f(); + Matrix4f projMatrix = new Matrix4f(); projMatrix.setIdentity(); - projMatrix.m00 = 2.0F / (float)width; - projMatrix.m11 = 2.0F / (float)(-height); + projMatrix.m00 = 2.0F / (float) width; + projMatrix.m11 = 2.0F / (float) (-height); projMatrix.m22 = -0.0020001999F; projMatrix.m33 = 1.0F; projMatrix.m03 = -1.0F; @@ -1630,7 +1638,7 @@ public class NEUOverlay extends Gui { int width = Utils.peekGuiScale().getScaledWidth(); int height = Utils.peekGuiScale().getScaledHeight(); - if(lastScreenWidth != width || lastScreenHeight != height || Utils.peekGuiScale().getScaleFactor() != lastScale) { + if (lastScreenWidth != width || lastScreenHeight != height || Utils.peekGuiScale().getScaleFactor() != lastScale) { guiGroup.width = width; guiGroup.height = height; @@ -1652,7 +1660,7 @@ public class NEUOverlay extends Gui { * Renders the search bar, quick commands, item selection (right) and item info (left) gui elements. */ public void render(boolean hoverInv) { - if(disabled) { + if (disabled) { return; } GlStateManager.enableDepth(); @@ -1667,15 +1675,15 @@ public class NEUOverlay extends Gui { int mouseX = Mouse.getX() * width / Minecraft.getMinecraft().displayWidth; int mouseY = height - Mouse.getY() * height / Minecraft.getMinecraft().displayHeight - 1; - if(showVanillaLast != NotEnoughUpdates.INSTANCE.config.itemlist.showVanillaItems) { + if (showVanillaLast != NotEnoughUpdates.INSTANCE.config.itemlist.showVanillaItems) { showVanillaLast = NotEnoughUpdates.INSTANCE.config.itemlist.showVanillaItems; updateSearch(); } - if(textField.getText().toLowerCase().contains("bald")) { + if (textField.getText().toLowerCase().contains("bald")) { Minecraft.getMinecraft().getTextureManager().bindTexture(SUPERGEHEIMNISVERMOGEN); GlStateManager.color(1, 1, 1, 1); - Utils.drawTexturedRect((width-64)/2f, (height-64)/2f-114, 64, 64, GL11.GL_LINEAR); + Utils.drawTexturedRect((width - 64) / 2f, (height - 64) / 2f - 114, 64, 64, GL11.GL_LINEAR); GlStateManager.bindTexture(0); } @@ -1683,12 +1691,12 @@ public class NEUOverlay extends Gui { updateGuiGroupSize(); - if(guiScaleLast != Utils.peekGuiScale().getScaleFactor()) { + if (guiScaleLast != Utils.peekGuiScale().getScaleFactor()) { guiScaleLast = Utils.peekGuiScale().getScaleFactor(); redrawItems = true; } - if(oldWidthMult != getWidthMult()) { + if (oldWidthMult != getWidthMult()) { oldWidthMult = getWidthMult(); redrawItems = true; } @@ -1701,29 +1709,29 @@ public class NEUOverlay extends Gui { Color fgCustomOpacity = new Color(SpecialColour.specialToChromaRGB(NotEnoughUpdates.INSTANCE.config.itemlist.foregroundColour), true); Color fgFavourite2 = new Color(SpecialColour.specialToChromaRGB(NotEnoughUpdates.INSTANCE.config.itemlist.favouriteColour), true); - Color fgFavourite = new Color((int)(fgFavourite2.getRed()*0.8f), (int)(fgFavourite2.getGreen()*0.8f), - (int)(fgFavourite2.getBlue()*0.8f), fgFavourite2.getAlpha()); + Color fgFavourite = new Color((int) (fgFavourite2.getRed() * 0.8f), (int) (fgFavourite2.getGreen() * 0.8f), + (int) (fgFavourite2.getBlue() * 0.8f), fgFavourite2.getAlpha()); - if(itemPaneOpen) { - if(itemPaneTabOffset.getValue() == 0) { - if(itemPaneOffsetFactor.getTarget() != 2/3f) { - itemPaneOffsetFactor.setTarget(2/3f); + if (itemPaneOpen) { + if (itemPaneTabOffset.getValue() == 0) { + if (itemPaneOffsetFactor.getTarget() != 2 / 3f) { + itemPaneOffsetFactor.setTarget(2 / 3f); itemPaneOffsetFactor.resetTimer(); } } else { - if(itemPaneTabOffset.getTarget() != 0) { + if (itemPaneTabOffset.getTarget() != 0) { itemPaneTabOffset.setTarget(0); itemPaneTabOffset.resetTimer(); } } } else { - if(itemPaneOffsetFactor.getValue() == 1) { - if(itemPaneTabOffset.getTarget() != 20) { + if (itemPaneOffsetFactor.getValue() == 1) { + if (itemPaneTabOffset.getTarget() != 20) { itemPaneTabOffset.setTarget(20); itemPaneTabOffset.resetTimer(); } } else { - if(itemPaneOffsetFactor.getTarget() != 1f) { + if (itemPaneOffsetFactor.getTarget() != 1f) { itemPaneOffsetFactor.setTarget(1f); itemPaneOffsetFactor.resetTimer(); } @@ -1734,27 +1742,27 @@ public class NEUOverlay extends Gui { itemPaneTabOffset.tick(); infoPaneOffsetFactor.tick(); - if(page > getMaxPages()-1) setPage(getMaxPages()-1); - if(page < 0) setPage(0); + if (page > getMaxPages() - 1) setPage(getMaxPages() - 1); + if (page < 0) setPage(0); GlStateManager.disableLighting(); - /** + /* * Item selection (right) gui element rendering */ - int paneWidth = (int)(width/3*getWidthMult()); - int leftSide = (int)(width*getItemPaneOffsetFactor()); - int rightSide = leftSide+paneWidth-getBoxPadding()-getItemBoxXPadding(); + int paneWidth = (int) (width / 3 * getWidthMult()); + int leftSide = (int) (width * getItemPaneOffsetFactor()); + int rightSide = leftSide + paneWidth - getBoxPadding() - getItemBoxXPadding(); //Tab - if(NotEnoughUpdates.INSTANCE.config.itemlist.tabOpen) { + if (NotEnoughUpdates.INSTANCE.config.itemlist.tabOpen) { Minecraft.getMinecraft().getTextureManager().bindTexture(itemPaneTabArrow); GlStateManager.color(1f, 1f, 1f, 0.3f); - Utils.drawTexturedRect(width-itemPaneTabOffset.getValue()*64/20f, height/2f - 32, 64, 64); + Utils.drawTexturedRect(width - itemPaneTabOffset.getValue() * 64 / 20f, height / 2f - 32, 64, 64); GlStateManager.bindTexture(0); - if(!itemPaneOpen && mouseX > width-itemPaneTabOffset.getValue() && mouseY > height/2 - 32 - && mouseY < height/2 + 32) { + if (!itemPaneOpen && mouseX > width - itemPaneTabOffset.getValue() && mouseY > height / 2 - 32 + && mouseY < height / 2 + 32) { itemPaneOpen = true; } } @@ -1762,110 +1770,110 @@ public class NEUOverlay extends Gui { //Atomic reference used so that below lambda doesn't complain about non-effectively-final variable AtomicReference tooltipToDisplay = new AtomicReference<>(null); //System.out.println(itemPaneOffsetFactor.getValue()); - if(itemPaneOffsetFactor.getValue() < 0.99) { - if(NotEnoughUpdates.INSTANCE.config.itemlist.bgBlurFactor > 0.5) { + if (itemPaneOffsetFactor.getValue() < 0.99) { + if (NotEnoughUpdates.INSTANCE.config.itemlist.bgBlurFactor > 0.5) { BackgroundBlur.renderBlurredBackground(NotEnoughUpdates.INSTANCE.config.itemlist.bgBlurFactor, width, height, - leftSide+getBoxPadding()-5, getBoxPadding()-5, - paneWidth-getBoxPadding()*2+10, height-getBoxPadding()*2+10, + leftSide + getBoxPadding() - 5, getBoxPadding() - 5, + paneWidth - getBoxPadding() * 2 + 10, height - getBoxPadding() * 2 + 10, itemPaneOffsetFactor.getValue() > 0.01); - Gui.drawRect(leftSide+getBoxPadding()-5, getBoxPadding()-5, - leftSide+getBoxPadding()-5+paneWidth-getBoxPadding()*2+10, - getBoxPadding()-5+height-getBoxPadding()*2+10, 0xc8101010); + Gui.drawRect(leftSide + getBoxPadding() - 5, getBoxPadding() - 5, + leftSide + getBoxPadding() - 5 + paneWidth - getBoxPadding() * 2 + 10, + getBoxPadding() - 5 + height - getBoxPadding() * 2 + 10, 0xc8101010); } - drawRect(leftSide+getBoxPadding()-5, getBoxPadding()-5, - leftSide+paneWidth-getBoxPadding()+5, height-getBoxPadding()+5, bg.getRGB()); + drawRect(leftSide + getBoxPadding() - 5, getBoxPadding() - 5, + leftSide + paneWidth - getBoxPadding() + 5, height - getBoxPadding() + 5, bg.getRGB()); - renderNavElement(leftSide+getBoxPadding()+getItemBoxXPadding(), rightSide, getMaxPages(), page+1, - Utils.peekGuiScale().getScaleFactor()<4?"Page: ":""); + renderNavElement(leftSide + getBoxPadding() + getItemBoxXPadding(), rightSide, getMaxPages(), page + 1, + Utils.peekGuiScale().getScaleFactor() < 4 ? "Page: " : ""); //Sort bar - drawRect(leftSide+getBoxPadding()+getItemBoxXPadding()-1, - height-getBoxPadding()-ITEM_SIZE-2, - rightSide+1, - height-getBoxPadding(), fgCustomOpacity.getRGB()); + drawRect(leftSide + getBoxPadding() + getItemBoxXPadding() - 1, + height - getBoxPadding() - ITEM_SIZE - 2, + rightSide + 1, + height - getBoxPadding(), fgCustomOpacity.getRGB()); - float sortIconsMinX = (sortIcons.length+orderIcons.length)*(ITEM_SIZE+ITEM_PADDING)+ITEM_SIZE; - float availableX = rightSide-(leftSide+getBoxPadding()+getItemBoxXPadding()); + float sortIconsMinX = (sortIcons.length + orderIcons.length) * (ITEM_SIZE + ITEM_PADDING) + ITEM_SIZE; + float availableX = rightSide - (leftSide + getBoxPadding() + getItemBoxXPadding()); float sortOrderScaleFactor = Math.min(1, availableX / sortIconsMinX); - int scaledITEM_SIZE = (int)(ITEM_SIZE*sortOrderScaleFactor); - int scaledItemPaddedSize = (int)((ITEM_SIZE+ITEM_PADDING)*sortOrderScaleFactor); - int iconTop = height-getBoxPadding()-(ITEM_SIZE+scaledITEM_SIZE)/2-1; + int scaledITEM_SIZE = (int) (ITEM_SIZE * sortOrderScaleFactor); + int scaledItemPaddedSize = (int) ((ITEM_SIZE + ITEM_PADDING) * sortOrderScaleFactor); + int iconTop = height - getBoxPadding() - (ITEM_SIZE + scaledITEM_SIZE) / 2 - 1; boolean hoveredOverControl = false; - for(int i=0; i iconTop && mouseY < iconTop+scaledITEM_SIZE) { - if(mouseX > orderIconX && mouseX < orderIconX+scaledITEM_SIZE) { + if (mouseY > iconTop && mouseY < iconTop + scaledITEM_SIZE) { + if (mouseX > orderIconX && mouseX < orderIconX + scaledITEM_SIZE) { hoveredOverControl = true; - if(System.currentTimeMillis() - millisLastMouseMove > 400) { - String text = EnumChatFormatting.GRAY+"Order "; - if(i == COMPARE_MODE_ALPHABETICAL) text += "Alphabetically"; - else if(i == COMPARE_MODE_RARITY) text += "by Rarity"; - else if(i == COMPARE_MODE_VALUE) text += "by Item Worth"; + if (System.currentTimeMillis() - millisLastMouseMove > 400) { + String text = EnumChatFormatting.GRAY + "Order "; + if (i == COMPARE_MODE_ALPHABETICAL) text += "Alphabetically"; + else if (i == COMPARE_MODE_RARITY) text += "by Rarity"; + else if (i == COMPARE_MODE_VALUE) text += "by Item Worth"; else text = null; - if(text != null) textToDisplay = Utils.createList(text); + if (text != null) textToDisplay = Utils.createList(text); } } } } - for(int i=0; i iconTop && mouseY < iconTop+scaledITEM_SIZE) { - if(mouseX > sortIconX && mouseX < sortIconX+scaledITEM_SIZE) { + if (mouseY > iconTop && mouseY < iconTop + scaledITEM_SIZE) { + if (mouseX > sortIconX && mouseX < sortIconX + scaledITEM_SIZE) { hoveredOverControl = true; - if(System.currentTimeMillis() - millisLastMouseMove > 400) { - String text = EnumChatFormatting.GRAY+"Filter "; - if(i == SORT_MODE_ALL) text = EnumChatFormatting.GRAY+"No Filter"; - else if(i == SORT_MODE_MOB) text += "Mobs"; - else if(i == SORT_MODE_PET) text += "Pets"; - else if(i == SORT_MODE_TOOL) text += "Tools"; - else if(i == SORT_MODE_ARMOR) text += "Armor"; - else if(i == SORT_MODE_ACCESSORY) text += "Accessories"; + if (System.currentTimeMillis() - millisLastMouseMove > 400) { + String text = EnumChatFormatting.GRAY + "Filter "; + if (i == SORT_MODE_ALL) text = EnumChatFormatting.GRAY + "No Filter"; + else if (i == SORT_MODE_MOB) text += "Mobs"; + else if (i == SORT_MODE_PET) text += "Pets"; + else if (i == SORT_MODE_TOOL) text += "Tools"; + else if (i == SORT_MODE_ARMOR) text += "Armor"; + else if (i == SORT_MODE_ACCESSORY) text += "Accessories"; else text = null; - if(text != null) textToDisplay = Utils.createList(text); + if (text != null) textToDisplay = Utils.createList(text); } } } } - if(!hoveredOverControl) { + if (!hoveredOverControl) { millisLastMouseMove = System.currentTimeMillis(); } - if(selectedItemGroup != null) { - if(mouseX < selectedItemGroupX-1 || mouseX > selectedItemGroupX+17 || - mouseY < selectedItemGroupY-1 || mouseY > selectedItemGroupY+17) { - int selectedX = Math.min(selectedItemGroupX, width-getBoxPadding()-18*selectedItemGroup.size()); - if(mouseX < selectedX-1 || mouseX > selectedX-1+18*selectedItemGroup.size() || - mouseY < selectedItemGroupY+17 || mouseY > selectedItemGroupY+35) { + if (selectedItemGroup != null) { + if (mouseX < selectedItemGroupX - 1 || mouseX > selectedItemGroupX + 17 || + mouseY < selectedItemGroupY - 1 || mouseY > selectedItemGroupY + 17) { + int selectedX = Math.min(selectedItemGroupX, width - getBoxPadding() - 18 * selectedItemGroup.size()); + if (mouseX < selectedX - 1 || mouseX > selectedX - 1 + 18 * selectedItemGroup.size() || + mouseY < selectedItemGroupY + 17 || mouseY > selectedItemGroupY + 35) { selectedItemGroup = null; selectedItemMillis = -1; } } } - if(!hoverInv) { + if (!hoverInv) { iterateItemSlots(new ItemSlotConsumer() { public void consume(int x, int y, int id) { JsonObject json = getSearchedItemPage(id); @@ -1875,14 +1883,14 @@ public class NEUOverlay extends Gui { if (mouseX > x - 1 && mouseX < x + ITEM_SIZE + 1) { if (mouseY > y - 1 && mouseY < y + ITEM_SIZE + 1) { String internalname = json.get("internalname").getAsString(); - if(searchedItemsSubgroup.containsKey(internalname)) { - if(selectedItemMillis == -1) selectedItemMillis = System.currentTimeMillis(); - if(System.currentTimeMillis() - selectedItemMillis > 200 && + if (searchedItemsSubgroup.containsKey(internalname)) { + if (selectedItemMillis == -1) selectedItemMillis = System.currentTimeMillis(); + if (System.currentTimeMillis() - selectedItemMillis > 200 && (selectedItemGroup == null || selectedItemGroup.isEmpty())) { ArrayList children = new ArrayList<>(); children.add(json); - for(String itemname : searchedItemsSubgroup.get(internalname)) { + for (String itemname : searchedItemsSubgroup.get(internalname)) { children.add(manager.getItemInformation().get(itemname)); } @@ -1901,15 +1909,15 @@ public class NEUOverlay extends Gui { //Iterate through all item slots and display the appropriate item int itemBoxXPadding = getItemBoxXPadding(); - int xStart = (int)(width*getItemPaneOffsetFactor())+getBoxPadding()+itemBoxXPadding; + int xStart = (int) (width * getItemPaneOffsetFactor()) + getBoxPadding() + itemBoxXPadding; - if(OpenGlHelper.isFramebufferEnabled()) { + if (OpenGlHelper.isFramebufferEnabled()) { renderItemsFromImage(xStart, width, height); renderEnchOverlay(); checkFramebufferSizes(width, height); - if(redrawItems || !NotEnoughUpdates.INSTANCE.config.hidden.cacheRenderedItempane) { + if (redrawItems || !NotEnoughUpdates.INSTANCE.config.hidden.cacheRenderedItempane) { renderItemsToImage(width, height, fgFavourite2, fgFavourite, fgCustomOpacity, true, true); redrawItems = false; } @@ -1917,36 +1925,36 @@ public class NEUOverlay extends Gui { renderItems(xStart, true, true, true); } - if(selectedItemGroup != null) { + if (selectedItemGroup != null) { GL11.glTranslatef(0, 0, 10); - int selectedX = Math.min(selectedItemGroupX, width-getBoxPadding()-18*selectedItemGroup.size()); + int selectedX = Math.min(selectedItemGroupX, width - getBoxPadding() - 18 * selectedItemGroup.size()); GlStateManager.enableDepth(); GlStateManager.depthFunc(GL11.GL_LESS); - drawRect(selectedX, selectedItemGroupY+18, - selectedX-2+18*selectedItemGroup.size(), selectedItemGroupY+34, fgCustomOpacity.getRGB()); - drawRect(selectedX-1, selectedItemGroupY+17, - selectedX-2+18*selectedItemGroup.size(), selectedItemGroupY+34, new Color(180, 180, 180).getRGB()); - drawRect(selectedX, selectedItemGroupY+18, - selectedX-1+18*selectedItemGroup.size(), selectedItemGroupY+35, new Color(30, 30, 30).getRGB()); - drawRect(selectedX-1+2, selectedItemGroupY+17+2, - selectedX-1+18*selectedItemGroup.size()+2, selectedItemGroupY+35+2, 0xa0000000); + drawRect(selectedX, selectedItemGroupY + 18, + selectedX - 2 + 18 * selectedItemGroup.size(), selectedItemGroupY + 34, fgCustomOpacity.getRGB()); + drawRect(selectedX - 1, selectedItemGroupY + 17, + selectedX - 2 + 18 * selectedItemGroup.size(), selectedItemGroupY + 34, new Color(180, 180, 180).getRGB()); + drawRect(selectedX, selectedItemGroupY + 18, + selectedX - 1 + 18 * selectedItemGroup.size(), selectedItemGroupY + 35, new Color(30, 30, 30).getRGB()); + drawRect(selectedX - 1 + 2, selectedItemGroupY + 17 + 2, + selectedX - 1 + 18 * selectedItemGroup.size() + 2, selectedItemGroupY + 35 + 2, 0xa0000000); GlStateManager.depthFunc(GL11.GL_LEQUAL); GL11.glTranslatef(0, 0, 10); tooltipToDisplay.set(null); - if(mouseY > selectedItemGroupY+17 && mouseY < selectedItemGroupY+35) { - for(int i=0; i= selectedX-1+18*i && mouseX <= selectedX+17+18*i) { + if (mouseY > selectedItemGroupY + 17 && mouseY < selectedItemGroupY + 35) { + for (int i = 0; i < selectedItemGroup.size(); i++) { + if (mouseX >= selectedX - 1 + 18 * i && mouseX <= selectedX + 17 + 18 * i) { tooltipToDisplay.set(selectedItemGroup.get(i)); } } } - for(int i=0; i text = stack.getTooltip(Minecraft.getMinecraft().thePlayer, false); String internalname = json.get("internalname").getAsString(); - if(!NotEnoughUpdates.INSTANCE.config.tooltipTweaks.showPriceInfoInvItem) { + if (!NotEnoughUpdates.INSTANCE.config.tooltipTweaks.showPriceInfoInvItem) { ItemPriceInformation.addToTooltip(text, internalname, stack); } boolean hasClick = false; boolean hasInfo = false; - if(json.has("clickcommand") && !json.get("clickcommand").getAsString().isEmpty()) { + if (json.has("clickcommand") && !json.get("clickcommand").getAsString().isEmpty()) { hasClick = true; } - if(json.has("info") && json.get("info").getAsJsonArray().size() > 0) { + if (json.has("info") && json.get("info").getAsJsonArray().size() > 0) { hasInfo = true; } - if(hasClick || hasInfo) text.add(""); - if(hasClick) text.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"LMB/R : View recipe!"); - if(hasInfo) text.add(EnumChatFormatting.YELLOW.toString()+EnumChatFormatting.BOLD+"RMB : View additional information!"); - + if (hasClick || hasInfo) text.add(""); + if (hasClick) + text.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "LMB/R : View recipe!"); + if (hasInfo) + text.add(EnumChatFormatting.YELLOW.toString() + EnumChatFormatting.BOLD + "RMB : View additional information!"); textToDisplay = text; } - if(textToDisplay != null) { + if (textToDisplay != null) { Utils.drawHoveringText(textToDisplay, mouseX, mouseY, width, height, -1, fr); textToDisplay = null; } @@ -2039,6 +2048,7 @@ public class NEUOverlay extends Gui { /** * Sets the current page and marks that the itemsPane should be redrawn + * * @param page */ public void setPage(int page) { @@ -2046,18 +2056,18 @@ public class NEUOverlay extends Gui { redrawItems = true; } - private Framebuffer[] itemFramebuffers = new Framebuffer[2]; + private final Framebuffer[] itemFramebuffers = new Framebuffer[2]; /** * Checks whether the screen size has changed, if so it reconstructs the itemPane framebuffer and marks that the * itemPane should be redrawn. */ private void checkFramebufferSizes(int width, int height) { - int sw = width*Utils.peekGuiScale().getScaleFactor(); - int sh = height*Utils.peekGuiScale().getScaleFactor(); - for(int i=0; i * (I tried very hard to replicate the enchant rendering overlay code from vanilla, but I couldn't get it to * work without rendering with the "ITEM" vertex model like in vanilla, so I choose to render an arbitrary 2D * item. If a texture pack sets a custom 3D model for an apple, this will probably break.) @@ -2137,66 +2149,66 @@ public class NEUOverlay extends Gui { ItemStack stack = new ItemStack(Items.apple); IBakedModel model = Minecraft.getMinecraft().getRenderItem().getItemModelMesher() .getItemModel(stack); - float f = (float)(Minecraft.getSystemTime() % 3000L) / 3000.0F / 8.0F; - float f1 = (float)(Minecraft.getSystemTime() % 4873L) / 4873.0F / 8.0F; + float f = (float) (Minecraft.getSystemTime() % 3000L) / 3000.0F / 8.0F; + float f1 = (float) (Minecraft.getSystemTime() % 4873L) / 4873.0F / 8.0F; Minecraft.getMinecraft().getTextureManager().bindTexture(RES_ITEM_GLINT); GL11.glPushMatrix(); - GL11.glTranslatef(0, 0, -7.5001f+itemRenderOffset); + GL11.glTranslatef(0, 0, -7.5001f + itemRenderOffset); iterateItemSlots(new ItemSlotConsumer() { public void consume(int x, int y, int id) { - JsonObject json = getSearchedItemPage(id); - if(json == null) { - return; - } - ItemStack stack = manager.jsonToStack(json, true, true, false); - if (stack == null || !stack.hasEffect()) { - return; - } + JsonObject json = getSearchedItemPage(id); + if (json == null) { + return; + } + ItemStack stack = manager.jsonToStack(json, true, true, false); + if (stack == null || !stack.hasEffect()) { + return; + } - GlStateManager.pushMatrix(); - GlStateManager.enableRescaleNormal(); - GlStateManager.enableAlpha(); - GlStateManager.alphaFunc(516, 0.1F); - GlStateManager.enableBlend(); + GlStateManager.pushMatrix(); + GlStateManager.enableRescaleNormal(); + GlStateManager.enableAlpha(); + GlStateManager.alphaFunc(516, 0.1F); + GlStateManager.enableBlend(); - GlStateManager.disableLighting(); + GlStateManager.disableLighting(); - GlStateManager.translate(x, y, 0); - GlStateManager.scale(16f, 16f, 16f); + GlStateManager.translate(x, y, 0); + GlStateManager.scale(16f, 16f, 16f); - GlStateManager.depthMask(false); - GlStateManager.depthFunc(GL11.GL_EQUAL); - GlStateManager.blendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE); - GlStateManager.matrixMode(5890); - GlStateManager.pushMatrix(); - GlStateManager.scale(8.0F, 8.0F, 8.0F); - GlStateManager.translate(f, 0.0F, 0.0F); - GlStateManager.rotate(-50.0F, 0.0F, 0.0F, 1.0F); + GlStateManager.depthMask(false); + GlStateManager.depthFunc(GL11.GL_EQUAL); + GlStateManager.blendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE); + GlStateManager.matrixMode(5890); + GlStateManager.pushMatrix(); + GlStateManager.scale(8.0F, 8.0F, 8.0F); + GlStateManager.translate(f, 0.0F, 0.0F); + GlStateManager.rotate(-50.0F, 0.0F, 0.0F, 1.0F); - renderModel(model, -8372020, null); + renderModel(model, -8372020, null); - GlStateManager.popMatrix(); - GlStateManager.pushMatrix(); - GlStateManager.scale(8.0F, 8.0F, 8.0F); - GlStateManager.translate(-f1, 0.0F, 0.0F); - GlStateManager.rotate(10.0F, 0.0F, 0.0F, 1.0F); + GlStateManager.popMatrix(); + GlStateManager.pushMatrix(); + GlStateManager.scale(8.0F, 8.0F, 8.0F); + GlStateManager.translate(-f1, 0.0F, 0.0F); + GlStateManager.rotate(10.0F, 0.0F, 0.0F, 1.0F); - renderModel(model, -8372020, null); + renderModel(model, -8372020, null); - GlStateManager.popMatrix(); - GlStateManager.matrixMode(5888); - GlStateManager.blendFunc(770, 771); - GlStateManager.depthFunc(515); - GlStateManager.depthMask(true); + GlStateManager.popMatrix(); + GlStateManager.matrixMode(5888); + GlStateManager.blendFunc(770, 771); + GlStateManager.depthFunc(515); + GlStateManager.depthMask(true); - GlStateManager.popMatrix(); + GlStateManager.popMatrix(); } }); GlStateManager.disableBlend(); GlStateManager.disableAlpha(); GlStateManager.disableRescaleNormal(); - GL11.glTranslatef(0, 0, 7.5001f-itemRenderOffset); + GL11.glTranslatef(0, 0, 7.5001f - itemRenderOffset); GL11.glPopMatrix(); GlStateManager.bindTexture(0); @@ -2217,9 +2229,9 @@ public class NEUOverlay extends Gui { } private void renderQuads(WorldRenderer renderer, List quads, int color) { - if(quads == null) return; + if (quads == null) return; - for(BakedQuad quad : quads) { + for (BakedQuad quad : quads) { renderer.addVertexData(quad.getVertexData()); renderer.putColor4(color); } @@ -2229,38 +2241,38 @@ public class NEUOverlay extends Gui { * Renders all the item backgrounds, either squares or squircles. */ private void renderItemBackgrounds(Color fgFavourite2, Color fgFavourite, Color fgCustomOpacity) { - if(fgCustomOpacity.getAlpha() == 0) return; + if (fgCustomOpacity.getAlpha() == 0) return; iterateItemSlots(new ItemSlotConsumer() { public void consume(int x, int y, int id) { - JsonObject json = getSearchedItemPage(id); - if (json == null) { - return; - } + JsonObject json = getSearchedItemPage(id); + if (json == null) { + return; + } - Minecraft.getMinecraft().getTextureManager().bindTexture(item_mask); - if (getFavourites().contains(json.get("internalname").getAsString())) { - if(NotEnoughUpdates.INSTANCE.config.itemlist.itemStyle == 0) { - GlStateManager.color(fgFavourite2.getRed() / 255f, fgFavourite2.getGreen() / 255f, - fgFavourite2.getBlue() / 255f, fgFavourite2.getAlpha() / 255f); - Utils.drawTexturedRect(x - 1, y - 1, ITEM_SIZE + 2, ITEM_SIZE + 2, GL11.GL_NEAREST); + Minecraft.getMinecraft().getTextureManager().bindTexture(item_mask); + if (getFavourites().contains(json.get("internalname").getAsString())) { + if (NotEnoughUpdates.INSTANCE.config.itemlist.itemStyle == 0) { + GlStateManager.color(fgFavourite2.getRed() / 255f, fgFavourite2.getGreen() / 255f, + fgFavourite2.getBlue() / 255f, fgFavourite2.getAlpha() / 255f); + Utils.drawTexturedRect(x - 1, y - 1, ITEM_SIZE + 2, ITEM_SIZE + 2, GL11.GL_NEAREST); - GlStateManager.color(fgFavourite.getRed() / 255f, fgFavourite.getGreen() / 255f, - fgFavourite.getBlue() / 255f, fgFavourite.getAlpha() / 255f); - Utils.drawTexturedRect(x, y, ITEM_SIZE, ITEM_SIZE, GL11.GL_NEAREST); - } else { - drawRect(x-1, y-1, x+ITEM_SIZE+1, y+ITEM_SIZE+1, fgFavourite2.getRGB()); - drawRect(x, y, x+ITEM_SIZE, y+ITEM_SIZE, fgFavourite.getRGB()); - } - } else { - if(NotEnoughUpdates.INSTANCE.config.itemlist.itemStyle == 0) { - GlStateManager.color(fgCustomOpacity.getRed() / 255f, fgCustomOpacity.getGreen() / 255f, - fgCustomOpacity.getBlue() / 255f, fgCustomOpacity.getAlpha() / 255f); - Utils.drawTexturedRect(x - 1, y - 1, ITEM_SIZE + 2, ITEM_SIZE + 2, GL11.GL_NEAREST); + GlStateManager.color(fgFavourite.getRed() / 255f, fgFavourite.getGreen() / 255f, + fgFavourite.getBlue() / 255f, fgFavourite.getAlpha() / 255f); + Utils.drawTexturedRect(x, y, ITEM_SIZE, ITEM_SIZE, GL11.GL_NEAREST); + } else { + drawRect(x - 1, y - 1, x + ITEM_SIZE + 1, y + ITEM_SIZE + 1, fgFavourite2.getRGB()); + drawRect(x, y, x + ITEM_SIZE, y + ITEM_SIZE, fgFavourite.getRGB()); + } } else { - drawRect(x-1, y-1, x+ITEM_SIZE+1, y+ITEM_SIZE+1, fgCustomOpacity.getRGB()); + if (NotEnoughUpdates.INSTANCE.config.itemlist.itemStyle == 0) { + GlStateManager.color(fgCustomOpacity.getRed() / 255f, fgCustomOpacity.getGreen() / 255f, + fgCustomOpacity.getBlue() / 255f, fgCustomOpacity.getAlpha() / 255f); + Utils.drawTexturedRect(x - 1, y - 1, ITEM_SIZE + 2, ITEM_SIZE + 2, GL11.GL_NEAREST); + } else { + drawRect(x - 1, y - 1, x + ITEM_SIZE + 1, y + ITEM_SIZE + 1, fgCustomOpacity.getRGB()); + } } - } - GlStateManager.bindTexture(0); + GlStateManager.bindTexture(0); } }, 10); } @@ -2274,7 +2286,7 @@ public class NEUOverlay extends Gui { } if (json.has("entityrender")) { - if(!entities) return; + if (!entities) return; String name = json.get("displayname").getAsString(); String[] split = name.split(" \\("); name = name.substring(0, name.length() - split[split.length - 1].length() - 2); @@ -2303,10 +2315,10 @@ public class NEUOverlay extends Gui { renderEntity(x + ITEM_SIZE / 2, y + ITEM_SIZE, scale, name, entities); } else { - if(!items) return; + if (!items) return; ItemStack stack = manager.jsonToStack(json, true, true, false); - if(stack != null) { - if(glint) { + if (stack != null) { + if (glint) { Utils.drawItemStack(stack, x, y); } else { Utils.drawItemStackWithoutGlint(stack, x, y); @@ -2315,10 +2327,10 @@ public class NEUOverlay extends Gui { } GlStateManager.translate(0, 0, 50); - if(searchedItemsSubgroup.containsKey(json.get("internalname").getAsString())) { + if (searchedItemsSubgroup.containsKey(json.get("internalname").getAsString())) { Minecraft.getMinecraft().getTextureManager().bindTexture(item_haschild); GlStateManager.color(1, 1, 1, 1); - Utils.drawTexturedRect(x-1, y-1, ITEM_SIZE+2, ITEM_SIZE+2, GL11.GL_NEAREST); + Utils.drawTexturedRect(x - 1, y - 1, ITEM_SIZE + 2, ITEM_SIZE + 2, GL11.GL_NEAREST); } GlStateManager.translate(0, 0, -50); } @@ -2326,7 +2338,7 @@ public class NEUOverlay extends Gui { } public float getItemPaneOffsetFactor() { - return itemPaneOffsetFactor.getValue() * getWidthMult() + (1-getWidthMult()); + return itemPaneOffsetFactor.getValue() * getWidthMult() + (1 - getWidthMult()); } public float getInfoPaneOffsetFactor() { diff --git a/src/main/java/io/github/moulberry/notenoughupdates/NotEnoughUpdates.java b/src/main/java/io/github/moulberry/notenoughupdates/NotEnoughUpdates.java index 6a0d3ab4..29eaf38e 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/NotEnoughUpdates.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/NotEnoughUpdates.java @@ -1,85 +1,45 @@ package io.github.moulberry.notenoughupdates; -import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import io.github.moulberry.notenoughupdates.auction.CustomAHGui; -import io.github.moulberry.notenoughupdates.collectionlog.GuiCollectionLog; import io.github.moulberry.notenoughupdates.commands.Commands; -import io.github.moulberry.notenoughupdates.commands.SimpleCommand; import io.github.moulberry.notenoughupdates.core.BackgroundBlur; -import io.github.moulberry.notenoughupdates.core.GuiScreenElementWrapper; -import io.github.moulberry.notenoughupdates.core.config.GuiPositionEditor; -import io.github.moulberry.notenoughupdates.core.util.MiscUtils; import io.github.moulberry.notenoughupdates.cosmetics.CapeManager; -import io.github.moulberry.notenoughupdates.cosmetics.GuiCosmetics; import io.github.moulberry.notenoughupdates.dungeons.DungeonMap; -import io.github.moulberry.notenoughupdates.dungeons.DungeonWin; -import io.github.moulberry.notenoughupdates.dungeons.GuiDungeonMapEditor; -import io.github.moulberry.notenoughupdates.gamemodes.GuiGamemodes; import io.github.moulberry.notenoughupdates.miscfeatures.*; -import io.github.moulberry.notenoughupdates.miscgui.*; -import io.github.moulberry.notenoughupdates.miscgui.tutorials.NeuTutorial; +import io.github.moulberry.notenoughupdates.miscgui.CalendarOverlay; +import io.github.moulberry.notenoughupdates.miscgui.InventoryStorageSelector; import io.github.moulberry.notenoughupdates.options.NEUConfig; -import io.github.moulberry.notenoughupdates.options.NEUConfigEditor; import io.github.moulberry.notenoughupdates.overlays.FuelBar; import io.github.moulberry.notenoughupdates.overlays.OverlayManager; -import io.github.moulberry.notenoughupdates.profileviewer.GuiProfileViewer; -import io.github.moulberry.notenoughupdates.profileviewer.PlayerStats; import io.github.moulberry.notenoughupdates.profileviewer.ProfileViewer; import io.github.moulberry.notenoughupdates.util.SBInfo; -import io.github.moulberry.notenoughupdates.util.Constants; import io.github.moulberry.notenoughupdates.util.Utils; import io.github.moulberry.notenoughupdates.util.XPInformation; -import net.minecraft.block.material.MapColor; import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.AbstractClientPlayer; -import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.resources.IReloadableResourceManager; import net.minecraft.client.settings.KeyBinding; -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayer; import net.minecraft.event.ClickEvent; -import net.minecraft.item.ItemMap; -import net.minecraft.item.ItemStack; import net.minecraft.scoreboard.ScoreObjective; import net.minecraft.scoreboard.Scoreboard; -import net.minecraft.util.*; -import net.minecraft.world.storage.MapData; -import net.minecraftforge.client.ClientCommandHandler; -import net.minecraftforge.common.ForgeVersion; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.EnumChatFormatting; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.client.registry.ClientRegistry; -import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; -import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.text.WordUtils; -import org.lwjgl.opengl.Display; -import org.lwjgl.opengl.GL11; import java.awt.*; -import java.awt.datatransfer.StringSelection; import java.io.*; -import java.lang.management.ManagementFactory; -import java.net.URI; -import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; -import java.util.*; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.HashMap; +import java.util.Set; @Mod(modid = NotEnoughUpdates.MODID, version = NotEnoughUpdates.VERSION, clientSideOnly = true) public class NotEnoughUpdates { @@ -97,10 +57,11 @@ public class NotEnoughUpdates { private File configFile; - public File getConfigFile(){ + public File getConfigFile() { return this.configFile; } - public void newConfigFile(){ + + public void newConfigFile() { this.configFile = new File(NotEnoughUpdates.INSTANCE.getNeuDir(), "configNew.json"); } @@ -110,16 +71,15 @@ public class NotEnoughUpdates { private String currChatMessage = null; //Stolen from Biscut and used for detecting whether in skyblock - private static final Set SKYBLOCK_IN_ALL_LANGUAGES = Sets.newHashSet("SKYBLOCK","\u7A7A\u5C9B\u751F\u5B58", "\u7A7A\u5CF6\u751F\u5B58"); + private static final Set SKYBLOCK_IN_ALL_LANGUAGES = Sets.newHashSet("SKYBLOCK", "\u7A7A\u5C9B\u751F\u5B58", "\u7A7A\u5CF6\u751F\u5B58"); public GuiScreen openGui = null; public long lastOpenedGui = 0; public Commands commands; - - public static HashMap petRarityToColourMap = new HashMap<>(); + static { petRarityToColourMap.put("UNKNOWN", EnumChatFormatting.RED.toString()); @@ -135,15 +95,16 @@ public class NotEnoughUpdates { public boolean packDevEnabled = false; - private Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create(); + private final Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create(); private File neuDir; - public File getNeuDir(){ return this.neuDir;} + public File getNeuDir() {return this.neuDir;} public Color[][] colourMap = null; /** * Instantiates NEUIo, NEUManager and NEUOverlay instances. Registers keybinds and adds a shutdown hook to clear tmp folder. + * * @param event */ @EventHandler @@ -155,10 +116,10 @@ public class NotEnoughUpdates { configFile = new File(neuDir, "configNew.json"); - if(configFile.exists()) { - try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(configFile), StandardCharsets.UTF_8))) { + if (configFile.exists()) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(configFile), StandardCharsets.UTF_8))) { config = gson.fromJson(reader, NEUConfig.class); - } catch(Exception e) { } + } catch (Exception ignored) {} } ItemCustomizeManager.loadCustomization(new File(neuDir, "itemCustomization.json")); @@ -167,7 +128,7 @@ public class NotEnoughUpdates { PetInfoOverlay.loadConfig(new File(neuDir, "petCache.json")); SlotLocking.getInstance().loadConfig(new File(neuDir, "slotLocking.json")); - if(config == null) { + if (config == null) { config = new NEUConfig(); saveConfig(); } @@ -198,10 +159,10 @@ public class NotEnoughUpdates { MinecraftForge.EVENT_BUS.register(SlotLocking.getInstance()); MinecraftForge.EVENT_BUS.register(FishingHelper.getInstance()); - if(Minecraft.getMinecraft().getResourceManager() instanceof IReloadableResourceManager) { - ((IReloadableResourceManager)Minecraft.getMinecraft().getResourceManager()).registerReloadListener(CustomSkulls.getInstance()); - ((IReloadableResourceManager)Minecraft.getMinecraft().getResourceManager()).registerReloadListener(NPCRetexturing.getInstance()); - ((IReloadableResourceManager)Minecraft.getMinecraft().getResourceManager()).registerReloadListener(new ItemCustomizeManager.ReloadListener()); + if (Minecraft.getMinecraft().getResourceManager() instanceof IReloadableResourceManager) { + ((IReloadableResourceManager) Minecraft.getMinecraft().getResourceManager()).registerReloadListener(CustomSkulls.getInstance()); + ((IReloadableResourceManager) Minecraft.getMinecraft().getResourceManager()).registerReloadListener(NPCRetexturing.getInstance()); + ((IReloadableResourceManager) Minecraft.getMinecraft().getResourceManager()).registerReloadListener(new ItemCustomizeManager.ReloadListener()); } this.commands = new Commands(); @@ -213,14 +174,14 @@ public class NotEnoughUpdates { overlay = new NEUOverlay(manager); profileViewer = new ProfileViewer(manager); - for(KeyBinding kb : manager.keybinds) { + for (KeyBinding kb : manager.keybinds) { ClientRegistry.registerKeyBinding(kb); } Runtime.getRuntime().addShutdownHook(new Thread(() -> { File tmp = new File(neuDir, "tmp"); - if(tmp.exists()) { - for(File tmpFile : tmp.listFiles()) { + if (tmp.exists()) { + for (File tmpFile : tmp.listFiles()) { tmpFile.delete(); } tmp.delete(); @@ -233,16 +194,26 @@ public class NotEnoughUpdates { try { configFile.createNewFile(); - try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(configFile), StandardCharsets.UTF_8))) { + try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(configFile), StandardCharsets.UTF_8))) { writer.write(gson.toJson(config)); } - } catch(Exception ignored) {} + } catch (Exception ignored) {} - try { ItemCustomizeManager.saveCustomization(new File(neuDir, "itemCustomization.json")); } catch(Exception ignored) {} - try { StorageManager.getInstance().saveConfig(new File(neuDir, "storageItems.json")); } catch(Exception ignored) {} - try { FairySouls.save(new File(neuDir, "collected_fairy_souls.json"), gson); } catch(Exception ignored) {} - try { PetInfoOverlay.saveConfig(new File(neuDir, "petCache.json")); } catch(Exception ignored) {} - try { SlotLocking.getInstance().saveConfig(new File(neuDir, "slotLocking.json")); } catch(Exception ignored) {} + try { + ItemCustomizeManager.saveCustomization(new File(neuDir, "itemCustomization.json")); + } catch (Exception ignored) {} + try { + StorageManager.getInstance().saveConfig(new File(neuDir, "storageItems.json")); + } catch (Exception ignored) {} + try { + FairySouls.save(new File(neuDir, "collected_fairy_souls.json"), gson); + } catch (Exception ignored) {} + try { + PetInfoOverlay.saveConfig(new File(neuDir, "petCache.json")); + } catch (Exception ignored) {} + try { + SlotLocking.getInstance().saveConfig(new File(neuDir, "slotLocking.json")); + } catch (Exception ignored) {} } /** @@ -250,7 +221,7 @@ public class NotEnoughUpdates { * If the last chat message was sent <200 ago, will cache the message for #onTick to handle. */ public void sendChatMessage(String message) { - if(System.currentTimeMillis() - lastChatMessage > CHAT_MSG_COOLDOWN) { + if (System.currentTimeMillis() - lastChatMessage > CHAT_MSG_COOLDOWN) { secondLastChatMessage = lastChatMessage; lastChatMessage = System.currentTimeMillis(); Minecraft.getMinecraft().thePlayer.sendChatMessage(message); @@ -270,22 +241,22 @@ public class NotEnoughUpdates { String other_link = update.get("other_link").getAsString(); ChatComponentText other = null; - if(other_text.length() > 0) { - other = new ChatComponentText(EnumChatFormatting.GRAY+"["+EnumChatFormatting.BLUE+other_text+EnumChatFormatting.GRAY+"]"); + if (other_text.length() > 0) { + other = new ChatComponentText(EnumChatFormatting.GRAY + "[" + EnumChatFormatting.BLUE + other_text + EnumChatFormatting.GRAY + "]"); other.setChatStyle(Utils.createClickStyle(ClickEvent.Action.OPEN_URL, other_link)); } ChatComponentText links = new ChatComponentText(""); ChatComponentText separator = new ChatComponentText( - EnumChatFormatting.GRAY+EnumChatFormatting.BOLD.toString()+EnumChatFormatting.STRIKETHROUGH+(other==null?"--":"-")); - ChatComponentText discord = new ChatComponentText(EnumChatFormatting.GRAY+"["+EnumChatFormatting.BLUE+"Discord"+EnumChatFormatting.GRAY+"]"); + EnumChatFormatting.GRAY + EnumChatFormatting.BOLD.toString() + EnumChatFormatting.STRIKETHROUGH + (other == null ? "--" : "-")); + ChatComponentText discord = new ChatComponentText(EnumChatFormatting.GRAY + "[" + EnumChatFormatting.BLUE + "Discord" + EnumChatFormatting.GRAY + "]"); discord.setChatStyle(Utils.createClickStyle(ClickEvent.Action.OPEN_URL, discord_link)); - ChatComponentText youtube = new ChatComponentText(EnumChatFormatting.GRAY+"["+EnumChatFormatting.RED+"YouTube"+EnumChatFormatting.GRAY+"]"); + ChatComponentText youtube = new ChatComponentText(EnumChatFormatting.GRAY + "[" + EnumChatFormatting.RED + "YouTube" + EnumChatFormatting.GRAY + "]"); youtube.setChatStyle(Utils.createClickStyle(ClickEvent.Action.OPEN_URL, youtube_link)); - ChatComponentText twitch = new ChatComponentText(EnumChatFormatting.GRAY+"["+EnumChatFormatting.DARK_PURPLE+"Twitch"+EnumChatFormatting.GRAY+"]"); + ChatComponentText twitch = new ChatComponentText(EnumChatFormatting.GRAY + "[" + EnumChatFormatting.DARK_PURPLE + "Twitch" + EnumChatFormatting.GRAY + "]"); twitch.setChatStyle(Utils.createClickStyle(ClickEvent.Action.OPEN_URL, twitch_link)); - ChatComponentText release = new ChatComponentText(EnumChatFormatting.GRAY+"["+EnumChatFormatting.GREEN+"Release"+EnumChatFormatting.GRAY+"]"); + ChatComponentText release = new ChatComponentText(EnumChatFormatting.GRAY + "[" + EnumChatFormatting.GREEN + "Release" + EnumChatFormatting.GRAY + "]"); release.setChatStyle(Utils.createClickStyle(ClickEvent.Action.OPEN_URL, update_link)); - ChatComponentText github = new ChatComponentText(EnumChatFormatting.GRAY+"["+EnumChatFormatting.DARK_PURPLE+"GitHub"+EnumChatFormatting.GRAY+"]"); + ChatComponentText github = new ChatComponentText(EnumChatFormatting.GRAY + "[" + EnumChatFormatting.DARK_PURPLE + "GitHub" + EnumChatFormatting.GRAY + "]"); github.setChatStyle(Utils.createClickStyle(ClickEvent.Action.OPEN_URL, github_link)); links.appendSibling(separator); @@ -299,7 +270,7 @@ public class NotEnoughUpdates { links.appendSibling(separator); links.appendSibling(github); links.appendSibling(separator); - if(other != null) { + if (other != null) { links.appendSibling(other); links.appendSibling(separator); } @@ -310,7 +281,7 @@ public class NotEnoughUpdates { @SubscribeEvent public void onTick(TickEvent.ClientTickEvent event) { if (event.phase != TickEvent.Phase.START) return; - if(Minecraft.getMinecraft().thePlayer == null) { + if (Minecraft.getMinecraft().thePlayer == null) { openGui = null; currChatMessage = null; return; @@ -318,14 +289,14 @@ public class NotEnoughUpdates { long currentTime = System.currentTimeMillis(); if (openGui != null) { - if(Minecraft.getMinecraft().thePlayer.openContainer != null) { + if (Minecraft.getMinecraft().thePlayer.openContainer != null) { Minecraft.getMinecraft().thePlayer.closeScreen(); } Minecraft.getMinecraft().displayGuiScreen(openGui); openGui = null; lastOpenedGui = System.currentTimeMillis(); } - if(currChatMessage != null && currentTime - lastChatMessage > CHAT_MSG_COOLDOWN) { + if (currChatMessage != null && currentTime - lastChatMessage > CHAT_MSG_COOLDOWN) { lastChatMessage = currentTime; Minecraft.getMinecraft().thePlayer.sendChatMessage(currChatMessage); currChatMessage = null; @@ -333,7 +304,7 @@ public class NotEnoughUpdates { } public boolean isOnSkyblock() { - if(!config.misc.onlyShowOnSkyblock) return true; + if (!config.misc.onlyShowOnSkyblock) return true; return hasSkyblockScoreboard(); } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/auction/APIManager.java b/src/main/java/io/github/moulberry/notenoughupdates/auction/APIManager.java index 9351b208..6b421192 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/auction/APIManager.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/auction/APIManager.java @@ -26,19 +26,18 @@ import java.io.IOException; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; public class APIManager { - private NEUManager manager; + private final NEUManager manager; public final CustomAH customAH; - private TreeMap auctionMap = new TreeMap<>(); + private final TreeMap auctionMap = new TreeMap<>(); public HashMap> internalnameToAucIdMap = new HashMap<>(); - private HashSet playerBids = new HashSet<>(); - private HashSet playerBidsNotified = new HashSet<>(); - private HashSet playerBidsFinishedNotified = new HashSet<>(); + private final HashSet playerBids = new HashSet<>(); + private final HashSet playerBidsNotified = new HashSet<>(); + private final HashSet playerBidsFinishedNotified = new HashSet<>(); private JsonObject lowestBins = null; private JsonObject auctionPricesAvgLowestBinJson = null; @@ -47,7 +46,7 @@ public class APIManager { private JsonObject bazaarJson = null; private JsonObject auctionPricesJson = null; - private HashMap craftCost = new HashMap<>(); + private final HashMap craftCost = new HashMap<>(); public TreeMap>> extrasToAucIdMap = new TreeMap<>(); @@ -117,16 +116,16 @@ public class APIManager { } public ItemStack getStack() { - if(item_tag == null && item_tag_str != null) { + if (item_tag == null && item_tag_str != null) { try { item_tag = CompressedStreamTools.readCompressed( new ByteArrayInputStream(Base64.getDecoder().decode(item_tag_str))); item_tag_str = null; - } catch(IOException e) { + } catch (IOException e) { return null; } } - if(stack != null) { + if (stack != null) { return stack; } else { JsonObject item = manager.getJsonFromNBT(item_tag); @@ -134,24 +133,24 @@ public class APIManager { JsonObject itemDefault = manager.getItemInformation().get(item.get("internalname").getAsString()); - if(stack != null && itemDefault != null) { + if (stack != null && itemDefault != null) { ItemStack stackDefault = manager.jsonToStack(itemDefault, true); - if(stack.isItemEqual(stackDefault)) { + if (stack.isItemEqual(stackDefault)) { //Item types are the same, compare lore String[] stackLore = manager.getLoreFromNBT(stack.getTagCompound()); String[] defaultLore = manager.getLoreFromNBT(stackDefault.getTagCompound()); boolean loreMatches = stackLore != null && defaultLore != null && stackLore.length == defaultLore.length; - if(loreMatches) { - for(int i=0; i 60*1000) { + if (currentTime - lastAuctionUpdate > 60 * 1000) { lastAuctionUpdate = currentTime; updatePageTick(); } - if(currentTime - lastShortAuctionUpdate > 10*1000) { + if (currentTime - lastShortAuctionUpdate > 10 * 1000) { lastShortAuctionUpdate = currentTime; updatePageTickShort(); ahNotification(); } - if(currentTime - lastCleanup > 60*1000) { + if (currentTime - lastCleanup > 60 * 1000) { lastCleanup = currentTime; cleanup(); } - if(currentTime - lastCustomAHSearch > 60*1000) { + if (currentTime - lastCustomAHSearch > 60 * 1000) { lastCustomAHSearch = currentTime; - if(Minecraft.getMinecraft().currentScreen instanceof CustomAHGui || customAH.isRenderOverAuctionView()) { + if (Minecraft.getMinecraft().currentScreen instanceof CustomAHGui || customAH.isRenderOverAuctionView()) { customAH.updateSearch(); calculateStats(); } } } - if(currentTime - lastAuctionAvgUpdate > 5*60*1000) { //5 minutes - lastAuctionAvgUpdate = currentTime - 4*60*1000; //Try again in 1 minute if updateAvgPrices doesn't succeed + if (currentTime - lastAuctionAvgUpdate > 5 * 60 * 1000) { //5 minutes + lastAuctionAvgUpdate = currentTime - 4 * 60 * 1000; //Try again in 1 minute if updateAvgPrices doesn't succeed updateAvgPrices(); } - if(currentTime - lastBazaarUpdate > 5*60*1000) { //5 minutes + if (currentTime - lastBazaarUpdate > 5 * 60 * 1000) { //5 minutes lastBazaarUpdate = currentTime; updateBazaar(); } - if(currentTime - lastLowestBinUpdate > 2*60*1000) { + if (currentTime - lastLowestBinUpdate > 2 * 60 * 1000) { lastLowestBinUpdate = currentTime; updateLowestBin(); } } private String niceAucId(String aucId) { - if(aucId.length()!=32) return aucId; + if (aucId.length() != 32) return aucId; StringBuilder niceAucId = new StringBuilder(); niceAucId.append(aucId, 0, 8); @@ -229,18 +228,18 @@ public class APIManager { } public Set getLowestBinKeySet() { - if(lowestBins == null) return new HashSet<>(); + if (lowestBins == null) return new HashSet<>(); HashSet keys = new HashSet<>(); - for(Map.Entry entry : lowestBins.entrySet()) { + for (Map.Entry entry : lowestBins.entrySet()) { keys.add(entry.getKey()); } return keys; } public int getLowestBin(String internalname) { - if(lowestBins != null && lowestBins.has(internalname)) { + if (lowestBins != null && lowestBins.has(internalname)) { JsonElement e = lowestBins.get(internalname); - if(e.isJsonPrimitive() && e.getAsJsonPrimitive().isNumber()) { + if (e.isJsonPrimitive() && e.getAsJsonPrimitive().isNumber()) { return e.getAsInt(); } } @@ -249,10 +248,10 @@ public class APIManager { public void updateLowestBin() { manager.hypixelApi.getMyApiGZIPAsync("lowestbin.json.gz", (jsonObject) -> { - if(lowestBins == null) { + if (lowestBins == null) { lowestBins = new JsonObject(); } - for(Map.Entry entry : jsonObject.entrySet()) { + for (Map.Entry entry : jsonObject.entrySet()) { lowestBins.add(entry.getKey(), entry.getValue()); } }, () -> {}); @@ -261,31 +260,31 @@ public class APIManager { private void ahNotification() { playerBidsNotified.retainAll(playerBids); playerBidsFinishedNotified.retainAll(playerBids); - if(NotEnoughUpdates.INSTANCE.config.neuAuctionHouse.ahNotification <= 0) { + if (NotEnoughUpdates.INSTANCE.config.neuAuctionHouse.ahNotification <= 0) { return; } - for(String aucid : playerBids) { + for (String aucid : playerBids) { Auction auc = auctionMap.get(aucid); - if(!playerBidsNotified.contains(aucid)) { - if(auc != null && auc.end - System.currentTimeMillis() < 1000*60*NotEnoughUpdates.INSTANCE.config.neuAuctionHouse.ahNotification) { + if (!playerBidsNotified.contains(aucid)) { + if (auc != null && auc.end - System.currentTimeMillis() < 1000 * 60 * NotEnoughUpdates.INSTANCE.config.neuAuctionHouse.ahNotification) { ChatComponentText message = new ChatComponentText( - EnumChatFormatting.YELLOW+"The " + auc.getStack().getDisplayName() + EnumChatFormatting.YELLOW + " you have bid on is ending soon! Click here to view."); + EnumChatFormatting.YELLOW + "The " + auc.getStack().getDisplayName() + EnumChatFormatting.YELLOW + " you have bid on is ending soon! Click here to view."); ChatStyle clickEvent = new ChatStyle().setChatClickEvent( new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/viewauction " + niceAucId(aucid))); - clickEvent.setChatHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ChatComponentText(EnumChatFormatting.YELLOW+"View auction"))); + clickEvent.setChatHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ChatComponentText(EnumChatFormatting.YELLOW + "View auction"))); message.setChatStyle(clickEvent); Minecraft.getMinecraft().thePlayer.addChatMessage(message); playerBidsNotified.add(aucid); } } - if(!playerBidsFinishedNotified.contains(aucid)) { - if(auc != null && auc.end < System.currentTimeMillis()) { + if (!playerBidsFinishedNotified.contains(aucid)) { + if (auc != null && auc.end < System.currentTimeMillis()) { ChatComponentText message = new ChatComponentText( - EnumChatFormatting.YELLOW+"The " + auc.getStack().getDisplayName() + EnumChatFormatting.YELLOW + " you have bid on (might) have ended! Click here to view."); + EnumChatFormatting.YELLOW + "The " + auc.getStack().getDisplayName() + EnumChatFormatting.YELLOW + " you have bid on (might) have ended! Click here to view."); ChatStyle clickEvent = new ChatStyle().setChatClickEvent( new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/viewauction " + niceAucId(aucid))); - clickEvent.setChatHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ChatComponentText(EnumChatFormatting.YELLOW+"View auction"))); + clickEvent.setChatHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ChatComponentText(EnumChatFormatting.YELLOW + "View auction"))); message.setChatStyle(clickEvent); Minecraft.getMinecraft().thePlayer.addChatMessage(message); @@ -295,76 +294,78 @@ public class APIManager { } } - private ExecutorService es = Executors.newSingleThreadExecutor(); + private final ExecutorService es = Executors.newSingleThreadExecutor(); + private void cleanup() { es.submit(() -> { try { long currTime = System.currentTimeMillis(); Set toRemove = new HashSet<>(); - for(Map.Entry entry : auctionMap.entrySet()) { + for (Map.Entry entry : auctionMap.entrySet()) { long timeToEnd = entry.getValue().end - currTime; - if(timeToEnd < -120*1000) { //2 minutes + if (timeToEnd < -120 * 1000) { //2 minutes toRemove.add(entry.getKey()); } } toRemove.removeAll(playerBids); remove(toRemove); - } catch(ConcurrentModificationException e) { - lastCleanup = System.currentTimeMillis() - 110*1000; + } catch (ConcurrentModificationException e) { + lastCleanup = System.currentTimeMillis() - 110 * 1000; } }); } private void remove(Set toRemove) { - for(String aucid : toRemove) { + for (String aucid : toRemove) { auctionMap.remove(aucid); } - for(HashMap> extrasMap : extrasToAucIdMap.values()) { - for(HashSet aucids : extrasMap.values()) { - for(String aucid : toRemove) { + for (HashMap> extrasMap : extrasToAucIdMap.values()) { + for (HashSet aucids : extrasMap.values()) { + for (String aucid : toRemove) { aucids.remove(aucid); } } } - for(HashSet aucids : internalnameToAucIdMap.values()) { + for (HashSet aucids : internalnameToAucIdMap.values()) { aucids.removeAll(toRemove); } } private void updatePageTickShort() { - if(pagesToDownload == null || pagesToDownload.isEmpty()) return; + if (pagesToDownload == null || pagesToDownload.isEmpty()) return; - if(firstHypixelApiUpdate == 0 || (System.currentTimeMillis() - firstHypixelApiUpdate)%(60*1000) > 15*1000) return; + if (firstHypixelApiUpdate == 0 || (System.currentTimeMillis() - firstHypixelApiUpdate) % (60 * 1000) > 15 * 1000) + return; JsonObject disable = Constants.DISABLE; - if(disable != null && disable.has("auctions_new") && disable.get("auctions_new").getAsBoolean()) return; + if (disable != null && disable.has("auctions_new") && disable.get("auctions_new").getAsBoolean()) return; - while(!pagesToDownload.isEmpty()) { + while (!pagesToDownload.isEmpty()) { try { int page = pagesToDownload.pop(); getPageFromAPI(page); - } catch(NoSuchElementException ignored) {} //Weird race condition? + } catch (NoSuchElementException ignored) {} //Weird race condition? } } private void updatePageTick() { JsonObject disable = Constants.DISABLE; - if(disable != null && disable.has("auctions_new") && disable.get("auctions_new").getAsBoolean()) return; + if (disable != null && disable.has("auctions_new") && disable.get("auctions_new").getAsBoolean()) return; - if(pagesToDownload == null) { + if (pagesToDownload == null) { getPageFromAPI(0); } Consumer process = jsonObject -> { - if(jsonObject.get("success").getAsBoolean()) { + if (jsonObject.get("success").getAsBoolean()) { JsonArray new_auctions = jsonObject.get("new_auctions").getAsJsonArray(); - for(JsonElement auctionElement : new_auctions) { + for (JsonElement auctionElement : new_auctions) { JsonObject auction = auctionElement.getAsJsonObject(); //System.out.println("New auction " + auction); processAuction(auction); } JsonArray new_bids = jsonObject.get("new_bids").getAsJsonArray(); - for(JsonElement newBidElement : new_bids) { + for (JsonElement newBidElement : new_bids) { JsonObject newBid = newBidElement.getAsJsonObject(); String newBidUUID = newBid.get("uuid").getAsString(); //System.out.println("new bid" + newBidUUID); @@ -373,7 +374,7 @@ public class APIManager { int bid_count = newBid.get("bid_count").getAsInt(); Auction auc = auctionMap.get(newBidUUID); - if(auc != null) { + if (auc != null) { //System.out.println("Setting auction " + newBidUUID + " price to " + newBidAmount); auc.highest_bid_amount = newBidAmount; auc.end = end; @@ -382,7 +383,7 @@ public class APIManager { } Set toRemove = new HashSet<>(); JsonArray removed_auctions = jsonObject.get("removed_auctions").getAsJsonArray(); - for(JsonElement removedAuctionsElement : removed_auctions) { + for (JsonElement removedAuctionsElement : removed_auctions) { String removed = removedAuctionsElement.getAsString(); toRemove.add(removed); } @@ -390,23 +391,20 @@ public class APIManager { } }; - manager.hypixelApi.getMyApiGZIPAsync("auctionLast.json.gz", process, () -> { - System.out.println("Error downloading auction from Moulberry's jank API. :("); - }); + manager.hypixelApi.getMyApiGZIPAsync("auctionLast.json.gz", process, () -> + System.out.println("Error downloading auction from Moulberry's jank API. :(")); manager.hypixelApi.getMyApiGZIPAsync("auction.json.gz", jsonObject -> { - if(jsonObject.get("success").getAsBoolean()) { - long apiUpdate = (long) jsonObject.get("time").getAsFloat(); - if (lastApiUpdate == apiUpdate) { - lastAuctionUpdate -= 30 * 1000; - } - lastApiUpdate = apiUpdate; - - process.accept(jsonObject); + if (jsonObject.get("success").getAsBoolean()) { + long apiUpdate = (long) jsonObject.get("time").getAsFloat(); + if (lastApiUpdate == apiUpdate) { + lastAuctionUpdate -= 30 * 1000; } - }, () -> { - System.out.println("Error downloading auction from Moulberry's jank API. :("); - }); + lastApiUpdate = apiUpdate; + + process.accept(jsonObject); + } + }, () -> System.out.println("Error downloading auction from Moulberry's jank API. :(")); } @@ -414,41 +412,41 @@ public class APIManager { try { uniqueItems = internalnameToAucIdMap.size(); Set aucs = new HashSet<>(); - for(HashSet aucids : internalnameToAucIdMap.values()) { + for (HashSet aucids : internalnameToAucIdMap.values()) { aucs.addAll(aucids); } internalnameTaggedAuctions = aucs.size(); totalTags = extrasToAucIdMap.size(); aucs = new HashSet<>(); - for(HashMap> extrasMap : extrasToAucIdMap.values()) { - for(HashSet aucids : extrasMap.values()) { + for (HashMap> extrasMap : extrasToAucIdMap.values()) { + for (HashSet aucids : extrasMap.values()) { aucs.addAll(aucids); } } taggedAuctions = aucs.size(); - } catch(Exception e) {} + } catch (Exception ignored) {} } -// String[] rarityArr = new String[] { -// "COMMON", "UNCOMMON", "RARE", "EPIC", "LEGENDARY", "MYTHIC", "SPECIAL", "VERY SPECIAL", "SUPREME", -// }; + //String[] rarityArr = new String[] { + // "COMMON", "UNCOMMON", "RARE", "EPIC", "LEGENDARY", "MYTHIC", "SPECIAL", "VERY SPECIAL", "SUPREME", + //}; public int checkItemType(String lore, boolean contains, String... typeMatches) { String[] split = lore.split("\n"); - for(int i=split.length-1; i>=0; i--) { + for (int i = split.length - 1; i >= 0; i--) { String line = split[i]; - for(String rarity : Utils.rarityArr) { - for(int j=0; j= 1 && enchantlevel <= 20) { - enchantLevelStr = romans[enchantlevel-1]; + if (enchantlevel >= 1 && enchantlevel <= 20) { + enchantLevelStr = romans[enchantlevel - 1]; } else { enchantLevelStr = String.valueOf(enchantlevel); } @@ -526,10 +527,10 @@ public class APIManager { } } - int index=0; - for(String str : extras.split(" ")) { + int index = 0; + for (String str : extras.split(" ")) { str = Utils.cleanColour(str).toLowerCase(); - if(str.length() > 0) { + if (str.length() > 0) { HashMap> extrasMap = extrasToAucIdMap.computeIfAbsent(str, k -> new HashMap<>()); HashSet aucids = extrasMap.computeIfAbsent(index, k -> new HashSet<>()); aucids.add(auctionUuid); @@ -537,19 +538,19 @@ public class APIManager { index++; } - for(int j=0; j= 0) { + if (checkItemType(item_lore, true, "DUNGEON") >= 0) { dungeonTier = 0; - for(int i=0; i= 0 && itemType < categoryItemType.length) { + if (itemType >= 0 && itemType < categoryItemType.length) { category = categoryItemType[itemType]; } - if(category.equals("consumables") && extras.contains("enchanted book")) category = "ebook"; - if(category.equals("consumables") && extras.endsWith("potion")) category = "potion"; - if(category.equals("misc") && extras.contains("rune")) category = "rune"; - if(category.equals("misc") && item_lore.split("\n")[0].endsWith("Furniture")) category = "furniture"; - if(item_lore.split("\n")[0].endsWith("Pet") || + if (category.equals("consumables") && extras.contains("enchanted book")) category = "ebook"; + if (category.equals("consumables") && extras.endsWith("potion")) category = "potion"; + if (category.equals("misc") && extras.contains("rune")) category = "rune"; + if (category.equals("misc") && item_lore.split("\n")[0].endsWith("Furniture")) category = "furniture"; + if (item_lore.split("\n")[0].endsWith("Pet") || item_lore.split("\n")[0].endsWith("Mount")) category = "pet"; Auction auction1 = new Auction(auctioneerUuid, end, starting_bid, highest_bid_amount, bid_count, bin, category, rarity, dungeonTier, item_bytes); - if(tag.hasKey("ench")) { + if (tag.hasKey("ench")) { auction1.enchLevel = 1; - if(tag.hasKey("ExtraAttributes", 10)) { + if (tag.hasKey("ExtraAttributes", 10)) { NBTTagCompound ea = tag.getCompoundTag("ExtraAttributes"); int hotpotatocount = ea.getInteger("hot_potato_count"); - if(hotpotatocount == 10) { + if (hotpotatocount == 10) { auction1.enchLevel = 2; } } @@ -586,27 +587,29 @@ public class APIManager { auctionMap.put(auctionUuid, auction1); internalnameToAucIdMap.computeIfAbsent(internalname, k -> new HashSet<>()).add(auctionUuid); - } catch(Exception e) {e.printStackTrace();} + } catch (Exception e) { + e.printStackTrace(); + } } private void getPageFromAPI(int page) { //System.out.println("downloading page:"+page); //System.out.println("Trying to update page: " + page); HashMap args = new HashMap<>(); - args.put("page", ""+page); + args.put("page", "" + page); manager.hypixelApi.getHypixelApiAsync(null, "skyblock/auctions", - args, jsonObject -> { - if(jsonObject == null) return; + args, jsonObject -> { + if (jsonObject == null) return; if (jsonObject.get("success").getAsBoolean()) { - if(pagesToDownload == null) { + if (pagesToDownload == null) { int totalPages = jsonObject.get("totalPages").getAsInt(); pagesToDownload = new LinkedList<>(); - for(int i=0; i { - pagesToDownload.addLast(page); - } + }, () -> pagesToDownload.addLast(page) ); } public void updateBazaar() { manager.hypixelApi.getHypixelApiAsync(NotEnoughUpdates.INSTANCE.config.apiKey.apiKey, "skyblock/bazaar", new HashMap<>(), (jsonObject) -> { - if(!jsonObject.get("success").getAsBoolean()) return; + if (!jsonObject.get("success").getAsBoolean()) return; craftCost.clear(); bazaarJson = new JsonObject(); JsonObject products = jsonObject.get("products").getAsJsonObject(); - for(Map.Entry entry : products.entrySet()) { - if(entry.getValue().isJsonObject()) { + for (Map.Entry entry : products.entrySet()) { + if (entry.getValue().isJsonObject()) { JsonObject productInfo = new JsonObject(); JsonObject product = entry.getValue().getAsJsonObject(); @@ -644,16 +645,16 @@ public class APIManager { productInfo.addProperty("avg_buy", quickStatus.get("buyPrice").getAsFloat()); productInfo.addProperty("avg_sell", quickStatus.get("sellPrice").getAsFloat()); - for(JsonElement element : product.get("sell_summary").getAsJsonArray()) { - if(element.isJsonObject()) { + for (JsonElement element : product.get("sell_summary").getAsJsonArray()) { + if (element.isJsonObject()) { JsonObject sellSummaryFirst = element.getAsJsonObject(); productInfo.addProperty("curr_sell", sellSummaryFirst.get("pricePerUnit").getAsFloat()); break; } } - for(JsonElement element : product.get("buy_summary").getAsJsonArray()) { - if(element.isJsonObject()) { + for (JsonElement element : product.get("buy_summary").getAsJsonArray()) { + if (element.isJsonObject()) { JsonObject sellSummaryFirst = element.getAsJsonObject(); productInfo.addProperty("curr_buy", sellSummaryFirst.get("pricePerUnit").getAsFloat()); break; @@ -672,74 +673,73 @@ public class APIManager { auctionPricesJson = jsonObject; lastAuctionAvgUpdate = System.currentTimeMillis(); }, () -> {}); - manager.hypixelApi.getMyApiGZIPAsync("auction_averages_lbin/1day.json.gz", (jsonObject) -> { - auctionPricesAvgLowestBinJson = jsonObject; - }, () -> {}); + manager.hypixelApi.getMyApiGZIPAsync("auction_averages_lbin/1day.json.gz", (jsonObject) -> auctionPricesAvgLowestBinJson = jsonObject, () -> {}); } public Set getItemAuctionInfoKeySet() { - if(auctionPricesJson == null) return new HashSet<>(); + if (auctionPricesJson == null) return new HashSet<>(); HashSet keys = new HashSet<>(); - for(Map.Entry entry : auctionPricesJson.entrySet()) { + for (Map.Entry entry : auctionPricesJson.entrySet()) { keys.add(entry.getKey()); } return keys; } public JsonObject getItemAuctionInfo(String internalname) { - if(auctionPricesJson == null) return null; + if (auctionPricesJson == null) return null; JsonElement e = auctionPricesJson.get(internalname); - if(e == null) { + if (e == null) { return null; } return e.getAsJsonObject(); } public float getItemAvgBin(String internalname) { - if(auctionPricesAvgLowestBinJson == null) return -1; + if (auctionPricesAvgLowestBinJson == null) return -1; JsonElement e = auctionPricesAvgLowestBinJson.get(internalname); - if(e == null) { + if (e == null) { return -1; } return Math.round(e.getAsFloat()); } public Set getBazaarKeySet() { - if(bazaarJson == null) return new HashSet<>(); + if (bazaarJson == null) return new HashSet<>(); HashSet keys = new HashSet<>(); - for(Map.Entry entry : bazaarJson.entrySet()) { + for (Map.Entry entry : bazaarJson.entrySet()) { keys.add(entry.getKey()); } return keys; } public JsonObject getBazaarInfo(String internalname) { - if(bazaarJson == null) return null; + if (bazaarJson == null) return null; JsonElement e = bazaarJson.get(internalname); - if(e == null) { + if (e == null) { return null; } return e.getAsJsonObject(); } private static final List hardcodedVanillaItems = Utils.createList( - "WOOD_AXE", "WOOD_HOE", "WOOD_PICKAXE","WOOD_SPADE", "WOOD_SWORD", + "WOOD_AXE", "WOOD_HOE", "WOOD_PICKAXE", "WOOD_SPADE", "WOOD_SWORD", "GOLD_AXE", "GOLD_HOE", "GOLD_PICKAXE", "GOLD_SPADE", "GOLD_SWORD", "ROOKIE_HOE" ); + public boolean isVanillaItem(String internalname) { - if(hardcodedVanillaItems.contains(internalname)) return true; + if (hardcodedVanillaItems.contains(internalname)) return true; //Removes trailing numbers and underscores, eg. LEAVES_2-3 -> LEAVES String vanillaName = internalname.split("-")[0]; - if(manager.getItemInformation().containsKey(vanillaName)) { + if (manager.getItemInformation().containsKey(vanillaName)) { JsonObject json = manager.getItemInformation().get(vanillaName); - if(json != null && json.has("vanilla") && json.get("vanilla").getAsBoolean()) return true; + if (json != null && json.has("vanilla") && json.get("vanilla").getAsBoolean()) return true; } return Item.itemRegistry.getObject(new ResourceLocation(vanillaName)) != null; } - public class CraftInfo { + public static class CraftInfo { public boolean fromRecipe = false; public boolean vanillaItem = false; public float craftCost = -1; @@ -753,7 +753,7 @@ public class APIManager { * Recursively calculates the cost of crafting an item from raw materials. */ public CraftInfo getCraftCost(String internalname, int depth) { - if(craftCost.containsKey(internalname)) { + if (craftCost.containsKey(internalname)) { return craftCost.get(internalname); } else { CraftInfo ci = new CraftInfo(); @@ -764,53 +764,53 @@ public class APIManager { float lowestBin = getLowestBin(internalname); JsonObject bazaarInfo = getBazaarInfo(internalname); - if(bazaarInfo != null && bazaarInfo.get("curr_buy") != null) { + if (bazaarInfo != null && bazaarInfo.get("curr_buy") != null) { float bazaarInstantBuyPrice = bazaarInfo.get("curr_buy").getAsFloat(); ci.craftCost = bazaarInstantBuyPrice; } //Don't use auction prices for vanilla items cuz people like to transfer money, messing up the cost of vanilla items. - if(lowestBin > 0 && !ci.vanillaItem) { - if(ci.craftCost < 0 || lowestBin < ci.craftCost) { + if (lowestBin > 0 && !ci.vanillaItem) { + if (ci.craftCost < 0 || lowestBin < ci.craftCost) { ci.craftCost = lowestBin; } - } else if(auctionInfo != null && !ci.vanillaItem) { + } else if (auctionInfo != null && !ci.vanillaItem) { float auctionPrice = auctionInfo.get("price").getAsFloat() / auctionInfo.get("count").getAsFloat(); - if(ci.craftCost < 0 || auctionPrice < ci.craftCost) { + if (ci.craftCost < 0 || auctionPrice < ci.craftCost) { ci.craftCost = auctionPrice; } } - if(depth > 16) { + if (depth > 16) { craftCost.put(internalname, ci); return ci; } JsonObject item = manager.getItemInformation().get(internalname); - if(item != null && item.has("recipe")) { + if (item != null && item.has("recipe")) { float craftPrice = 0; JsonObject recipe = item.get("recipe").getAsJsonObject(); - String[] x = {"1","2","3"}; - String[] y = {"A","B","C"}; - for(int i=0; i<9; i++) { - String name = y[i/3]+x[i%3]; + String[] x = {"1", "2", "3"}; + String[] y = {"A", "B", "C"}; + for (int i = 0; i < 9; i++) { + String name = y[i / 3] + x[i % 3]; String itemS = recipe.get(name).getAsString(); - if(itemS == null || itemS.length() == 0) continue; + if (itemS == null || itemS.length() == 0) continue; int count = 1; - if(itemS.split(":").length == 2) { + if (itemS.split(":").length == 2) { count = Integer.parseInt(itemS.split(":")[1]); itemS = itemS.split(":")[0]; } - if(itemS.equals(internalname)) { //if item is used a crafting component in its own recipe, return + if (itemS.equals(internalname)) { //if item is used a crafting component in its own recipe, return craftCost.put(internalname, ci); return ci; } - float compCost = getCraftCost(itemS, depth+1).craftCost * count; - if(compCost < 0) { + float compCost = getCraftCost(itemS, depth + 1).craftCost * count; + if (compCost < 0) { //If it's a custom item without a cost, return - if(!getCraftCost(itemS).vanillaItem) { + if (!getCraftCost(itemS).vanillaItem) { craftCost.put(internalname, ci); return ci; } @@ -819,7 +819,7 @@ public class APIManager { } } - if(ci.craftCost < 0 || craftPrice < ci.craftCost) { + if (ci.craftCost < 0 || craftPrice < ci.craftCost) { ci.craftCost = craftPrice; ci.fromRecipe = true; } @@ -834,18 +834,18 @@ public class APIManager { */ public float getCostOfEnchants(String internalname, NBTTagCompound tag) { float costOfEnchants = 0; - if(true) return 0; + if (true) return 0; JsonObject info = getItemAuctionInfo(internalname); - if(info == null || !info.has("price")) { + if (info == null || !info.has("price")) { return 0; } - if(auctionPricesJson == null || !auctionPricesJson.has("ench_prices") || !auctionPricesJson.has("ench_maximums")) { + if (auctionPricesJson == null || !auctionPricesJson.has("ench_prices") || !auctionPricesJson.has("ench_maximums")) { return 0; } JsonObject ench_prices = auctionPricesJson.getAsJsonObject("ench_prices"); JsonObject ench_maximums = auctionPricesJson.getAsJsonObject("ench_maximums"); - if(!ench_prices.has(internalname) || !ench_maximums.has(internalname)) { + if (!ench_prices.has(internalname) || !ench_maximums.has(internalname)) { return 0; } JsonObject iid_variables = ench_prices.getAsJsonObject(internalname); @@ -853,18 +853,18 @@ public class APIManager { int enchants = 0; float price = getItemAuctionInfo(internalname).get("price").getAsFloat(); - if(tag.hasKey("ExtraAttributes")) { + if (tag.hasKey("ExtraAttributes")) { NBTTagCompound ea = tag.getCompoundTag("ExtraAttributes"); - if(ea.hasKey("enchantments")) { + if (ea.hasKey("enchantments")) { NBTTagCompound enchs = ea.getCompoundTag("enchantments"); - for(String ench : enchs.getKeySet()) { + for (String ench : enchs.getKeySet()) { enchants++; int level = enchs.getInteger(ench); - for(Map.Entry entry : iid_variables.entrySet()) { - if(matchEnch(ench, level, entry.getKey())) { - costOfEnchants += entry.getValue().getAsJsonObject().get("A").getAsFloat()*price + + for (Map.Entry entry : iid_variables.entrySet()) { + if (matchEnch(ench, level, entry.getKey())) { + costOfEnchants += entry.getValue().getAsJsonObject().get("A").getAsFloat() * price + entry.getValue().getAsJsonObject().get("B").getAsFloat(); break; } @@ -880,26 +880,26 @@ public class APIManager { * eg. PROTECTION_GE6 will match -> ench_name = PROTECTION, lvl >= 6 */ private boolean matchEnch(String ench, int level, String id) { - if(!id.contains(":")) { + if (!id.contains(":")) { return false; } String idEnch = id.split(":")[0]; String idLevel = id.split(":")[1]; - if(!ench.equalsIgnoreCase(idEnch)) { + if (!ench.equalsIgnoreCase(idEnch)) { return false; } - if(String.valueOf(level).equalsIgnoreCase(idLevel)) { + if (String.valueOf(level).equalsIgnoreCase(idLevel)) { return true; } - if(idLevel.startsWith("LE")) { - int idLevelI = Integer.valueOf(idLevel.substring(2)); + if (idLevel.startsWith("LE")) { + int idLevelI = Integer.parseInt(idLevel.substring(2)); return level <= idLevelI; - } else if(idLevel.startsWith("GE")) { - int idLevelI = Integer.valueOf(idLevel.substring(2)); + } else if (idLevel.startsWith("GE")) { + int idLevelI = Integer.parseInt(idLevel.substring(2)); return level >= idLevelI; } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/auction/CustomAH.java b/src/main/java/io/github/moulberry/notenoughupdates/auction/CustomAH.java index 25d4d03b..6f3209b2 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/auction/CustomAH.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/auction/CustomAH.java @@ -35,8 +35,8 @@ import org.lwjgl.opengl.GL14; import java.awt.*; import java.awt.datatransfer.StringSelection; import java.text.NumberFormat; -import java.util.*; import java.util.List; +import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.regex.Matcher; @@ -106,45 +106,45 @@ public class CustomAH extends Gui { public int guiLeft = -1; public int guiTop = -1; - private Category CATEGORY_SWORD = new Category("sword", "Swords", "diamond_sword"); - private Category CATEGORY_ARMOR = new Category("armor", "Armor", "diamond_chestplate"); - private Category CATEGORY_BOWS = new Category("bow", "Bows", "bow"); - private Category CATEGORY_ACCESSORIES = new Category("accessories", "Accessories", "diamond"); + private final Category CATEGORY_SWORD = new Category("sword", "Swords", "diamond_sword"); + private final Category CATEGORY_ARMOR = new Category("armor", "Armor", "diamond_chestplate"); + private final Category CATEGORY_BOWS = new Category("bow", "Bows", "bow"); + private final Category CATEGORY_ACCESSORIES = new Category("accessories", "Accessories", "diamond"); - private Category CATEGORY_FISHING_ROD = new Category("fishingrod", "Fishing Rods", "fishing_rod"); - private Category CATEGORY_PICKAXE = new Category("pickaxe", "Pickaxes", "iron_pickaxe"); - private Category CATEGORY_AXE = new Category("axe", "Axes", "iron_axe"); - private Category CATEGORY_SHOVEL = new Category("shovel", "Shovels", "iron_shovel"); + private final Category CATEGORY_FISHING_ROD = new Category("fishingrod", "Fishing Rods", "fishing_rod"); + private final Category CATEGORY_PICKAXE = new Category("pickaxe", "Pickaxes", "iron_pickaxe"); + private final Category CATEGORY_AXE = new Category("axe", "Axes", "iron_axe"); + private final Category CATEGORY_SHOVEL = new Category("shovel", "Shovels", "iron_shovel"); - private Category CATEGORY_PET_ITEM = new Category("petitem", "Pet Items", "lead"); + private final Category CATEGORY_PET_ITEM = new Category("petitem", "Pet Items", "lead"); - private Category CATEGORY_EBOOKS = new Category("ebook", "Enchanted Books", "enchanted_book"); - private Category CATEGORY_POTIONS = new Category("potion", "Potions", "potion"); - private Category CATEGORY_TRAVEL_SCROLLS = new Category("travelscroll", "Travel Scrolls", "map"); + private final Category CATEGORY_EBOOKS = new Category("ebook", "Enchanted Books", "enchanted_book"); + private final Category CATEGORY_POTIONS = new Category("potion", "Potions", "potion"); + private final Category CATEGORY_TRAVEL_SCROLLS = new Category("travelscroll", "Travel Scrolls", "map"); - private Category CATEGORY_REFORGE_STONES = new Category("reforgestone", "Reforge Stones", "anvil"); - private Category CATEGORY_RUNES = new Category("rune", "Runes", "magma_cream"); - private Category CATEGORY_FURNITURE = new Category("furniture", "Furniture", "armor_stand"); + private final Category CATEGORY_REFORGE_STONES = new Category("reforgestone", "Reforge Stones", "anvil"); + private final Category CATEGORY_RUNES = new Category("rune", "Runes", "magma_cream"); + private final Category CATEGORY_FURNITURE = new Category("furniture", "Furniture", "armor_stand"); - private Category CATEGORY_COMBAT = new Category("weapon", "Combat", "golden_sword", CATEGORY_SWORD, + private final Category CATEGORY_COMBAT = new Category("weapon", "Combat", "golden_sword", CATEGORY_SWORD, CATEGORY_BOWS, CATEGORY_ARMOR, CATEGORY_ACCESSORIES); - private Category CATEGORY_TOOL = new Category("", "Tools", "diamond_pickaxe", CATEGORY_FISHING_ROD, CATEGORY_PICKAXE, + private final Category CATEGORY_TOOL = new Category("", "Tools", "diamond_pickaxe", CATEGORY_FISHING_ROD, CATEGORY_PICKAXE, CATEGORY_AXE, CATEGORY_SHOVEL); - private Category CATEGORY_PET = new Category("pet", "Pets", "bone", CATEGORY_PET_ITEM); - private Category CATEGORY_CONSUMABLES = new Category("consumables", "Consumables", "apple", CATEGORY_EBOOKS, CATEGORY_POTIONS, + private final Category CATEGORY_PET = new Category("pet", "Pets", "bone", CATEGORY_PET_ITEM); + private final Category CATEGORY_CONSUMABLES = new Category("consumables", "Consumables", "apple", CATEGORY_EBOOKS, CATEGORY_POTIONS, CATEGORY_TRAVEL_SCROLLS); - private Category CATEGORY_BLOCKS = new Category("blocks", "Blocks", "cobblestone"); - private Category CATEGORY_MISC = new Category("misc", "Misc", "stick", CATEGORY_REFORGE_STONES, CATEGORY_RUNES, + private final Category CATEGORY_BLOCKS = new Category("blocks", "Blocks", "cobblestone"); + private final Category CATEGORY_MISC = new Category("misc", "Misc", "stick", CATEGORY_REFORGE_STONES, CATEGORY_RUNES, CATEGORY_FURNITURE); - private Category[] mainCategories = new Category[]{CATEGORY_COMBAT, CATEGORY_TOOL, CATEGORY_PET, + private final Category[] mainCategories = new Category[]{CATEGORY_COMBAT, CATEGORY_TOOL, CATEGORY_PET, CATEGORY_CONSUMABLES, CATEGORY_BLOCKS, CATEGORY_MISC}; private static final int SORT_MODE_HIGH = 0; private static final int SORT_MODE_LOW = 1; private static final int SORT_MODE_SOON = 2; -// private static final String[] rarities = {"COMMON", "UNCOMMON", "RARE", "EPIC", + // private static final String[] rarities = {"COMMON", "UNCOMMON", "RARE", "EPIC", // "LEGENDARY", "MYTHIC", "SPECIAL", "VERY SPECIAL", "SUPREME"}; private static final String[] rarityColours = {"" + EnumChatFormatting.WHITE, "" + EnumChatFormatting.GREEN, "" + EnumChatFormatting.BLUE, "" + EnumChatFormatting.DARK_PURPLE, @@ -175,23 +175,23 @@ public class CustomAH extends Gui { private int binFilter = BIN_FILTER_ALL; private int enchFilter = ENCH_FILTER_ALL; - private static ItemStack DUNGEON_SORT = Utils.createItemStack(Item.getItemFromBlock(Blocks.deadbush), + private static final ItemStack DUNGEON_SORT = Utils.createItemStack(Item.getItemFromBlock(Blocks.deadbush), EnumChatFormatting.GREEN + "Dungeon Sorting"); - private static ItemStack CONTROL_SORT = Utils.createItemStack(Item.getItemFromBlock(Blocks.hopper), + private static final ItemStack CONTROL_SORT = Utils.createItemStack(Item.getItemFromBlock(Blocks.hopper), EnumChatFormatting.GREEN + "Sort"); - private static ItemStack CONTROL_TIER = Utils.createItemStack(Items.ender_eye, + private static final ItemStack CONTROL_TIER = Utils.createItemStack(Items.ender_eye, EnumChatFormatting.GREEN + "Item Tier"); - private static ItemStack CONTROL_MYAUC = Utils.createItemStack(Items.gold_ingot, + private static final ItemStack CONTROL_MYAUC = Utils.createItemStack(Items.gold_ingot, EnumChatFormatting.GREEN + "My Auctions"); - private static ItemStack CONTROL_BIN = Utils.createItemStack(Item.getItemFromBlock(Blocks.golden_rail), + private static final ItemStack CONTROL_BIN = Utils.createItemStack(Item.getItemFromBlock(Blocks.golden_rail), EnumChatFormatting.GREEN + "BIN Filter"); - private static ItemStack CONTROL_ENCH = Utils.createItemStack(Items.enchanted_book, + private static final ItemStack CONTROL_ENCH = Utils.createItemStack(Items.enchanted_book, EnumChatFormatting.GREEN + "Enchant Filter"); - private static ItemStack CONTROL_STATS = Utils.createItemStack(Item.getItemFromBlock(Blocks.command_block), + private static final ItemStack CONTROL_STATS = Utils.createItemStack(Item.getItemFromBlock(Blocks.command_block), EnumChatFormatting.GREEN + "Stats for nerds"); - private ItemStack[] controls = {DUNGEON_SORT, CONTROL_SORT, CONTROL_TIER, null, CONTROL_MYAUC, null, CONTROL_BIN, CONTROL_ENCH, CONTROL_STATS}; + private final ItemStack[] controls = {DUNGEON_SORT, CONTROL_SORT, CONTROL_TIER, null, CONTROL_MYAUC, null, CONTROL_BIN, CONTROL_ENCH, CONTROL_STATS}; - private NEUManager manager; + private final NEUManager manager; public CustomAH(NEUManager manager) { this.manager = manager; @@ -229,7 +229,7 @@ public class CustomAH extends Gui { } } - public class Category { + public static class Category { public String categoryMatch; public Category[] subcategories; public String displayName; @@ -439,7 +439,7 @@ public class CustomAH extends Gui { GlStateManager.disableBlend(); } - private HashMap timeParseMap = new HashMap<>(); + private final HashMap timeParseMap = new HashMap<>(); public long prettyTimeToMillis(String endsInStr) { if (timeParseMap.isEmpty()) { @@ -891,8 +891,7 @@ public class CustomAH extends Gui { tooltipToRender = getTooltipForAucId(aucid); } } - } catch (Exception e) { - } + } catch (Exception ignored) {} } } } @@ -1345,7 +1344,7 @@ public class CustomAH extends Gui { return matches; } - private ExecutorService es = Executors.newSingleThreadExecutor(); + private final ExecutorService es = Executors.newSingleThreadExecutor(); public void updateSearch() { if (!NotEnoughUpdates.INSTANCE.config.neuAuctionHouse.enableNeuAuctionHouse) { @@ -1726,7 +1725,6 @@ public class CustomAH extends Gui { ContainerChest container = (ContainerChest) auctionView.inventorySlots; String containerName = container.getLowerChestInventory().getDisplayName().getUnformattedText(); - if (containerName.trim().equals("Auction View") || containerName.trim().equals("BIN Auction View")) { if (mouseX > guiLeft + getXSize() + 4 + 31 && mouseX < guiLeft + getXSize() + 4 + 31 + 16) { @@ -1795,22 +1793,20 @@ public class CustomAH extends Gui { if (mouseX < auctionViewLeft + 16 + 32) { //top left increasePriceByFactor(2); - Utils.playPressSound(); } else { //top right increasePriceByFactor(1.5f); - Utils.playPressSound(); } + Utils.playPressSound(); } else if (mouseY > guiTop + 50 && mouseY < guiTop + 50 + 16) { if (mouseX < auctionViewLeft + 16 + 32) { //mid left increasePriceByFactor(1.25f); - Utils.playPressSound(); } else { //mid right increasePriceByFactor(1.1f); - Utils.playPressSound(); } + Utils.playPressSound(); } else if (mouseY > guiTop + 68 && mouseY < guiTop + 68 + 16) { //bottom Utils.playPressSound(); diff --git a/src/main/java/io/github/moulberry/notenoughupdates/auction/CustomAHGui.java b/src/main/java/io/github/moulberry/notenoughupdates/auction/CustomAHGui.java index bb36d363..a42fdb64 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/auction/CustomAHGui.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/auction/CustomAHGui.java @@ -1,7 +1,6 @@ package io.github.moulberry.notenoughupdates.auction; import net.minecraft.client.gui.GuiScreen; -import org.lwjgl.input.Mouse; public class CustomAHGui extends GuiScreen { diff --git a/src/main/java/io/github/moulberry/notenoughupdates/collectionlog/GuiCollectionLog.java b/src/main/java/io/github/moulberry/notenoughupdates/collectionlog/GuiCollectionLog.java index a2c8bfa9..ed479e79 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/collectionlog/GuiCollectionLog.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/collectionlog/GuiCollectionLog.java @@ -24,29 +24,29 @@ public class GuiCollectionLog extends GuiScreen { int colwidth = 307; int colheight = 187; - int left = width/2 - colwidth/2; - int top = height/2 - colheight/2; + int left = width / 2 - colwidth / 2; + int top = height / 2 - colheight / 2; BackgroundBlur.renderBlurredBackground(10, width, height, left, top, colwidth, colheight); super.drawDefaultBackground(); - Utils.drawStringCentered("\u00a7lCollection Log", fontRendererObj, width/2, top - 27, true, 0xfff5aa00); + Utils.drawStringCentered("\u00a7lCollection Log", fontRendererObj, width / 2, top - 27, true, 0xfff5aa00); String[] cats = {"Bosses", "Dragons", "Slayer", "Dungeons"}; GlStateManager.enableDepth(); GlStateManager.translate(0, 0, 2); - for(int i=0; i<4; i++) { - if(i == 0) { + for (int i = 0; i < 4; i++) { + if (i == 0) { int offset = i == 0 ? 1 : 2; Minecraft.getMinecraft().getTextureManager().bindTexture(COLLECTION_LOG_TEX); GlStateManager.color(1, 1, 1, 1); - Utils.drawTexturedRect(left+i*71, top-21, 71, 25, - (71*offset)/512f, (71+71*offset)/512f, 211/512f, (211+25)/512f, GL11.GL_NEAREST); + Utils.drawTexturedRect(left + i * 71, top - 21, 71, 25, + (71 * offset) / 512f, (71 + 71 * offset) / 512f, 211 / 512f, (211 + 25) / 512f, GL11.GL_NEAREST); - Utils.drawStringCentered(cats[i], fontRendererObj, left+i*71+71/2, top - 8, true, 0xfff5aa00); + Utils.drawStringCentered(cats[i], fontRendererObj, left + i * 71 + 71 / 2, top - 8, true, 0xfff5aa00); } } @@ -54,50 +54,48 @@ public class GuiCollectionLog extends GuiScreen { Minecraft.getMinecraft().getTextureManager().bindTexture(COLLECTION_LOG_TEX); GlStateManager.color(1, 1, 1, 1); Utils.drawTexturedRect(left, top, colwidth, colheight, - 0, colwidth/512f, 0, colheight/512f, GL11.GL_NEAREST); + 0, colwidth / 512f, 0, colheight / 512f, GL11.GL_NEAREST); - GlScissorStack.push(0, top+3, width, top+colheight-6, scaledResolution); + GlScissorStack.push(0, top + 3, width, top + colheight - 6, scaledResolution); int catIndex = 0; - for(int h=top+3; h neuDevHelpMessages = Lists.newArrayList( "\u00a76/neudevtest \u00a7r\u00a77- dev test command", "\u00a76/neuzeephere \u00a7r\u00a77- sphere", "\u00a76/neudungeonwintest \u00a7r\u00a77- displays the dungeon win screen"); - for (int i = 0; i < neuDevHelpMessages.size(); i++) { - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(neuDevHelpMessages.get(i) - )); - + for (String neuDevHelpMessage : neuDevHelpMessages) { + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(neuDevHelpMessage)); } } Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("")); @@ -284,9 +273,9 @@ public class Commands { SimpleCommand neuFeatures = new SimpleCommand("neufeatures", new SimpleCommand.ProcessCommandRunnable() { public void processCommand(ICommandSender sender, String[] args) { Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("")); - if(Constants.MISC == null || !Constants.MISC.has("featureslist")){ - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(""+EnumChatFormatting.DARK_RED+EnumChatFormatting.BOLD+"WARNING: "+EnumChatFormatting.RESET+EnumChatFormatting.RED+"Could not load URL from repo.")); - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(""+EnumChatFormatting.RED+ "Please run "+EnumChatFormatting.BOLD+"/neuresetrepo"+EnumChatFormatting.RESET+EnumChatFormatting.RED+" and "+EnumChatFormatting.BOLD+"restart your game"+EnumChatFormatting.RESET+EnumChatFormatting.RED+" in order to fix. "+EnumChatFormatting.DARK_RED+EnumChatFormatting.BOLD+"If that doesn't fix it"+EnumChatFormatting.RESET+EnumChatFormatting.RED+", please join discord.gg/moulberry and post in #neu-support")); + if (Constants.MISC == null || !Constants.MISC.has("featureslist")) { + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("" + EnumChatFormatting.DARK_RED + EnumChatFormatting.BOLD + "WARNING: " + EnumChatFormatting.RESET + EnumChatFormatting.RED + "Could not load URL from repo.")); + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("" + EnumChatFormatting.RED + "Please run " + EnumChatFormatting.BOLD + "/neuresetrepo" + EnumChatFormatting.RESET + EnumChatFormatting.RED + " and " + EnumChatFormatting.BOLD + "restart your game" + EnumChatFormatting.RESET + EnumChatFormatting.RED + " in order to fix. " + EnumChatFormatting.DARK_RED + EnumChatFormatting.BOLD + "If that doesn't fix it" + EnumChatFormatting.RESET + EnumChatFormatting.RED + ", please join discord.gg/moulberry and post in #neu-support")); Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText("")); return; } @@ -295,11 +284,11 @@ public class Commands { Desktop desk = Desktop.getDesktop(); try { desk.browse(new URI(url)); - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.DARK_PURPLE+""+EnumChatFormatting.BOLD+"NEU"+EnumChatFormatting.RESET+EnumChatFormatting.GOLD+"> Opening Feature List in browser.")); - } catch (URISyntaxException | IOException ignored){ + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.DARK_PURPLE + "" + EnumChatFormatting.BOLD + "NEU" + EnumChatFormatting.RESET + EnumChatFormatting.GOLD + "> Opening Feature List in browser.")); + } catch (URISyntaxException | IOException ignored) { ChatComponentText clickTextFeatures = new ChatComponentText( - EnumChatFormatting.DARK_PURPLE+""+EnumChatFormatting.BOLD+"NEU"+EnumChatFormatting.RESET+EnumChatFormatting.GOLD+"> Click here to open the Feature List in your browser."); + EnumChatFormatting.DARK_PURPLE + "" + EnumChatFormatting.BOLD + "NEU" + EnumChatFormatting.RESET + EnumChatFormatting.GOLD + "> Click here to open the Feature List in your browser."); clickTextFeatures.setChatStyle(Utils.createClickStyle(ClickEvent.Action.OPEN_URL, url)); Minecraft.getMinecraft().thePlayer.addChatMessage(clickTextFeatures); @@ -309,7 +298,6 @@ public class Commands { } }); - SimpleCommand stWhyCommand = new SimpleCommand("neustwhy", new SimpleCommand.ProcessCommandRunnable() { public void processCommand(ICommandSender sender, String[] args) { NEUEventListener.displayNotification(Lists.newArrayList( @@ -350,8 +338,8 @@ public class Commands { SimpleCommand dungeonWinTest = new SimpleCommand("neudungeonwintest", new SimpleCommand.ProcessCommandRunnable() { public void processCommand(ICommandSender sender, String[] args) { - if(args.length > 0) { - DungeonWin.TEAM_SCORE = new ResourceLocation("notenoughupdates:dungeon_win/"+args[0].toLowerCase()+".png"); + if (args.length > 0) { + DungeonWin.TEAM_SCORE = new ResourceLocation("notenoughupdates:dungeon_win/" + args[0].toLowerCase() + ".png"); } DungeonWin.displayWin(); @@ -361,11 +349,11 @@ public class Commands { SimpleCommand reloadRepoCommand = new SimpleCommand("neureloadrepo", new SimpleCommand.ProcessCommandRunnable() { public void processCommand(ICommandSender sender, String[] args) { File items = new File(NotEnoughUpdates.INSTANCE.manager.repoLocation, "items"); - if(items.exists()) { + if (items.exists()) { File[] itemFiles = new File(NotEnoughUpdates.INSTANCE.manager.repoLocation, "items").listFiles(); - if(itemFiles != null) { - for(File f : itemFiles) { - String internalname = f.getName().substring(0, f.getName().length()-5); + if (itemFiles != null) { + for (File f : itemFiles) { + String internalname = f.getName().substring(0, f.getName().length() - 5); NotEnoughUpdates.INSTANCE.manager.loadItem(internalname); } } @@ -373,10 +361,10 @@ public class Commands { Constants.reload(); NotEnoughUpdates.INSTANCE.newConfigFile(); - if(NotEnoughUpdates.INSTANCE.getConfigFile().exists()) { - try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(NotEnoughUpdates.INSTANCE.getConfigFile()), StandardCharsets.UTF_8))) { + if (NotEnoughUpdates.INSTANCE.getConfigFile().exists()) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(NotEnoughUpdates.INSTANCE.getConfigFile()), StandardCharsets.UTF_8))) { NotEnoughUpdates.INSTANCE.config = NotEnoughUpdates.INSTANCE.manager.gson.fromJson(reader, NEUConfig.class); - } catch(Exception e) { } + } catch (Exception ignored) {} } } }); @@ -386,48 +374,48 @@ public class Commands { SimpleCommand peekCommand = new SimpleCommand("peek", new SimpleCommand.ProcessCommandRunnable() { public void processCommand(ICommandSender sender, String[] args) { String name; - if(args.length == 0) { + if (args.length == 0) { name = Minecraft.getMinecraft().thePlayer.getName(); } else { name = args[0]; } - int id = new Random().nextInt(Integer.MAX_VALUE/2)+Integer.MAX_VALUE/2; + int id = new Random().nextInt(Integer.MAX_VALUE / 2) + Integer.MAX_VALUE / 2; Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessageWithOptionalDeletion(new ChatComponentText( - EnumChatFormatting.YELLOW+"[PEEK] Getting player information..."), id); - NotEnoughUpdates.INSTANCE.profileViewer.getProfileByName(name, profile -> { + EnumChatFormatting.YELLOW + "[PEEK] Getting player information..."), id); + NotEnoughUpdates.profileViewer.getProfileByName(name, profile -> { if (profile == null) { Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessageWithOptionalDeletion(new ChatComponentText( - EnumChatFormatting.RED+"[PEEK] Unknown player or api is down."), id); + EnumChatFormatting.RED + "[PEEK] Unknown player or api is down."), id); } else { profile.resetCache(); - if(peekCommandExecutorService == null || peekCommandExecutorService.isShutdown()) { + if (peekCommandExecutorService == null || peekCommandExecutorService.isShutdown()) { peekCommandExecutorService = Executors.newSingleThreadScheduledExecutor(); } else { Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText( - EnumChatFormatting.RED+"[PEEK] New peek command run, cancelling old one.")); + EnumChatFormatting.RED + "[PEEK] New peek command run, cancelling old one.")); peekCommandExecutorService.shutdownNow(); peekCommandExecutorService = Executors.newSingleThreadScheduledExecutor(); } Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessageWithOptionalDeletion(new ChatComponentText( - EnumChatFormatting.YELLOW+"[PEEK] Getting player skyblock profiles..."), id); + EnumChatFormatting.YELLOW + "[PEEK] Getting player skyblock profiles..."), id); long startTime = System.currentTimeMillis(); peekCommandExecutorService.schedule(new Runnable() { public void run() { - if(System.currentTimeMillis() - startTime > 10*1000) { + if (System.currentTimeMillis() - startTime > 10 * 1000) { Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessageWithOptionalDeletion(new ChatComponentText( - EnumChatFormatting.RED+"[PEEK] Getting profile info took too long, aborting."), id); + EnumChatFormatting.RED + "[PEEK] Getting profile info took too long, aborting."), id); return; } String g = EnumChatFormatting.GRAY.toString(); JsonObject profileInfo = profile.getProfileInformation(null); - if(profileInfo != null) { + if (profileInfo != null) { float overallScore = 0; boolean isMe = name.equalsIgnoreCase("moulberry"); @@ -435,21 +423,21 @@ public class Commands { PlayerStats.Stats stats = profile.getStats(null); JsonObject skill = profile.getSkillInfo(null); - Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessageWithOptionalDeletion(new ChatComponentText(EnumChatFormatting.GREEN+" "+ - EnumChatFormatting.STRIKETHROUGH+"-=-" +EnumChatFormatting.RESET+EnumChatFormatting.GREEN+" "+ + Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessageWithOptionalDeletion(new ChatComponentText(EnumChatFormatting.GREEN + " " + + EnumChatFormatting.STRIKETHROUGH + "-=-" + EnumChatFormatting.RESET + EnumChatFormatting.GREEN + " " + Utils.getElementAsString(profile.getHypixelProfile().get("displayname"), name) + "'s Info " + - EnumChatFormatting.STRIKETHROUGH+"-=-"), id); + EnumChatFormatting.STRIKETHROUGH + "-=-"), id); - if(skill == null) { - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.YELLOW+"Skills api disabled!")); + if (skill == null) { + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.YELLOW + "Skills api disabled!")); } else { float totalSkillLVL = 0; float totalSkillCount = 0; - for(Map.Entry entry : skill.entrySet()) { - if(entry.getKey().startsWith("level_skill")) { - if(entry.getKey().contains("runecrafting")) continue; - if(entry.getKey().contains("carpentry")) continue; + for (Map.Entry entry : skill.entrySet()) { + if (entry.getKey().startsWith("level_skill")) { + if (entry.getKey().contains("runecrafting")) continue; + if (entry.getKey().contains("carpentry")) continue; totalSkillLVL += entry.getValue().getAsFloat(); totalSkillCount++; } @@ -461,9 +449,9 @@ public class Commands { float wolf = Utils.getElementAsFloat(skill.get("level_slayer_wolf"), 0); float enderman = Utils.getElementAsFloat(skill.get("level_slayer_enderman"), 0); - float avgSkillLVL = totalSkillLVL/totalSkillCount; + float avgSkillLVL = totalSkillLVL / totalSkillCount; - if(isMe) { + if (isMe) { avgSkillLVL = 6; combat = 4; zombie = 2; @@ -472,104 +460,104 @@ public class Commands { enderman = 0; } - EnumChatFormatting combatPrefix = combat>20?(combat>35?EnumChatFormatting.GREEN:EnumChatFormatting.YELLOW):EnumChatFormatting.RED; - EnumChatFormatting zombiePrefix = zombie>3?(zombie>6?EnumChatFormatting.GREEN:EnumChatFormatting.YELLOW):EnumChatFormatting.RED; - EnumChatFormatting spiderPrefix = spider>3?(spider>6?EnumChatFormatting.GREEN:EnumChatFormatting.YELLOW):EnumChatFormatting.RED; - EnumChatFormatting wolfPrefix = wolf>3?(wolf>6?EnumChatFormatting.GREEN:EnumChatFormatting.YELLOW):EnumChatFormatting.RED; - EnumChatFormatting endermanPrefix = enderman>3?(enderman>6?EnumChatFormatting.GREEN:EnumChatFormatting.YELLOW):EnumChatFormatting.RED; - EnumChatFormatting avgPrefix = avgSkillLVL>20?(avgSkillLVL>35?EnumChatFormatting.GREEN:EnumChatFormatting.YELLOW):EnumChatFormatting.RED; + EnumChatFormatting combatPrefix = combat > 20 ? (combat > 35 ? EnumChatFormatting.GREEN : EnumChatFormatting.YELLOW) : EnumChatFormatting.RED; + EnumChatFormatting zombiePrefix = zombie > 3 ? (zombie > 6 ? EnumChatFormatting.GREEN : EnumChatFormatting.YELLOW) : EnumChatFormatting.RED; + EnumChatFormatting spiderPrefix = spider > 3 ? (spider > 6 ? EnumChatFormatting.GREEN : EnumChatFormatting.YELLOW) : EnumChatFormatting.RED; + EnumChatFormatting wolfPrefix = wolf > 3 ? (wolf > 6 ? EnumChatFormatting.GREEN : EnumChatFormatting.YELLOW) : EnumChatFormatting.RED; + EnumChatFormatting endermanPrefix = enderman > 3 ? (enderman > 6 ? EnumChatFormatting.GREEN : EnumChatFormatting.YELLOW) : EnumChatFormatting.RED; + EnumChatFormatting avgPrefix = avgSkillLVL > 20 ? (avgSkillLVL > 35 ? EnumChatFormatting.GREEN : EnumChatFormatting.YELLOW) : EnumChatFormatting.RED; - overallScore += zombie*zombie/81f; - overallScore += spider*spider/81f; - overallScore += wolf*wolf/81f; - overallScore += enderman*enderman/81f; - overallScore += avgSkillLVL/20f; + overallScore += zombie * zombie / 81f; + overallScore += spider * spider / 81f; + overallScore += wolf * wolf / 81f; + overallScore += enderman * enderman / 81f; + overallScore += avgSkillLVL / 20f; - int cata = (int)Utils.getElementAsFloat(skill.get("level_skill_catacombs"), 0); - EnumChatFormatting cataPrefix = cata>15?(cata>25?EnumChatFormatting.GREEN:EnumChatFormatting.YELLOW):EnumChatFormatting.RED; + int cata = (int) Utils.getElementAsFloat(skill.get("level_skill_catacombs"), 0); + EnumChatFormatting cataPrefix = cata > 15 ? (cata > 25 ? EnumChatFormatting.GREEN : EnumChatFormatting.YELLOW) : EnumChatFormatting.RED; - overallScore += cata*cata/2000f; + overallScore += cata * cata / 2000f; Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText( - g+"Combat: "+combatPrefix+(int)Math.floor(combat) + - (cata > 0 ? g+" - Cata: "+cataPrefix+cata : "")+ - g+" - AVG: " + avgPrefix+(int)Math.floor(avgSkillLVL))); + g + "Combat: " + combatPrefix + (int) Math.floor(combat) + + (cata > 0 ? g + " - Cata: " + cataPrefix + cata : "") + + g + " - AVG: " + avgPrefix + (int) Math.floor(avgSkillLVL))); Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText( - g+"Slayer: "+zombiePrefix+(int)Math.floor(zombie)+g+"-"+ - spiderPrefix+(int)Math.floor(spider)+g+"-"+ - wolfPrefix+(int)Math.floor(wolf)+"-"+ - endermanPrefix+(int)Math.floor(enderman))); + g + "Slayer: " + zombiePrefix + (int) Math.floor(zombie) + g + "-" + + spiderPrefix + (int) Math.floor(spider) + g + "-" + + wolfPrefix + (int) Math.floor(wolf) + "-" + + endermanPrefix + (int) Math.floor(enderman))); } if (stats == null) { Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText( - EnumChatFormatting.YELLOW+"Skills, collection and/or inventory apis disabled!")); + EnumChatFormatting.YELLOW + "Skills, collection and/or inventory apis disabled!")); } else { - int health = (int)stats.get("health"); - int defence = (int)stats.get("defence"); - int strength = (int)stats.get("strength"); - int intelligence = (int)stats.get("intelligence"); + int health = (int) stats.get("health"); + int defence = (int) stats.get("defence"); + int strength = (int) stats.get("strength"); + int intelligence = (int) stats.get("intelligence"); - EnumChatFormatting healthPrefix = health>800?(health>1600?EnumChatFormatting.GREEN:EnumChatFormatting.YELLOW):EnumChatFormatting.RED; - EnumChatFormatting defencePrefix = defence>200?(defence>600?EnumChatFormatting.GREEN:EnumChatFormatting.YELLOW):EnumChatFormatting.RED; - EnumChatFormatting strengthPrefix = strength>100?(strength>300?EnumChatFormatting.GREEN:EnumChatFormatting.YELLOW):EnumChatFormatting.RED; - EnumChatFormatting intelligencePrefix = intelligence>300?(intelligence>900?EnumChatFormatting.GREEN:EnumChatFormatting.YELLOW):EnumChatFormatting.RED; + EnumChatFormatting healthPrefix = health > 800 ? (health > 1600 ? EnumChatFormatting.GREEN : EnumChatFormatting.YELLOW) : EnumChatFormatting.RED; + EnumChatFormatting defencePrefix = defence > 200 ? (defence > 600 ? EnumChatFormatting.GREEN : EnumChatFormatting.YELLOW) : EnumChatFormatting.RED; + EnumChatFormatting strengthPrefix = strength > 100 ? (strength > 300 ? EnumChatFormatting.GREEN : EnumChatFormatting.YELLOW) : EnumChatFormatting.RED; + EnumChatFormatting intelligencePrefix = intelligence > 300 ? (intelligence > 900 ? EnumChatFormatting.GREEN : EnumChatFormatting.YELLOW) : EnumChatFormatting.RED; Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText( - g+"Stats : "+healthPrefix+health+EnumChatFormatting.RED+"\u2764 "+ - defencePrefix+defence+EnumChatFormatting.GREEN+"\u2748 "+ - strengthPrefix+strength+EnumChatFormatting.RED+"\u2741 "+ - intelligencePrefix+intelligence+EnumChatFormatting.AQUA+"\u270e ")); + g + "Stats : " + healthPrefix + health + EnumChatFormatting.RED + "\u2764 " + + defencePrefix + defence + EnumChatFormatting.GREEN + "\u2748 " + + strengthPrefix + strength + EnumChatFormatting.RED + "\u2741 " + + intelligencePrefix + intelligence + EnumChatFormatting.AQUA + "\u270e ")); } float bankBalance = Utils.getElementAsFloat(Utils.getElement(profileInfo, "banking.balance"), -1); float purseBalance = Utils.getElementAsFloat(Utils.getElement(profileInfo, "coin_purse"), 0); long networth = profile.getNetWorth(null); - float money = Math.max(bankBalance+purseBalance, networth); - EnumChatFormatting moneyPrefix = money>50*1000*1000? - (money>200*1000*1000?EnumChatFormatting.GREEN:EnumChatFormatting.YELLOW):EnumChatFormatting.RED; + float money = Math.max(bankBalance + purseBalance, networth); + EnumChatFormatting moneyPrefix = money > 50 * 1000 * 1000 ? + (money > 200 * 1000 * 1000 ? EnumChatFormatting.GREEN : EnumChatFormatting.YELLOW) : EnumChatFormatting.RED; Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText( - g+"Purse: "+moneyPrefix+Utils.shortNumberFormat(purseBalance, 0) + g+" - Bank: " + - (bankBalance == -1 ? EnumChatFormatting.YELLOW+"N/A" : moneyPrefix+ - (isMe?"4.8b":Utils.shortNumberFormat(bankBalance, 0))) + - (networth > 0 ? g+" - Net: "+moneyPrefix+Utils.shortNumberFormat(networth, 0) : ""))); + g + "Purse: " + moneyPrefix + Utils.shortNumberFormat(purseBalance, 0) + g + " - Bank: " + + (bankBalance == -1 ? EnumChatFormatting.YELLOW + "N/A" : moneyPrefix + + (isMe ? "4.8b" : Utils.shortNumberFormat(bankBalance, 0))) + + (networth > 0 ? g + " - Net: " + moneyPrefix + Utils.shortNumberFormat(networth, 0) : ""))); - overallScore += Math.min(2, money/(100f*1000*1000)); + overallScore += Math.min(2, money / (100f * 1000 * 1000)); String activePet = Utils.getElementAsString(Utils.getElement(profile.getPetsInfo(null), "active_pet.type"), "None Active"); String activePetTier = Utils.getElementAsString(Utils.getElement(profile.getPetsInfo(null), "active_pet.tier"), "UNKNOWN"); String col = NotEnoughUpdates.petRarityToColourMap.get(activePetTier); - if(col == null) col = EnumChatFormatting.LIGHT_PURPLE.toString(); + if (col == null) col = EnumChatFormatting.LIGHT_PURPLE.toString(); - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(g+"Pet : " + + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(g + "Pet : " + col + WordUtils.capitalizeFully(activePet.replace("_", " ")))); String overall = "Skywars Main"; - if(isMe) { + if (isMe) { overall = Utils.chromaString("Literally the best player to exist"); // ego much - } else if(overallScore < 5 && (bankBalance+purseBalance) > 500*1000*1000) { - overall = EnumChatFormatting.GOLD+"Bill Gates"; - } else if(overallScore > 9) { + } else if (overallScore < 5 && (bankBalance + purseBalance) > 500 * 1000 * 1000) { + overall = EnumChatFormatting.GOLD + "Bill Gates"; + } else if (overallScore > 9) { overall = Utils.chromaString("Didn't even think this score was possible"); - } else if(overallScore > 8) { + } else if (overallScore > 8) { overall = Utils.chromaString("Mentally unstable"); - } else if(overallScore > 7) { - overall = EnumChatFormatting.GOLD+"Why though 0.0"; - } else if(overallScore > 5.5) { - overall = EnumChatFormatting.GOLD+"Bro stop playing"; - } else if(overallScore > 4) { - overall = EnumChatFormatting.GREEN+"Kinda sweaty"; - } else if(overallScore > 3) { - overall = EnumChatFormatting.YELLOW+"Alright I guess"; - } else if(overallScore > 2) { - overall = EnumChatFormatting.YELLOW+"Ender Non"; - } else if(overallScore > 1) { - overall = EnumChatFormatting.RED+"Played Skyblock"; + } else if (overallScore > 7) { + overall = EnumChatFormatting.GOLD + "Why though 0.0"; + } else if (overallScore > 5.5) { + overall = EnumChatFormatting.GOLD + "Bro stop playing"; + } else if (overallScore > 4) { + overall = EnumChatFormatting.GREEN + "Kinda sweaty"; + } else if (overallScore > 3) { + overall = EnumChatFormatting.YELLOW + "Alright I guess"; + } else if (overallScore > 2) { + overall = EnumChatFormatting.YELLOW + "Ender Non"; + } else if (overallScore > 1) { + overall = EnumChatFormatting.RED + "Played Skyblock"; } - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(g+"Overall score: " + - overall + g + " (" + Math.round(overallScore*10)/10f + ")")); + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(g + "Overall score: " + + overall + g + " (" + Math.round(overallScore * 10) / 10f + ")")); peekCommandExecutorService.shutdownNow(); } else { @@ -599,7 +587,7 @@ public class Commands { public SimpleCommand.ProcessCommandRunnable viewProfileRunnable = new SimpleCommand.ProcessCommandRunnable() { public void processCommand(ICommandSender sender, String[] args) { - if(!OpenGlHelper.isFramebufferEnabled()) { + if (!OpenGlHelper.isFramebufferEnabled()) { Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "Some parts of the profile viewer do not work with OF Fast Render. Go to ESC > Options > Video Settings > Performance > Fast Render to disable it.")); @@ -608,8 +596,8 @@ public class Commands { Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "Can't view profile, apikey is not set. Run /api new and put the result in settings.")); } else if (args.length == 0) { - NotEnoughUpdates.INSTANCE.profileViewer.getProfileByName(Minecraft.getMinecraft().thePlayer.getName(), profile -> { - if(profile == null) { + NotEnoughUpdates.profileViewer.getProfileByName(Minecraft.getMinecraft().thePlayer.getName(), profile -> { + if (profile == null) { Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "Invalid player name/api key. Maybe api is down? Try /api new.")); } else { @@ -621,8 +609,8 @@ public class Commands { Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "Too many arguments. Usage: /neuprofile [name]")); } else { - NotEnoughUpdates.INSTANCE.profileViewer.getProfileByName(args[0], profile -> { - if(profile == null) { + NotEnoughUpdates.profileViewer.getProfileByName(args[0], profile -> { + if (profile == null) { Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "Invalid player name/api key. Maybe api is down? Try /api new.")); } else { @@ -634,26 +622,25 @@ public class Commands { } }; - SimpleCommand joinDungeonCommand = new SimpleCommand("join", new SimpleCommand.ProcessCommandRunnable() { @Override public void processCommand(ICommandSender sender, String[] args) { if (!NotEnoughUpdates.INSTANCE.hasSkyblockScoreboard()) { Minecraft.getMinecraft().thePlayer.sendChatMessage("/join " + StringUtils.join(args, " ")); } else { - if(args.length != 1) { + if (args.length != 1) { Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText( - EnumChatFormatting.RED+"Example Usage: /join f7, /join m6 or /join 7")); + EnumChatFormatting.RED + "Example Usage: /join f7, /join m6 or /join 7")); } else { String cataPrefix = "catacombs"; - if(args[0].startsWith("m")){ + if (args[0].startsWith("m")) { cataPrefix = "master_catacombs"; } - String cmd = "/joindungeon "+cataPrefix+" " + args[0].charAt(args[0].length()-1); + String cmd = "/joindungeon " + cataPrefix + " " + args[0].charAt(args[0].length() - 1); Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText( - EnumChatFormatting.YELLOW+"Running command: "+cmd)); + EnumChatFormatting.YELLOW + "Running command: " + cmd)); Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText( - EnumChatFormatting.YELLOW+"The dungeon should start soon. If it doesn't, make sure you have a party of 5 people")); + EnumChatFormatting.YELLOW + "The dungeon should start soon. If it doesn't, make sure you have a party of 5 people")); Minecraft.getMinecraft().thePlayer.sendChatMessage(cmd); } } @@ -663,13 +650,13 @@ public class Commands { SimpleCommand viewProfileCommand = new SimpleCommand("neuprofile", viewProfileRunnable, new SimpleCommand.TabCompleteRunnable() { @Override public List tabComplete(ICommandSender sender, String[] args, BlockPos pos) { - if(args.length != 1) return null; + if (args.length != 1) return null; - String lastArg = args[args.length-1]; + String lastArg = args[args.length - 1]; List playerMatches = new ArrayList<>(); - for(EntityPlayer player : Minecraft.getMinecraft().theWorld.playerEntities) { + for (EntityPlayer player : Minecraft.getMinecraft().theWorld.playerEntities) { String playerName = player.getName(); - if(playerName.toLowerCase().startsWith(lastArg.toLowerCase())) { + if (playerName.toLowerCase().startsWith(lastArg.toLowerCase())) { playerMatches.add(playerName); } } @@ -680,7 +667,7 @@ public class Commands { SimpleCommand viewProfileShortCommand = new SimpleCommand("pv", new SimpleCommand.ProcessCommandRunnable() { @Override public void processCommand(ICommandSender sender, String[] args) { - if(!NotEnoughUpdates.INSTANCE.isOnSkyblock()) { + if (!NotEnoughUpdates.INSTANCE.isOnSkyblock()) { Minecraft.getMinecraft().thePlayer.sendChatMessage("/pv " + StringUtils.join(args, " ")); } else { viewProfileRunnable.processCommand(sender, args); @@ -710,7 +697,7 @@ public class Commands { } }); - private ScheduledExecutorService devES = Executors.newSingleThreadScheduledExecutor(); + private final ScheduledExecutorService devES = Executors.newSingleThreadScheduledExecutor(); private static final String[] devFailStrings = {"No.", "I said no.", "You aren't allowed to use this.", "Are you sure you want to use this? Type 'Yes' in chat.", "Are you sure you want to use this? Type 'Yes' in chat.", "Lmao you thought", "Ok please stop", "What do you want from me?", @@ -724,8 +711,8 @@ public class Commands { SimpleCommand devTestCommand = new SimpleCommand("neudevtest", new SimpleCommand.ProcessCommandRunnable() { @Override public void processCommand(ICommandSender sender, String[] args) { - if(!devTestUsers.contains(Minecraft.getMinecraft().thePlayer.getName().toLowerCase())) { - if(devFailIndex >= devFailStrings.length) { + if (!devTestUsers.contains(Minecraft.getMinecraft().thePlayer.getName().toLowerCase())) { + if (devFailIndex >= devFailStrings.length) { throw new Error("L") { @Override public void printStackTrace() { @@ -733,7 +720,7 @@ public class Commands { } }; } - if(devFailIndex == devFailStrings.length-2) { + if (devFailIndex == devFailStrings.length - 2) { devFailIndex++; ChatComponentText component = new ChatComponentText("\u00a7cYou are permanently banned from this server!"); @@ -746,39 +733,39 @@ public class Commands { Minecraft.getMinecraft().getNetHandler().getNetworkManager().closeChannel(component); return; } - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED+devFailStrings[devFailIndex++])); + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + devFailStrings[devFailIndex++])); return; } /*if(args.length == 1) { DupePOC.doDupe(args[0]); return; }*/ - if(args.length == 1 && args[0].equalsIgnoreCase("positiontest")) { + if (args.length == 1 && args[0].equalsIgnoreCase("positiontest")) { NotEnoughUpdates.INSTANCE.openGui = new GuiPositionEditor(); return; } - if(args.length == 2 && args[0].equalsIgnoreCase("pt")) { + if (args.length == 2 && args[0].equalsIgnoreCase("pt")) { EnumParticleTypes t = EnumParticleTypes.valueOf(args[1]); FishingHelper.type = t; return; } - if(args.length == 1 && args[0].equalsIgnoreCase("dev")) { + if (args.length == 1 && args[0].equalsIgnoreCase("dev")) { NotEnoughUpdates.INSTANCE.config.hidden.dev = true; return; } - if(args.length == 1 && args[0].equalsIgnoreCase("saveconfig")) { + if (args.length == 1 && args[0].equalsIgnoreCase("saveconfig")) { NotEnoughUpdates.INSTANCE.saveConfig(); return; } - if(args.length == 1 && args[0].equalsIgnoreCase("center")) { + if (args.length == 1 && args[0].equalsIgnoreCase("center")) { double x = Math.floor(Minecraft.getMinecraft().thePlayer.posX) + 0.5f; double z = Math.floor(Minecraft.getMinecraft().thePlayer.posZ) + 0.5f; Minecraft.getMinecraft().thePlayer.setPosition(x, Minecraft.getMinecraft().thePlayer.posY, z); return; } - if(args.length == 1 && args[0].equalsIgnoreCase("pansc")) { - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.GREEN+"Taking panorama screenshot")); + if (args.length == 1 && args[0].equalsIgnoreCase("pansc")) { + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.GREEN + "Taking panorama screenshot")); AtomicInteger perspective = new AtomicInteger(0); FancyPortals.perspectiveId = 0; @@ -790,22 +777,22 @@ public class Commands { @Override public void run() { Minecraft.getMinecraft().addScheduledTask(() -> { - ScreenShotHelper.saveScreenshot(new File("C:/Users/James/Desktop/"), "pansc-"+perspective.get()+".png", + ScreenShotHelper.saveScreenshot(new File("C:/Users/James/Desktop/"), "pansc-" + perspective.get() + ".png", Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayHeight, Minecraft.getMinecraft().getFramebuffer()); }); - if(perspective.incrementAndGet() >= 6) { + if (perspective.incrementAndGet() >= 6) { FancyPortals.perspectiveId = -1; return; } devES.schedule(() -> { FancyPortals.perspectiveId = perspective.get(); - if(FancyPortals.perspectiveId == 5) { + if (FancyPortals.perspectiveId == 5) { p.prevRotationYaw = p.rotationYaw = 0; p.prevRotationPitch = p.rotationPitch = -90; - } else if(FancyPortals.perspectiveId >= 1 && FancyPortals.perspectiveId <= 4) { - float yaw = 90*FancyPortals.perspectiveId-180; - if(yaw > 180) yaw -= 360; + } else if (FancyPortals.perspectiveId >= 1 && FancyPortals.perspectiveId <= 4) { + float yaw = 90 * FancyPortals.perspectiveId - 180; + if (yaw > 180) yaw -= 360; p.prevRotationYaw = p.rotationYaw = yaw; p.prevRotationPitch = p.rotationPitch = 0; } @@ -821,7 +808,7 @@ public class Commands { NEUEventListener.displayUpdateMessageIfOutOfDate(); } */ - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.GREEN+"Executing dubious code")); + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.GREEN + "Executing dubious code")); /*Minecraft.getMinecraft().thePlayer.rotationYaw = 0; Minecraft.getMinecraft().thePlayer.rotationPitch = 0; Minecraft.getMinecraft().thePlayer.setPosition( @@ -835,33 +822,33 @@ public class Commands { SimpleCommand packDevCommand = new SimpleCommand("neupackdev", new SimpleCommand.ProcessCommandRunnable() { @Override public void processCommand(ICommandSender sender, String[] args) { - if(args.length == 1 && args[0].equalsIgnoreCase("getnpc")) { + if (args.length == 1 && args[0].equalsIgnoreCase("getnpc")) { double distSq = 25; EntityPlayer closestNPC = null; EntityPlayerSP p = Minecraft.getMinecraft().thePlayer; - for(EntityPlayer player : Minecraft.getMinecraft().theWorld.playerEntities) { - if(player instanceof AbstractClientPlayer && p != player && player.getUniqueID().version() != 4) { + for (EntityPlayer player : Minecraft.getMinecraft().theWorld.playerEntities) { + if (player instanceof AbstractClientPlayer && p != player && player.getUniqueID().version() != 4) { double dSq = player.getDistanceSq(p.posX, p.posY, p.posZ); - if(dSq < distSq) { + if (dSq < distSq) { distSq = dSq; closestNPC = player; } } } - if(closestNPC == null) { - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED+"No NPCs found within 5 blocks :(")); + if (closestNPC == null) { + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "No NPCs found within 5 blocks :(")); } else { - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.GREEN+"Copied entity texture id to clipboard")); - MiscUtils.copyToClipboard(((AbstractClientPlayer)closestNPC).getLocationSkin().getResourcePath().replace("skins/", "")); + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.GREEN + "Copied entity texture id to clipboard")); + MiscUtils.copyToClipboard(((AbstractClientPlayer) closestNPC).getLocationSkin().getResourcePath().replace("skins/", "")); } return; } NotEnoughUpdates.INSTANCE.packDevEnabled = !NotEnoughUpdates.INSTANCE.packDevEnabled; - if(NotEnoughUpdates.INSTANCE.packDevEnabled) { - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.GREEN+"Enabled pack developer mode.")); + if (NotEnoughUpdates.INSTANCE.packDevEnabled) { + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.GREEN + "Enabled pack developer mode.")); } else { - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED+"Disabled pack developer mode.")); + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "Disabled pack developer mode.")); } } }); @@ -870,7 +857,7 @@ public class Commands { @Override public void processCommand(ICommandSender sender, String[] args) { Minecraft.getMinecraft().thePlayer.sendChatMessage("/warp dungeon_hub"); - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA+"Warping to:"+EnumChatFormatting.YELLOW+" Deez Nuts lmao")); + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "Warping to:" + EnumChatFormatting.YELLOW + " Deez Nuts lmao")); } }); @@ -900,7 +887,7 @@ public class Commands { SimpleCommand linksCommand = new SimpleCommand("neulinks", new SimpleCommand.ProcessCommandRunnable() { public void processCommand(ICommandSender sender, String[] args) { File repo = NotEnoughUpdates.INSTANCE.manager.repoLocation; - if(repo.exists()) { + if (repo.exists()) { File updateJson = new File(repo, "update.json"); try { JsonObject update = NotEnoughUpdates.INSTANCE.manager.getJsonFromFile(updateJson); @@ -926,47 +913,46 @@ public class Commands { } }); - SimpleCommand neumapCommand = new SimpleCommand("neumap", new SimpleCommand.ProcessCommandRunnable() { public void processCommand(ICommandSender sender, String[] args) { - if(NotEnoughUpdates.INSTANCE.colourMap == null) { - try(BufferedReader reader = new BufferedReader(new InputStreamReader(Minecraft.getMinecraft().getResourceManager().getResource( + if (NotEnoughUpdates.INSTANCE.colourMap == null) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(Minecraft.getMinecraft().getResourceManager().getResource( new ResourceLocation("notenoughupdates:maps/F1Full.json")).getInputStream(), StandardCharsets.UTF_8))) { JsonObject json = NotEnoughUpdates.INSTANCE.manager.gson.fromJson(reader, JsonObject.class); NotEnoughUpdates.INSTANCE.colourMap = new Color[128][128]; - for(int x=0; x<128; x++) { - for(int y=0; y<128; y++) { + for (int x = 0; x < 128; x++) { + for (int y = 0; y < 128; y++) { NotEnoughUpdates.INSTANCE.colourMap[x][y] = new Color(0, 0, 0, 0); } } - for(Map.Entry entry : json.entrySet()) { + for (Map.Entry entry : json.entrySet()) { int x = Integer.parseInt(entry.getKey().split(":")[0]); int y = Integer.parseInt(entry.getKey().split(":")[1]); NotEnoughUpdates.INSTANCE.colourMap[x][y] = new Color(entry.getValue().getAsInt(), true); } - } catch(Exception ignored) { } + } catch (Exception ignored) {} } - if(!NotEnoughUpdates.INSTANCE.config.hidden.dev) { + if (!NotEnoughUpdates.INSTANCE.config.hidden.dev) { NotEnoughUpdates.INSTANCE.openGui = new GuiDungeonMapEditor(); return; } - if(args.length == 1 && args[0].equals("reset")) { + if (args.length == 1 && args[0].equals("reset")) { NotEnoughUpdates.INSTANCE.colourMap = null; return; } - if(args.length != 2) { + if (args.length != 2) { NotEnoughUpdates.INSTANCE.openGui = new GuiDungeonMapEditor(); return; } - if(args[0].equals("save")) { + if (args[0].equals("save")) { ItemStack stack = Minecraft.getMinecraft().thePlayer.getHeldItem(); - if(stack != null && stack.getItem() instanceof ItemMap) { + if (stack != null && stack.getItem() instanceof ItemMap) { ItemMap map = (ItemMap) stack.getItem(); MapData mapData = map.getMapData(stack, Minecraft.getMinecraft().theWorld); @@ -986,33 +972,33 @@ public class Commands { c = new Color(MapColor.mapColorArray[j / 4].getMapColor(j & 3), true); } - json.addProperty(x+":"+y, c.getRGB()); + json.addProperty(x + ":" + y, c.getRGB()); } try { new File(NotEnoughUpdates.INSTANCE.manager.configLocation, "maps").mkdirs(); - NotEnoughUpdates.INSTANCE.manager.writeJson(json, new File(NotEnoughUpdates.INSTANCE.manager.configLocation, "maps/"+args[1]+".json")); - } catch(Exception e) { + NotEnoughUpdates.INSTANCE.manager.writeJson(json, new File(NotEnoughUpdates.INSTANCE.manager.configLocation, "maps/" + args[1] + ".json")); + } catch (Exception e) { e.printStackTrace(); } - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.GREEN+ + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.GREEN + "Saved to file.")); } return; } - if(args[0].equals("load")) { - JsonObject json = NotEnoughUpdates.INSTANCE.manager.getJsonFromFile(new File(NotEnoughUpdates.INSTANCE.manager.configLocation, "maps/"+args[1]+".json")); + if (args[0].equals("load")) { + JsonObject json = NotEnoughUpdates.INSTANCE.manager.getJsonFromFile(new File(NotEnoughUpdates.INSTANCE.manager.configLocation, "maps/" + args[1] + ".json")); NotEnoughUpdates.INSTANCE.colourMap = new Color[128][128]; - for(int x=0; x<128; x++) { - for(int y=0; y<128; y++) { + for (int x = 0; x < 128; x++) { + for (int y = 0; y < 128; y++) { NotEnoughUpdates.INSTANCE.colourMap[x][y] = new Color(0, 0, 0, 0); } } - for(Map.Entry entry : json.entrySet()) { + for (Map.Entry entry : json.entrySet()) { int x = Integer.parseInt(entry.getKey().split(":")[0]); int y = Integer.parseInt(entry.getKey().split(":")[1]); @@ -1028,7 +1014,7 @@ public class Commands { SimpleCommand cosmeticsCommand = new SimpleCommand("neucosmetics", new SimpleCommand.ProcessCommandRunnable() { public void processCommand(ICommandSender sender, String[] args) { - if(!OpenGlHelper.isFramebufferEnabled()) { + if (!OpenGlHelper.isFramebufferEnabled()) { Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "NEU cosmetics do not work with OF Fast Render. Go to ESC > Options > Video Settings > Performance > Fast Render to disable it.")); @@ -1042,14 +1028,14 @@ public class Commands { public void processCommand(ICommandSender sender, String[] args) { ItemStack held = Minecraft.getMinecraft().thePlayer.getHeldItem(); - if(held == null) { + if (held == null) { sender.addChatMessage(new ChatComponentText("\u00a7cYou can't customize your hand...")); return; } String heldUUID = NotEnoughUpdates.INSTANCE.manager.getUUIDForItem(held); - if(heldUUID == null) { + if (heldUUID == null) { sender.addChatMessage(new ChatComponentText("\u00a7cHeld item does not have UUID, cannot be customized")); return; } @@ -1063,7 +1049,7 @@ public class Commands { SimpleCommand.ProcessCommandRunnable settingsRunnable = new SimpleCommand.ProcessCommandRunnable() { public void processCommand(ICommandSender sender, String[] args) { - if(args.length > 0) { + if (args.length > 0) { NotEnoughUpdates.INSTANCE.openGui = new GuiScreenElementWrapper(new NEUConfigEditor(NotEnoughUpdates.INSTANCE.config, StringUtils.join(args, " "))); } else { NotEnoughUpdates.INSTANCE.openGui = new GuiScreenElementWrapper(NEUConfigEditor.editor); @@ -1085,11 +1071,11 @@ public class Commands { SimpleCommand neuAhCommand = new SimpleCommand("neuah", new SimpleCommand.ProcessCommandRunnable() { public void processCommand(ICommandSender sender, String[] args) { - if(!NotEnoughUpdates.INSTANCE.hasSkyblockScoreboard()) { - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED+ + if (!NotEnoughUpdates.INSTANCE.hasSkyblockScoreboard()) { + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "You must be on Skyblock to use this feature.")); - } else if(NotEnoughUpdates.INSTANCE.config.apiKey.apiKey == null || NotEnoughUpdates.INSTANCE.config.apiKey.apiKey.trim().isEmpty()) { - Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED+ + } else if (NotEnoughUpdates.INSTANCE.config.apiKey.apiKey == null || NotEnoughUpdates.INSTANCE.config.apiKey.apiKey.trim().isEmpty()) { + Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "Can't open NeuAH, apikey is not set. Run /api new and put the result in settings.")); } else { NotEnoughUpdates.INSTANCE.openGui = new CustomAHGui(); @@ -1097,7 +1083,8 @@ public class Commands { NotEnoughUpdates.INSTANCE.manager.auctionManager.customAH.clearSearch(); NotEnoughUpdates.INSTANCE.manager.auctionManager.customAH.updateSearch(); - if(args.length > 0) NotEnoughUpdates.INSTANCE.manager.auctionManager.customAH.setSearch(StringUtils.join(args, " ")); + if (args.length > 0) + NotEnoughUpdates.INSTANCE.manager.auctionManager.customAH.setSearch(StringUtils.join(args, " ")); } } }); diff --git a/src/main/java/io/github/moulberry/notenoughupdates/commands/SimpleCommand.java b/src/main/java/io/github/moulberry/notenoughupdates/commands/SimpleCommand.java index 029e24db..f13dca10 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/commands/SimpleCommand.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/commands/SimpleCommand.java @@ -5,13 +5,12 @@ import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.util.BlockPos; -import java.util.ArrayList; import java.util.List; public class SimpleCommand extends CommandBase { - private String commandName; - private ProcessCommandRunnable runnable; + private final String commandName; + private final ProcessCommandRunnable runnable; private TabCompleteRunnable tabRunnable; public SimpleCommand(String commandName, ProcessCommandRunnable runnable) { @@ -50,7 +49,7 @@ public class SimpleCommand extends CommandBase { } public List addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) { - if(tabRunnable != null) return tabRunnable.tabComplete(sender, args, pos); + if (tabRunnable != null) return tabRunnable.tabComplete(sender, args, pos); return null; } } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/commands/StatsCommand.java b/src/main/java/io/github/moulberry/notenoughupdates/commands/StatsCommand.java index b61c58ed..e0743162 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/commands/StatsCommand.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/commands/StatsCommand.java @@ -36,7 +36,7 @@ public class StatsCommand extends ClientCommandBase { @Override public void processCommand(ICommandSender sender, String[] args) { - if (args.length > 0){ + if (args.length > 0) { switch (args[0].toLowerCase(Locale.ROOT)) { case "modlist": clipboardAndSendMessage(createModList(new DiscordMarkdownBuilder()).toString()); @@ -49,7 +49,7 @@ public class StatsCommand extends ClientCommandBase { final ObjectName objectName = ObjectName.getInstance("com.sun.management:type=DiagnosticCommand"); final DiagnosticCommandMXBean proxy = JMX.newMXBeanProxy(server, objectName, DiagnosticCommandMXBean.class); clipboardAndSendMessage(HastebinUploader.upload(proxy.gcClassHistogram(new String[0]).replace("[", "[]"), HastebinUploader.Mode.NORMAL)); - }catch (Exception e){ + } catch (Exception e) { clipboardAndSendMessage(null); } }); @@ -103,8 +103,8 @@ public class StatsCommand extends ClientCommandBase { builder.append("Display", String.format("%dx%d (%s)", Display.getWidth(), Display.getHeight(), GL11.glGetString(GL11.GL_VENDOR))); builder.append("GPU", GL11.glGetString(GL11.GL_RENDERER)); builder.append("GPU Driver", GL11.glGetString(GL11.GL_VERSION)); - if(getMemorySize() > 0) builder.append("Maximum Memory", (getMemorySize() / 1024L / 1024L) + "MB"); - builder.append("Shaders", (""+OpenGlHelper.isFramebufferEnabled()).toUpperCase()); + if (getMemorySize() > 0) builder.append("Maximum Memory", (getMemorySize() / 1024L / 1024L) + "MB"); + builder.append("Shaders", ("" + OpenGlHelper.isFramebufferEnabled()).toUpperCase()); builder.category("Java Stats"); builder.append("Java", String.format("%s %dbit", System.getProperty("java.version"), Minecraft.getMinecraft().isJava64bit() ? 64 : 32)); builder.append("Memory", String.format("% 2d%% %03d/%03dMB", currentMemory * 100L / maxMemory, currentMemory / 1024L / 1024L, maxMemory / 1024L / 1024L)); @@ -113,7 +113,7 @@ public class StatsCommand extends ClientCommandBase { builder.append("FPS", String.valueOf(Minecraft.getDebugFPS())); builder.append("Loaded Mods", String.valueOf(activeModCount)); builder.append("Forge", ForgeVersion.getVersion()); - builder.category("Neu Settings"); + builder.category("Neu Settings"); builder.append("API Key", NotEnoughUpdates.INSTANCE.config.apiKey.apiKey.isEmpty() ? "FALSE" : "TRUE"); builder.append("On Skyblock", NotEnoughUpdates.INSTANCE.hasSkyblockScoreboard() ? "TRUE" : "FALSE"); builder.append("Mod Version", Loader.instance().getIndexedModList().get(NotEnoughUpdates.MODID).getSource().getName()); @@ -132,13 +132,13 @@ public class StatsCommand extends ClientCommandBase { return builder; } - private static long getMemorySize(){ + private static long getMemorySize() { try { return ((com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getTotalPhysicalMemorySize(); - } catch(Exception e){ + } catch (Exception e) { try { return ((com.sun.management.UnixOperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getTotalPhysicalMemorySize(); - } catch(Exception ignored){/*IGNORE*/} + } catch (Exception ignored) {/*IGNORE*/} } return -1; } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/BackgroundBlur.java b/src/main/java/io/github/moulberry/notenoughupdates/core/BackgroundBlur.java index 8a8655f9..98b4ccfe 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/BackgroundBlur.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/BackgroundBlur.java @@ -2,7 +2,6 @@ package io.github.moulberry.notenoughupdates.core; import io.github.moulberry.notenoughupdates.NotEnoughUpdates; import io.github.moulberry.notenoughupdates.core.util.render.RenderUtils; -import io.github.moulberry.notenoughupdates.util.Utils; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.renderer.GlStateManager; @@ -15,8 +14,6 @@ import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.TickEvent; -import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL30; @@ -39,15 +36,16 @@ public class BackgroundBlur { } } - private static HashMap blurOutput = new HashMap<>(); - private static HashMap lastBlurUse = new HashMap<>(); + private static final HashMap blurOutput = new HashMap<>(); + private static final HashMap lastBlurUse = new HashMap<>(); private static long lastBlur = 0; - private static HashSet requestedBlurs = new HashSet<>(); + private static final HashSet requestedBlurs = new HashSet<>(); private static int fogColour = 0; private static boolean registered = false; + public static void registerListener() { - if(!registered) { + if (!registered) { registered = true; MinecraftForge.EVENT_BUS.register(new BackgroundBlur()); } @@ -56,18 +54,18 @@ public class BackgroundBlur { private static boolean shouldBlur = true; public static void markDirty() { - if(Minecraft.getMinecraft().theWorld != null) { + if (Minecraft.getMinecraft().theWorld != null) { shouldBlur = true; } } public static void processBlurs() { - if(shouldBlur) { + if (shouldBlur) { shouldBlur = false; long currentTime = System.currentTimeMillis(); - for(float blur : requestedBlurs) { + for (float blur : requestedBlurs) { lastBlur = currentTime; lastBlurUse.put(blur, currentTime); @@ -80,12 +78,12 @@ public class BackgroundBlur { return new OutputStuff(fb, null, null); }); - if(output.framebuffer.framebufferWidth != width || output.framebuffer.framebufferHeight != height) { + if (output.framebuffer.framebufferWidth != width || output.framebuffer.framebufferHeight != height) { output.framebuffer.createBindFramebuffer(width, height); - if(output.blurShaderHorz != null) { + if (output.blurShaderHorz != null) { output.blurShaderHorz.setProjectionMatrix(createProjectionMatrix(width, height)); } - if(output.blurShaderVert != null) { + if (output.blurShaderVert != null) { output.blurShaderVert.setProjectionMatrix(createProjectionMatrix(width, height)); } } @@ -94,15 +92,15 @@ public class BackgroundBlur { } Set remove = new HashSet<>(); - for(Map.Entry entry : lastBlurUse.entrySet()) { - if(currentTime - entry.getValue() > 30*1000) { + for (Map.Entry entry : lastBlurUse.entrySet()) { + if (currentTime - entry.getValue() > 30 * 1000) { remove.add(entry.getKey()); } } - remove.remove((float)NotEnoughUpdates.INSTANCE.config.itemlist.bgBlurFactor); + remove.remove((float) NotEnoughUpdates.INSTANCE.config.itemlist.bgBlurFactor); - for(Map.Entry entry : blurOutput.entrySet()) { - if(remove.contains(entry.getKey())) { + for (Map.Entry entry : blurOutput.entrySet()) { + if (remove.contains(entry.getKey())) { entry.getValue().framebuffer.deleteFramebuffer(); entry.getValue().blurShaderHorz.deleteShader(); entry.getValue().blurShaderVert.deleteShader(); @@ -118,7 +116,7 @@ public class BackgroundBlur { @SubscribeEvent(priority = EventPriority.HIGHEST) public void onScreenRender(RenderGameOverlayEvent.Pre event) { - if(event.type == RenderGameOverlayEvent.ElementType.ALL) { + if (event.type == RenderGameOverlayEvent.ElementType.ALL) { processBlurs(); } Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false); @@ -127,9 +125,9 @@ public class BackgroundBlur { @SubscribeEvent public void onFogColour(EntityViewRenderEvent.FogColors event) { fogColour = 0xff000000; - fogColour |= ((int)(event.red*255) & 0xFF) << 16; - fogColour |= ((int)(event.green*255) & 0xFF) << 8; - fogColour |= (int)(event.blue*255) & 0xFF; + fogColour |= ((int) (event.red * 255) & 0xFF) << 16; + fogColour |= ((int) (event.green * 255) & 0xFF) << 8; + fogColour |= (int) (event.blue * 255) & 0xFF; } private static Framebuffer blurOutputHorz = null; @@ -137,15 +135,15 @@ public class BackgroundBlur { /** * Creates a projection matrix that projects from our coordinate space [0->width; 0->height] to OpenGL coordinate * space [-1 -> 1; 1 -> -1] (Note: flipped y-axis). - * + *

* This is so that we can render to and from the framebuffer in a way that is familiar to us, instead of needing to * apply scales and translations manually. */ private static Matrix4f createProjectionMatrix(int width, int height) { - Matrix4f projMatrix = new Matrix4f(); + Matrix4f projMatrix = new Matrix4f(); projMatrix.setIdentity(); - projMatrix.m00 = 2.0F / (float)width; - projMatrix.m11 = 2.0F / (float)(-height); + projMatrix.m00 = 2.0F / (float) width; + projMatrix.m11 = 2.0F / (float) (-height); projMatrix.m22 = -0.0020001999F; projMatrix.m33 = 1.0F; projMatrix.m03 = -1.0F; @@ -154,9 +152,10 @@ public class BackgroundBlur { return projMatrix; } - private static double lastBgBlurFactor = -1; + private static final double lastBgBlurFactor = -1; + private static void blurBackground(OutputStuff output, float blurFactor) { - if(!OpenGlHelper.isFramebufferEnabled() || !OpenGlHelper.areShadersSupported()) return; + if (!OpenGlHelper.isFramebufferEnabled() || !OpenGlHelper.areShadersSupported()) return; int width = Minecraft.getMinecraft().displayWidth; int height = Minecraft.getMinecraft().displayHeight; @@ -168,36 +167,36 @@ public class BackgroundBlur { GlStateManager.loadIdentity(); GlStateManager.translate(0.0F, 0.0F, -2000.0F); - if(blurOutputHorz == null) { + if (blurOutputHorz == null) { blurOutputHorz = new Framebuffer(width, height, false); blurOutputHorz.setFramebufferFilter(GL11.GL_NEAREST); } - if(blurOutputHorz == null || output == null) { + if (blurOutputHorz == null || output == null) { return; } - if(blurOutputHorz.framebufferWidth != width || blurOutputHorz.framebufferHeight != height) { + if (blurOutputHorz.framebufferWidth != width || blurOutputHorz.framebufferHeight != height) { blurOutputHorz.createBindFramebuffer(width, height); Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false); } - if(output.blurShaderHorz == null) { + if (output.blurShaderHorz == null) { try { output.blurShaderHorz = new Shader(Minecraft.getMinecraft().getResourceManager(), "blur", output.framebuffer, blurOutputHorz); output.blurShaderHorz.getShaderManager().getShaderUniform("BlurDir").set(1, 0); output.blurShaderHorz.setProjectionMatrix(createProjectionMatrix(width, height)); - } catch(Exception e) { } + } catch (Exception ignored) {} } - if(output.blurShaderVert == null) { + if (output.blurShaderVert == null) { try { output.blurShaderVert = new Shader(Minecraft.getMinecraft().getResourceManager(), "blur", blurOutputHorz, output.framebuffer); output.blurShaderVert.getShaderManager().getShaderUniform("BlurDir").set(0, 1); output.blurShaderVert.setProjectionMatrix(createProjectionMatrix(width, height)); - } catch(Exception e) { } + } catch (Exception ignored) {} } - if(output.blurShaderHorz != null && output.blurShaderVert != null) { - if(output.blurShaderHorz.getShaderManager().getShaderUniform("Radius") == null) { + if (output.blurShaderHorz != null && output.blurShaderVert != null) { + if (output.blurShaderHorz.getShaderManager().getShaderUniform("Radius") == null) { //Corrupted shader? return; } @@ -231,30 +230,30 @@ public class BackgroundBlur { */ public static void renderBlurredBackground(float blurStrength, int screenWidth, int screenHeight, int x, int y, int blurWidth, int blurHeight, boolean forcedUpdate) { - if(!OpenGlHelper.isFramebufferEnabled() || !OpenGlHelper.areShadersSupported()) return; - if(blurStrength < 0.5) return; + if (!OpenGlHelper.isFramebufferEnabled() || !OpenGlHelper.areShadersSupported()) return; + if (blurStrength < 0.5) return; requestedBlurs.add(blurStrength); long currentTime = System.currentTimeMillis(); - if(currentTime - lastBlur > 300) { + if (currentTime - lastBlur > 300) { shouldBlur = true; - if(currentTime - lastBlur > 400 && forcedUpdate) return; + if (currentTime - lastBlur > 400 && forcedUpdate) return; } - if(blurOutput.isEmpty()) return; + if (blurOutput.isEmpty()) return; OutputStuff out = blurOutput.get(blurStrength); - if(out == null) { + if (out == null) { out = blurOutput.values().iterator().next(); } - float uMin = x/(float)screenWidth; - float uMax = (x+blurWidth)/(float)screenWidth; - float vMin = (screenHeight-y)/(float)screenHeight; - float vMax = (screenHeight-y-blurHeight)/(float)screenHeight; + float uMin = x / (float) screenWidth; + float uMax = (x + blurWidth) / (float) screenWidth; + float vMin = (screenHeight - y) / (float) screenHeight; + float vMax = (screenHeight - y - blurHeight) / (float) screenHeight; GlStateManager.depthMask(false); - Gui.drawRect(x, y, x+blurWidth, y+blurHeight, fogColour); + Gui.drawRect(x, y, x + blurWidth, y + blurHeight, fogColour); out.framebuffer.bindFramebufferTexture(); GlStateManager.color(1f, 1f, 1f, 1f); RenderUtils.drawTexturedRect(x, y, blurWidth, blurHeight, uMin, uMax, vMin, vMax); diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/ChromaColour.java b/src/main/java/io/github/moulberry/notenoughupdates/core/ChromaColour.java index 9509c332..1581c77c 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/ChromaColour.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/ChromaColour.java @@ -25,9 +25,8 @@ public class ChromaColour { int[] arr = new int[split.length]; - - for(int i=0; i 0) { + if (chr > 0) { float seconds = getSecondsForSpeed(chr); - hsv[0] += (System.currentTimeMillis()-startTime)/1000f/seconds; + hsv[0] += (System.currentTimeMillis() - startTime) / 1000f / seconds; hsv[0] %= 1; - if(hsv[0] < 0) hsv[0] += 1; + if (hsv[0] < 0) hsv[0] += 1; } return (a & 0xFF) << 24 | (Color.HSBtoRGB(hsv[0], hsv[1], hsv[2]) & 0x00FFFFFF); @@ -85,11 +85,10 @@ public class ChromaColour { float[] hsv = Color.RGBtoHSB(r, g, b, null); - hsv[0] += degrees/360f; + hsv[0] += degrees / 360f; hsv[0] %= 1; return (a & 0xFF) << 24 | (Color.HSBtoRGB(hsv[0], hsv[1], hsv[2]) & 0x00FFFFFF); } - } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/GlScissorStack.java b/src/main/java/io/github/moulberry/notenoughupdates/core/GlScissorStack.java index f70bec40..45f7e269 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/GlScissorStack.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/GlScissorStack.java @@ -27,10 +27,10 @@ public class GlScissorStack { right = Math.min(right, this.right); bottom = Math.min(bottom, this.bottom); - if(top > bottom) { + if (top > bottom) { top = bottom; } - if(left > right) { + if (left > right) { left = right; } @@ -40,39 +40,39 @@ public class GlScissorStack { public void set(ScaledResolution scaledResolution) { int height = Minecraft.getMinecraft().displayHeight; int scale = scaledResolution.getScaleFactor(); - GL11.glScissor(left*scale, height-bottom*scale, (right-left)*scale, (bottom-top)*scale); + GL11.glScissor(left * scale, height - bottom * scale, (right - left) * scale, (bottom - top) * scale); } } - private static LinkedList boundsStack = new LinkedList<>(); + private static final LinkedList boundsStack = new LinkedList<>(); public static void push(int left, int top, int right, int bottom, ScaledResolution scaledResolution) { - if(right < left) { + if (right < left) { int temp = right; right = left; left = temp; } - if(bottom < top) { + if (bottom < top) { int temp = bottom; bottom = top; top = temp; } - if(boundsStack.isEmpty()) { + if (boundsStack.isEmpty()) { boundsStack.push(new Bounds(left, top, right, bottom)); } else { boundsStack.push(boundsStack.peek().createSubBound(left, top, right, bottom)); } - if(!boundsStack.isEmpty()) { + if (!boundsStack.isEmpty()) { boundsStack.peek().set(scaledResolution); } GL11.glEnable(GL11.GL_SCISSOR_TEST); } public static void pop(ScaledResolution scaledResolution) { - if(!boundsStack.isEmpty()) { + if (!boundsStack.isEmpty()) { boundsStack.pop(); } - if(boundsStack.isEmpty()) { + if (boundsStack.isEmpty()) { GL11.glDisable(GL11.GL_SCISSOR_TEST); } else { boundsStack.peek().set(scaledResolution); diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElement.java b/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElement.java index 5969c691..aa3d4989 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElement.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElement.java @@ -2,9 +2,11 @@ package io.github.moulberry.notenoughupdates.core; import net.minecraft.client.gui.Gui; -public abstract class GuiElement extends Gui { +public abstract class GuiElement extends Gui { public abstract void render(); + public abstract boolean mouseInput(int mouseX, int mouseY); + public abstract boolean keyboardInput(); } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElementBoolean.java b/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElementBoolean.java index bfd95612..66310dfd 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElementBoolean.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElementBoolean.java @@ -15,8 +15,8 @@ public class GuiElementBoolean extends GuiElement { public int x; public int y; private boolean value; - private int clickRadius; - private Consumer toggleCallback; + private final int clickRadius; + private final Consumer toggleCallback; private boolean previewValue; private int animation = 0; @@ -38,7 +38,7 @@ public class GuiElementBoolean extends GuiElement { this.toggleCallback = toggleCallback; this.lastMillis = System.currentTimeMillis(); - if(value) animation = 36; + if (value) animation = 36; } @Override @@ -52,58 +52,58 @@ public class GuiElementBoolean extends GuiElement { long deltaMillis = currentMillis - lastMillis; lastMillis = currentMillis; boolean passedLimit = false; - if(previewValue != value) { - if((previewValue && animation > 12) || + if (previewValue != value) { + if ((previewValue && animation > 12) || (!previewValue && animation < 24)) { passedLimit = true; } } - if(previewValue != passedLimit) { - animation += deltaMillis/10; + if (previewValue != passedLimit) { + animation += deltaMillis / 10; } else { - animation -= deltaMillis/10; + animation -= deltaMillis / 10; } - lastMillis -= deltaMillis%10; + lastMillis -= deltaMillis % 10; - if(previewValue == value) { + if (previewValue == value) { animation = Math.max(0, Math.min(36, animation)); - } else if(!passedLimit) { - if(previewValue) { + } else if (!passedLimit) { + if (previewValue) { animation = Math.max(0, Math.min(12, animation)); } else { animation = Math.max(24, Math.min(36, animation)); } } else { - if(previewValue) { + if (previewValue) { animation = Math.max(12, animation); } else { animation = Math.min(24, animation); } } - int animation = (int)(LerpUtils.sigmoidZeroOne(this.animation/36f)*36); - if(animation < 3) { + int animation = (int) (LerpUtils.sigmoidZeroOne(this.animation / 36f) * 36); + if (animation < 3) { buttonLoc = GuiTextures.OFF; - } else if(animation < 13) { + } else if (animation < 13) { buttonLoc = GuiTextures.ONE; - } else if(animation < 23) { + } else if (animation < 23) { buttonLoc = GuiTextures.TWO; - } else if(animation < 33) { + } else if (animation < 33) { buttonLoc = GuiTextures.THREE; } Minecraft.getMinecraft().getTextureManager().bindTexture(buttonLoc); - RenderUtils.drawTexturedRect(x+animation, y, 12, 14); + RenderUtils.drawTexturedRect(x + animation, y, 12, 14); } @Override public boolean mouseInput(int mouseX, int mouseY) { - if(mouseX > x-clickRadius && mouseX < x+xSize+clickRadius && - mouseY > y-clickRadius && mouseY < y+ySize+clickRadius) { - if(Mouse.getEventButton() == 0) { - if(Mouse.getEventButtonState()) { + if (mouseX > x - clickRadius && mouseX < x + xSize + clickRadius && + mouseY > y - clickRadius && mouseY < y + ySize + clickRadius) { + if (Mouse.getEventButton() == 0) { + if (Mouse.getEventButtonState()) { previewValue = !value; - } else if(previewValue == !value) { + } else if (previewValue == !value) { value = !value; toggleCallback.accept(value); } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElementColour.java b/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElementColour.java index 3ab47531..6d267040 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElementColour.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElementColour.java @@ -30,18 +30,18 @@ public class GuiElementColour extends GuiElement { private final GuiElementTextField hexField = new GuiElementTextField("", GuiElementTextField.SCALE_TEXT | GuiElementTextField.FORCE_CAPS | GuiElementTextField.NO_SPACE); - private int x; - private int y; + private final int x; + private final int y; private int xSize = 119; - private int ySize = 89; + private final int ySize = 89; private float wheelAngle = 0; private float wheelRadius = 0; private int clickedComponent = -1; - private Consumer colourChangedCallback; - private Runnable closeCallback; + private final Consumer colourChangedCallback; + private final Runnable closeCallback; private String colour; private final boolean opacitySlider; @@ -56,8 +56,8 @@ public class GuiElementColour extends GuiElement { Runnable closeCallback, boolean opacitySlider, boolean valueSlider) { final ScaledResolution scaledResolution = new ScaledResolution(Minecraft.getMinecraft()); - this.y = Math.max(10, Math.min(scaledResolution.getScaledHeight()-ySize-10, y)); - this.x = Math.max(10, Math.min(scaledResolution.getScaledWidth()-xSize-10, x)); + this.y = Math.max(10, Math.min(scaledResolution.getScaledHeight() - ySize - 10, y)); + this.x = Math.max(10, Math.min(scaledResolution.getScaledWidth() - xSize - 10, x)); this.colour = initialColour; this.colourChangedCallback = colourChangedCallback; @@ -71,13 +71,13 @@ public class GuiElementColour extends GuiElement { this.opacitySlider = opacitySlider; this.valueSlider = valueSlider; - if(!valueSlider) xSize -= 15; - if(!opacitySlider) xSize -= 15; + if (!valueSlider) xSize -= 15; + if (!opacitySlider) xSize -= 15; } public void updateAngleAndRadius(float[] hsv) { this.wheelRadius = hsv[1]; - this.wheelAngle = hsv[0]*360; + this.wheelAngle = hsv[0] * 360; } public void render() { @@ -89,27 +89,27 @@ public class GuiElementColour extends GuiElement { BufferedImage bufferedImage = new BufferedImage(288, 288, BufferedImage.TYPE_INT_ARGB); float borderRadius = 0.05f; - if(Keyboard.isKeyDown(Keyboard.KEY_N)) borderRadius = 0; - for(int x=-16; x<272; x++) { - for(int y=-16; y<272; y++) { - float radius = (float) Math.sqrt(((x-128)*(x-128)+(y-128)*(y-128))/16384f); - float angle = (float) Math.toDegrees(Math.atan((128-x)/(y-128+1E-5))+Math.PI/2); - if(y < 128) angle += 180; - if(radius <= 1) { - int rgb = Color.getHSBColor(angle/360f, (float)Math.pow(radius, 1.5f), hsv[2]).getRGB(); - bufferedImage.setRGB(x+16, y+16, rgb); - } else if(radius <= 1+borderRadius) { - float invBlackAlpha = Math.abs(radius-1-borderRadius/2)/borderRadius*2; - float blackAlpha = 1-invBlackAlpha; - - if(radius > 1+borderRadius/2) { - bufferedImage.setRGB(x+16, y+16, (int)(blackAlpha*255) << 24); + if (Keyboard.isKeyDown(Keyboard.KEY_N)) borderRadius = 0; + for (int x = -16; x < 272; x++) { + for (int y = -16; y < 272; y++) { + float radius = (float) Math.sqrt(((x - 128) * (x - 128) + (y - 128) * (y - 128)) / 16384f); + float angle = (float) Math.toDegrees(Math.atan((128 - x) / (y - 128 + 1E-5)) + Math.PI / 2); + if (y < 128) angle += 180; + if (radius <= 1) { + int rgb = Color.getHSBColor(angle / 360f, (float) Math.pow(radius, 1.5f), hsv[2]).getRGB(); + bufferedImage.setRGB(x + 16, y + 16, rgb); + } else if (radius <= 1 + borderRadius) { + float invBlackAlpha = Math.abs(radius - 1 - borderRadius / 2) / borderRadius * 2; + float blackAlpha = 1 - invBlackAlpha; + + if (radius > 1 + borderRadius / 2) { + bufferedImage.setRGB(x + 16, y + 16, (int) (blackAlpha * 255) << 24); } else { - Color col = Color.getHSBColor(angle/360f, 1, hsv[2]); - int rgb = (int)(col.getRed()*invBlackAlpha) << 16 | - (int)(col.getGreen()*invBlackAlpha) << 8 | - (int)(col.getBlue()*invBlackAlpha); - bufferedImage.setRGB(x+16, y+16, 0xff000000 | rgb); + Color col = Color.getHSBColor(angle / 360f, 1, hsv[2]); + int rgb = (int) (col.getRed() * invBlackAlpha) << 16 | + (int) (col.getGreen() * invBlackAlpha) << 8 | + (int) (col.getBlue() * invBlackAlpha); + bufferedImage.setRGB(x + 16, y + 16, 0xff000000 | rgb); } } @@ -117,191 +117,191 @@ public class GuiElementColour extends GuiElement { } BufferedImage bufferedImageValue = new BufferedImage(10, 64, BufferedImage.TYPE_INT_ARGB); - for(int x=0; x<10; x++) { - for(int y=0; y<64; y++) { - if((x == 0 || x == 9) && (y == 0 || y == 63)) continue; + for (int x = 0; x < 10; x++) { + for (int y = 0; y < 64; y++) { + if ((x == 0 || x == 9) && (y == 0 || y == 63)) continue; - int rgb = Color.getHSBColor(wheelAngle/360, wheelRadius, (64-y)/64f).getRGB(); + int rgb = Color.getHSBColor(wheelAngle / 360, wheelRadius, (64 - y) / 64f).getRGB(); bufferedImageValue.setRGB(x, y, rgb); } } BufferedImage bufferedImageOpacity = new BufferedImage(10, 64, BufferedImage.TYPE_INT_ARGB); - for(int x=0; x<10; x++) { - for(int y=0; y<64; y++) { - if((x == 0 || x == 9) && (y == 0 || y == 63)) continue; + for (int x = 0; x < 10; x++) { + for (int y = 0; y < 64; y++) { + if ((x == 0 || x == 9) && (y == 0 || y == 63)) continue; - int rgb = (currentColour & 0x00FFFFFF) | (Math.min(255, (64-y)*4) << 24); + int rgb = (currentColour & 0x00FFFFFF) | (Math.min(255, (64 - y) * 4) << 24); bufferedImageOpacity.setRGB(x, y, rgb); } } - float selradius = (float)Math.pow(wheelRadius, 1/1.5f)*32; - int selx = (int)(Math.cos(Math.toRadians(wheelAngle))*selradius); - int sely = (int)(Math.sin(Math.toRadians(wheelAngle))*selradius); + float selradius = (float) Math.pow(wheelRadius, 1 / 1.5f) * 32; + int selx = (int) (Math.cos(Math.toRadians(wheelAngle)) * selradius); + int sely = (int) (Math.sin(Math.toRadians(wheelAngle)) * selradius); int valueOffset = 0; - if(valueSlider) { + if (valueSlider) { valueOffset = 15; Minecraft.getMinecraft().getTextureManager().loadTexture(colourPickerBarValueLocation, new DynamicTexture(bufferedImageValue)); Minecraft.getMinecraft().getTextureManager().bindTexture(colourPickerBarValueLocation); GlStateManager.color(1, 1, 1, 1); - RenderUtils.drawTexturedRect(x+5+64+5, y+5, 10, 64, GL11.GL_NEAREST); + RenderUtils.drawTexturedRect(x + 5 + 64 + 5, y + 5, 10, 64, GL11.GL_NEAREST); } int opacityOffset = 0; - if(opacitySlider) { + if (opacitySlider) { opacityOffset = 15; Minecraft.getMinecraft().getTextureManager().bindTexture(colour_selector_bar_alpha); GlStateManager.color(1, 1, 1, 1); - RenderUtils.drawTexturedRect(x+5+64+5+valueOffset, y+5, 10, 64, GL11.GL_NEAREST); - + RenderUtils.drawTexturedRect(x + 5 + 64 + 5 + valueOffset, y + 5, 10, 64, GL11.GL_NEAREST); + Minecraft.getMinecraft().getTextureManager().loadTexture(colourPickerBarOpacityLocation, new DynamicTexture(bufferedImageOpacity)); Minecraft.getMinecraft().getTextureManager().bindTexture(colourPickerBarOpacityLocation); GlStateManager.color(1, 1, 1, 1); - RenderUtils.drawTexturedRect(x+5+64+5+valueOffset, y+5, 10, 64, GL11.GL_NEAREST); + RenderUtils.drawTexturedRect(x + 5 + 64 + 5 + valueOffset, y + 5, 10, 64, GL11.GL_NEAREST); } int chromaSpeed = ChromaColour.getSpeed(colour); int currentColourChroma = ChromaColour.specialToChromaRGB(colour); Color cChroma = new Color(currentColourChroma, true); - float hsvChroma[] = Color.RGBtoHSB(cChroma.getRed(), cChroma.getGreen(), cChroma.getBlue(), null); + float[] hsvChroma = Color.RGBtoHSB(cChroma.getRed(), cChroma.getGreen(), cChroma.getBlue(), null); - if(chromaSpeed > 0) { - Gui.drawRect(x+5+64+valueOffset+opacityOffset+5+1, y+5+1, - x+5+64+valueOffset+opacityOffset+5+10-1, y+5+64-1, + if (chromaSpeed > 0) { + Gui.drawRect(x + 5 + 64 + valueOffset + opacityOffset + 5 + 1, y + 5 + 1, + x + 5 + 64 + valueOffset + opacityOffset + 5 + 10 - 1, y + 5 + 64 - 1, Color.HSBtoRGB(hsvChroma[0], 0.8f, 0.8f)); } else { - Gui.drawRect(x+5+64+valueOffset+opacityOffset+5+1, y+5+27+1, - x+5+64+valueOffset+opacityOffset+5+10-1, y+5+37-1, - Color.HSBtoRGB((hsvChroma[0]+(System.currentTimeMillis()-ChromaColour.startTime)/1000f)%1, 0.8f, 0.8f)); + Gui.drawRect(x + 5 + 64 + valueOffset + opacityOffset + 5 + 1, y + 5 + 27 + 1, + x + 5 + 64 + valueOffset + opacityOffset + 5 + 10 - 1, y + 5 + 37 - 1, + Color.HSBtoRGB((hsvChroma[0] + (System.currentTimeMillis() - ChromaColour.startTime) / 1000f) % 1, 0.8f, 0.8f)); } Minecraft.getMinecraft().getTextureManager().bindTexture(colour_selector_bar); GlStateManager.color(1, 1, 1, 1); - if(valueSlider) RenderUtils.drawTexturedRect(x+5+64+5, y+5, 10, 64, GL11.GL_NEAREST); - if(opacitySlider) RenderUtils.drawTexturedRect(x+5+64+5+valueOffset, y+5, 10, 64, GL11.GL_NEAREST); + if (valueSlider) RenderUtils.drawTexturedRect(x + 5 + 64 + 5, y + 5, 10, 64, GL11.GL_NEAREST); + if (opacitySlider) RenderUtils.drawTexturedRect(x + 5 + 64 + 5 + valueOffset, y + 5, 10, 64, GL11.GL_NEAREST); - if(chromaSpeed > 0) { - RenderUtils.drawTexturedRect(x+5+64+valueOffset+opacityOffset+5, y+5, 10, 64, GL11.GL_NEAREST); + if (chromaSpeed > 0) { + RenderUtils.drawTexturedRect(x + 5 + 64 + valueOffset + opacityOffset + 5, y + 5, 10, 64, GL11.GL_NEAREST); } else { Minecraft.getMinecraft().getTextureManager().bindTexture(colour_selector_chroma); - RenderUtils.drawTexturedRect(x+5+64+valueOffset+opacityOffset+5, y+5+27, 10, 10, GL11.GL_NEAREST); + RenderUtils.drawTexturedRect(x + 5 + 64 + valueOffset + opacityOffset + 5, y + 5 + 27, 10, 10, GL11.GL_NEAREST); } - if(valueSlider) Gui.drawRect(x+5+64+5, y+5+64-(int)(64*hsv[2]), - x+5+64+valueOffset, y+5+64-(int)(64*hsv[2])+1, 0xFF000000); - if(opacitySlider) Gui.drawRect(x+5+64+5+valueOffset, y+5+64-c.getAlpha()/4, - x+5+64+valueOffset+opacityOffset, y+5+64-c.getAlpha()/4-1, 0xFF000000); - if(chromaSpeed > 0) { - Gui.drawRect(x+5+64+valueOffset+opacityOffset+5, - y+5+64-(int)(chromaSpeed/255f*64), - x+5+64+valueOffset+opacityOffset+5+10, - y+5+64-(int)(chromaSpeed/255f*64)+1, 0xFF000000); + if (valueSlider) Gui.drawRect(x + 5 + 64 + 5, y + 5 + 64 - (int) (64 * hsv[2]), + x + 5 + 64 + valueOffset, y + 5 + 64 - (int) (64 * hsv[2]) + 1, 0xFF000000); + if (opacitySlider) Gui.drawRect(x + 5 + 64 + 5 + valueOffset, y + 5 + 64 - c.getAlpha() / 4, + x + 5 + 64 + valueOffset + opacityOffset, y + 5 + 64 - c.getAlpha() / 4 - 1, 0xFF000000); + if (chromaSpeed > 0) { + Gui.drawRect(x + 5 + 64 + valueOffset + opacityOffset + 5, + y + 5 + 64 - (int) (chromaSpeed / 255f * 64), + x + 5 + 64 + valueOffset + opacityOffset + 5 + 10, + y + 5 + 64 - (int) (chromaSpeed / 255f * 64) + 1, 0xFF000000); } Minecraft.getMinecraft().getTextureManager().loadTexture(colourPickerLocation, new DynamicTexture(bufferedImage)); Minecraft.getMinecraft().getTextureManager().bindTexture(colourPickerLocation); GlStateManager.color(1, 1, 1, 1); - RenderUtils.drawTexturedRect(x+1, y+1, 72, 72, GL11.GL_LINEAR); + RenderUtils.drawTexturedRect(x + 1, y + 1, 72, 72, GL11.GL_LINEAR); Minecraft.getMinecraft().getTextureManager().bindTexture(colour_selector_dot); GlStateManager.color(1, 1, 1, 1); - RenderUtils.drawTexturedRect(x+5+32+selx-4, y+5+32+sely-4, 8, 8, GL11.GL_NEAREST); + RenderUtils.drawTexturedRect(x + 5 + 32 + selx - 4, y + 5 + 32 + sely - 4, 8, 8, GL11.GL_NEAREST); - TextRenderUtils.drawStringCenteredScaledMaxWidth(EnumChatFormatting.GRAY.toString()+Math.round(hsv[2]*100)+"", + TextRenderUtils.drawStringCenteredScaledMaxWidth(EnumChatFormatting.GRAY.toString() + Math.round(hsv[2] * 100) + "", Minecraft.getMinecraft().fontRendererObj, - x+5+64+5+5-(Math.round(hsv[2]*100)==100?1:0), y+5+64+5+5, true, 13, -1); - if(opacitySlider) { - TextRenderUtils.drawStringCenteredScaledMaxWidth(EnumChatFormatting.GRAY.toString()+Math.round(c.getAlpha()/255f*100)+"", + x + 5 + 64 + 5 + 5 - (Math.round(hsv[2] * 100) == 100 ? 1 : 0), y + 5 + 64 + 5 + 5, true, 13, -1); + if (opacitySlider) { + TextRenderUtils.drawStringCenteredScaledMaxWidth(EnumChatFormatting.GRAY.toString() + Math.round(c.getAlpha() / 255f * 100) + "", Minecraft.getMinecraft().fontRendererObj, - x+5+64+5+valueOffset+5, y+5+64+5+5, true, 13, -1); + x + 5 + 64 + 5 + valueOffset + 5, y + 5 + 64 + 5 + 5, true, 13, -1); } - if(chromaSpeed > 0) { - TextRenderUtils.drawStringCenteredScaledMaxWidth(EnumChatFormatting.GRAY.toString()+ - (int)ChromaColour.getSecondsForSpeed(chromaSpeed)+"s", + if (chromaSpeed > 0) { + TextRenderUtils.drawStringCenteredScaledMaxWidth(EnumChatFormatting.GRAY.toString() + + (int) ChromaColour.getSecondsForSpeed(chromaSpeed) + "s", Minecraft.getMinecraft().fontRendererObj, - x+5+64+5+valueOffset+opacityOffset+6, y+5+64+5+5, true, 13, -1); + x + 5 + 64 + 5 + valueOffset + opacityOffset + 6, y + 5 + 64 + 5 + 5, true, 13, -1); } hexField.setSize(48, 10); - if(!hexField.getFocus()) hexField.setText(Integer.toHexString(c.getRGB() & 0xFFFFFF).toUpperCase()); + if (!hexField.getFocus()) hexField.setText(Integer.toHexString(c.getRGB() & 0xFFFFFF).toUpperCase()); - StringBuilder sb = new StringBuilder(EnumChatFormatting.GRAY+"#"); - for(int i=0; i<6-hexField.getText().length(); i++) { + StringBuilder sb = new StringBuilder(EnumChatFormatting.GRAY + "#"); + for (int i = 0; i < 6 - hexField.getText().length(); i++) { sb.append("0"); } sb.append(EnumChatFormatting.WHITE); hexField.setPrependText(sb.toString()); - hexField.render(x+5+8, y+5+64+5); + hexField.render(x + 5 + 8, y + 5 + 64 + 5); } public boolean mouseInput(int mouseX, int mouseY) { ScaledResolution scaledResolution = new ScaledResolution(Minecraft.getMinecraft()); - float mouseXF = (float)(Mouse.getX() * scaledResolution.getScaledWidth_double() / + float mouseXF = (float) (Mouse.getX() * scaledResolution.getScaledWidth_double() / Minecraft.getMinecraft().displayWidth); - float mouseYF = (float)(scaledResolution.getScaledHeight_double() - Mouse.getY() * + float mouseYF = (float) (scaledResolution.getScaledHeight_double() - Mouse.getY() * scaledResolution.getScaledHeight_double() / Minecraft.getMinecraft().displayHeight - 1); - if((Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) && Mouse.getEventButtonState()) { - if(mouseX > x+5+8 && mouseX < x+5+8+48) { - if(mouseY > y+5+64+5 && mouseY < y+5+64+5+10) { + if ((Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) && Mouse.getEventButtonState()) { + if (mouseX > x + 5 + 8 && mouseX < x + 5 + 8 + 48) { + if (mouseY > y + 5 + 64 + 5 && mouseY < y + 5 + 64 + 5 + 10) { hexField.mouseClicked(mouseX, mouseY, Mouse.getEventButton()); clickedComponent = -1; return true; } } } - if(!Mouse.getEventButtonState() && Mouse.getEventButton() == 0) { + if (!Mouse.getEventButtonState() && Mouse.getEventButton() == 0) { clickedComponent = -1; } - if(Mouse.getEventButtonState() && Mouse.getEventButton() == 0) { - if(mouseX >= x && mouseX <= x+119 && - mouseY >= y && mouseY <= y+89) { + if (Mouse.getEventButtonState() && Mouse.getEventButton() == 0) { + if (mouseX >= x && mouseX <= x + 119 && + mouseY >= y && mouseY <= y + 89) { hexField.unfocus(); int xWheel = mouseX - x - 5; int yWheel = mouseY - y - 5; - if(xWheel > 0 && xWheel < 64) { - if(yWheel > 0 && yWheel < 64) { + if (xWheel > 0 && xWheel < 64) { + if (yWheel > 0 && yWheel < 64) { clickedComponent = 0; } } - int xValue = mouseX - (x+5+64+5); + int xValue = mouseX - (x + 5 + 64 + 5); int y = mouseY - this.y - 5; int opacityOffset = opacitySlider ? 15 : 0; int valueOffset = valueSlider ? 15 : 0; - if(y > -5 && y <= 69) { - if(valueSlider) { - if(xValue > 0 && xValue < 10) { + if (y > -5 && y <= 69) { + if (valueSlider) { + if (xValue > 0 && xValue < 10) { clickedComponent = 1; } } - if(opacitySlider) { - int xOpacity = mouseX - (x+5+64+5+valueOffset); + if (opacitySlider) { + int xOpacity = mouseX - (x + 5 + 64 + 5 + valueOffset); - if(xOpacity > 0 && xOpacity < 10) { + if (xOpacity > 0 && xOpacity < 10) { clickedComponent = 2; } } } int chromaSpeed = ChromaColour.getSpeed(colour); - int xChroma = mouseX - (x+5+64+valueOffset+opacityOffset+5); - if(xChroma > 0 && xChroma < 10) { - if(chromaSpeed > 0) { - if(y > -5 && y <= 69) { + int xChroma = mouseX - (x + 5 + 64 + valueOffset + opacityOffset + 5); + if (xChroma > 0 && xChroma < 10) { + if (chromaSpeed > 0) { + if (y > -5 && y <= 69) { clickedComponent = 3; } - } else if(mouseY > this.y+5+27 && mouseY < this.y+5+37) { + } else if (mouseY > this.y + 5 + 27 && mouseY < this.y + 5 + 37) { int currentColour = ChromaColour.specialToSimpleRGB(colour); Color c = new Color(currentColour, true); colour = ChromaColour.special(200, c.getAlpha(), currentColour); @@ -314,7 +314,7 @@ public class GuiElementColour extends GuiElement { return false; } } - if(Mouse.isButtonDown(0) && clickedComponent >= 0) { + if (Mouse.isButtonDown(0) && clickedComponent >= 0) { int currentColour = ChromaColour.specialToSimpleRGB(colour); Color c = new Color(currentColour, true); float[] hsv = Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(), null); @@ -322,16 +322,16 @@ public class GuiElementColour extends GuiElement { float xWheel = mouseXF - x - 5; float yWheel = mouseYF - y - 5; - if(clickedComponent == 0) { - float angle = (float) Math.toDegrees(Math.atan((32-xWheel)/(yWheel-32+1E-5))+Math.PI/2); + if (clickedComponent == 0) { + float angle = (float) Math.toDegrees(Math.atan((32 - xWheel) / (yWheel - 32 + 1E-5)) + Math.PI / 2); xWheel = Math.max(0, Math.min(64, xWheel)); yWheel = Math.max(0, Math.min(64, yWheel)); - float radius = (float) Math.sqrt(((xWheel-32)*(xWheel-32)+(yWheel-32)*(yWheel-32))/1024f); - if(yWheel < 32) angle += 180; + float radius = (float) Math.sqrt(((xWheel - 32) * (xWheel - 32) + (yWheel - 32) * (yWheel - 32)) / 1024f); + if (yWheel < 32) angle += 180; this.wheelAngle = angle; - this.wheelRadius = (float)Math.pow(Math.min(1, radius), 1.5f); - int rgb = Color.getHSBColor(angle/360f, wheelRadius, hsv[2]).getRGB(); + this.wheelRadius = (float) Math.pow(Math.min(1, radius), 1.5f); + int rgb = Color.getHSBColor(angle / 360f, wheelRadius, hsv[2]).getRGB(); colour = ChromaColour.special(ChromaColour.getSpeed(colour), c.getAlpha(), rgb); colourChangedCallback.accept(colour); return true; @@ -341,22 +341,22 @@ public class GuiElementColour extends GuiElement { y = Math.max(0, Math.min(64, y)); System.out.println(y); - if(clickedComponent == 1) { - int rgb = Color.getHSBColor(wheelAngle/360, wheelRadius, 1-y/64f).getRGB(); + if (clickedComponent == 1) { + int rgb = Color.getHSBColor(wheelAngle / 360, wheelRadius, 1 - y / 64f).getRGB(); colour = ChromaColour.special(ChromaColour.getSpeed(colour), c.getAlpha(), rgb); colourChangedCallback.accept(colour); return true; } - if(clickedComponent == 2) { + if (clickedComponent == 2) { colour = ChromaColour.special(ChromaColour.getSpeed(colour), - 255-Math.round(y/64f*255), currentColour); + 255 - Math.round(y / 64f * 255), currentColour); colourChangedCallback.accept(colour); return true; } - if(clickedComponent == 3) { - colour = ChromaColour.special(255-Math.round(y/64f*255), c.getAlpha(), currentColour); + if (clickedComponent == 3) { + colour = ChromaColour.special(255 - Math.round(y / 64f * 255), c.getAlpha(), currentColour); colourChangedCallback.accept(colour); } return true; @@ -365,7 +365,7 @@ public class GuiElementColour extends GuiElement { } public boolean keyboardInput() { - if(Keyboard.getEventKeyState() && hexField.getFocus()) { + if (Keyboard.getEventKeyState() && hexField.getFocus()) { if (Keyboard.getEventKey() == Keyboard.KEY_ESCAPE) { hexField.unfocus(); return true; @@ -374,7 +374,7 @@ public class GuiElementColour extends GuiElement { hexField.keyTyped(Keyboard.getEventCharacter(), Keyboard.getEventKey()); - if(hexField.getText().length() > 6) { + if (hexField.getText().length() > 6) { hexField.setText(old); } else { try { @@ -388,13 +388,12 @@ public class GuiElementColour extends GuiElement { Color c = new Color(rgb); float[] hsv = Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(), null); updateAngleAndRadius(hsv); - } catch(Exception e) {}; + } catch (Exception ignored) {} } return true; } return false; } - } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElementTextField.java b/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElementTextField.java index d221b37e..5b52515d 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElementTextField.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/GuiElementTextField.java @@ -40,7 +40,7 @@ public class GuiElementTextField { private int customTextColour = 0xffffffff; private final GuiTextField textField = new GuiTextField(0, Minecraft.getMinecraft().fontRendererObj, - 0 , 0, 0, 0); + 0, 0, 0, 0); private int customBorderColour = -1; @@ -76,11 +76,11 @@ public class GuiElementTextField { public String getTextDisplay() { String textNoColour = getText(); - while(true) { + while (true) { Matcher matcher = PATTERN_CONTROL_CODE.matcher(textNoColour); - if(!matcher.find()) break; + if (!matcher.find()) break; String code = matcher.group(1); - textNoColour = matcher.replaceFirst("\u00B6"+code); + textNoColour = matcher.replaceFirst("\u00B6" + code); } return textNoColour; @@ -91,13 +91,13 @@ public class GuiElementTextField { } public void setText(String text) { - if(textField.getText() == null || !textField.getText().equals(text)) { + if (textField.getText() == null || !textField.getText().equals(text)) { textField.setText(text); } } public void setSize(int searchBarXSize, int searchBarYSize) { - this.searchBarXSize = searchBarXSize; + this.searchBarXSize = searchBarXSize; this.searchBarYSize = searchBarYSize; } @@ -112,34 +112,35 @@ public class GuiElementTextField { public void setFocus(boolean focus) { this.focus = focus; - if(!focus) { + if (!focus) { textField.setCursorPosition(textField.getCursorPosition()); } } + public boolean getFocus() { return focus; } public int getHeight() { ScaledResolution scaledresolution = new ScaledResolution(Minecraft.getMinecraft()); - int paddingUnscaled = searchBarPadding/scaledresolution.getScaleFactor(); + int paddingUnscaled = searchBarPadding / scaledresolution.getScaleFactor(); - int numLines = org.apache.commons.lang3.StringUtils.countMatches(textField.getText(), "\n")+1; - int extraSize = (searchBarYSize-8)/2+8; - int bottomTextBox = searchBarYSize + extraSize*(numLines-1); + int numLines = org.apache.commons.lang3.StringUtils.countMatches(textField.getText(), "\n") + 1; + int extraSize = (searchBarYSize - 8) / 2 + 8; + int bottomTextBox = searchBarYSize + extraSize * (numLines - 1); - return bottomTextBox + paddingUnscaled*2; + return bottomTextBox + paddingUnscaled * 2; } public int getWidth() { ScaledResolution scaledresolution = new ScaledResolution(Minecraft.getMinecraft()); - int paddingUnscaled = searchBarPadding/scaledresolution.getScaleFactor(); + int paddingUnscaled = searchBarPadding / scaledresolution.getScaleFactor(); - return searchBarXSize + paddingUnscaled*2; + return searchBarXSize + paddingUnscaled * 2; } private float getScaleFactor(String str) { - return Math.min(1, (searchBarXSize-2)/(float)Minecraft.getMinecraft().fontRendererObj.getStringWidth(str)); + return Math.min(1, (searchBarXSize - 2) / (float) Minecraft.getMinecraft().fontRendererObj.getStringWidth(str)); } private boolean isScaling() { @@ -152,60 +153,60 @@ public class GuiElementTextField { int xComp = mouseX - x; int yComp = mouseY - y; - int extraSize = (searchBarYSize-8)/2+8; + int extraSize = (searchBarYSize - 8) / 2 + 8; String renderText = prependText + textField.getText(); - int lineNum = Math.round(((yComp - (searchBarYSize-8)/2))/extraSize); + int lineNum = Math.round(((yComp - (searchBarYSize - 8) / 2)) / extraSize); String text = renderText; String textNoColour = renderText; - if((options & COLOUR) != 0) { - while(true) { + if ((options & COLOUR) != 0) { + while (true) { Matcher matcher = PATTERN_CONTROL_CODE.matcher(text); - if(!matcher.find() || matcher.groupCount() < 1) break; + if (!matcher.find() || matcher.groupCount() < 1) break; String code = matcher.group(1); - if(code.isEmpty()) { + if (code.isEmpty()) { text = matcher.replaceFirst("\u00A7r\u00B6"); } else { - text = matcher.replaceFirst("\u00A7"+code+"\u00B6"+code); + text = matcher.replaceFirst("\u00A7" + code + "\u00B6" + code); } } } - while(true) { + while (true) { Matcher matcher = PATTERN_CONTROL_CODE.matcher(textNoColour); - if(!matcher.find() || matcher.groupCount() < 1) break; + if (!matcher.find() || matcher.groupCount() < 1) break; String code = matcher.group(1); - textNoColour = matcher.replaceFirst("\u00B6"+code); + textNoColour = matcher.replaceFirst("\u00B6" + code); } int currentLine = 0; int cursorIndex = 0; - for(; cursorIndex 0) { + if (split.length == numLinesBeforeCursor && split.length > 0) { textBeforeCursorWidth = 0; - lineBefore = split[split.length-1]; + lineBefore = split[split.length - 1]; thisLineBeforeCursor = ""; - } else if(split.length > 1) { - thisLineBeforeCursor = split[split.length-1]; - lineBefore = split[split.length-2]; + } else if (split.length > 1) { + thisLineBeforeCursor = split[split.length - 1]; + lineBefore = split[split.length - 2]; textBeforeCursorWidth = Minecraft.getMinecraft().fontRendererObj.getStringWidth(thisLineBeforeCursor); } else { return; @@ -294,60 +295,60 @@ public class GuiElementTextField { String trimmed = Minecraft.getMinecraft().fontRendererObj .trimStringToWidth(lineBefore, textBeforeCursorWidth); int linePos = strLenNoColor(trimmed); - if(linePos != strLenNoColor(lineBefore)) { + if (linePos != strLenNoColor(lineBefore)) { char after = lineBefore.charAt(linePos); int trimmedWidth = Minecraft.getMinecraft().fontRendererObj.getStringWidth(trimmed); int charWidth = Minecraft.getMinecraft().fontRendererObj.getCharWidth(after); - if(trimmedWidth + charWidth/2 < textBeforeCursorWidth) { + if (trimmedWidth + charWidth / 2 < textBeforeCursorWidth) { linePos++; } } - int newPos = textField.getSelectionEnd()-strLenNoColor(thisLineBeforeCursor) - -strLenNoColor(lineBefore)-1+linePos; + int newPos = textField.getSelectionEnd() - strLenNoColor(thisLineBeforeCursor) + - strLenNoColor(lineBefore) - 1 + linePos; - if(GuiScreen.isShiftKeyDown()) { + if (GuiScreen.isShiftKeyDown()) { textField.setSelectionPos(newPos); } else { textField.setCursorPosition(newPos); } - } else if(keyCode == 208) { //Down + } else if (keyCode == 208) { //Down String textNCBeforeCursor = textNoColour.substring(0, textField.getSelectionEnd()); int colorCodes = org.apache.commons.lang3.StringUtils.countMatches(textNCBeforeCursor, "\u00B6"); - String textBeforeCursor = text.substring(0, textField.getSelectionEnd()+colorCodes*2); + String textBeforeCursor = text.substring(0, textField.getSelectionEnd() + colorCodes * 2); int numLinesBeforeCursor = org.apache.commons.lang3.StringUtils.countMatches(textBeforeCursor, "\n"); String[] split = textBeforeCursor.split("\n"); String thisLineBeforeCursor; int textBeforeCursorWidth; - if(split.length == numLinesBeforeCursor) { + if (split.length == numLinesBeforeCursor) { thisLineBeforeCursor = ""; textBeforeCursorWidth = 0; - } else if(split.length > 0) { - thisLineBeforeCursor = split[split.length-1]; + } else if (split.length > 0) { + thisLineBeforeCursor = split[split.length - 1]; textBeforeCursorWidth = Minecraft.getMinecraft().fontRendererObj.getStringWidth(thisLineBeforeCursor); } else { return; } String[] split2 = textNoColour.split("\n"); - if(split2.length > numLinesBeforeCursor+1) { - String lineAfter = split2[numLinesBeforeCursor+1]; + if (split2.length > numLinesBeforeCursor + 1) { + String lineAfter = split2[numLinesBeforeCursor + 1]; String trimmed = Minecraft.getMinecraft().fontRendererObj .trimStringToWidth(lineAfter, textBeforeCursorWidth); int linePos = strLenNoColor(trimmed); - if(linePos != strLenNoColor(lineAfter)) { + if (linePos != strLenNoColor(lineAfter)) { char after = lineAfter.charAt(linePos); int trimmedWidth = Minecraft.getMinecraft().fontRendererObj.getStringWidth(trimmed); int charWidth = Minecraft.getMinecraft().fontRendererObj.getCharWidth(after); - if(trimmedWidth + charWidth/2 < textBeforeCursorWidth) { + if (trimmedWidth + charWidth / 2 < textBeforeCursorWidth) { linePos++; } } - int newPos = textField.getSelectionEnd()-strLenNoColor(thisLineBeforeCursor) - +strLenNoColor(split2[numLinesBeforeCursor])+1+linePos; + int newPos = textField.getSelectionEnd() - strLenNoColor(thisLineBeforeCursor) + + strLenNoColor(split2[numLinesBeforeCursor]) + 1 + linePos; - if(GuiScreen.isShiftKeyDown()) { + if (GuiScreen.isShiftKeyDown()) { textField.setSelectionPos(newPos); } else { textField.setCursorPosition(newPos); @@ -357,47 +358,47 @@ public class GuiElementTextField { } String old = textField.getText(); - if((options & FORCE_CAPS) != 0) typedChar = Character.toUpperCase(typedChar); - if((options & NO_SPACE) != 0 && typedChar == ' ') return; + if ((options & FORCE_CAPS) != 0) typedChar = Character.toUpperCase(typedChar); + if ((options & NO_SPACE) != 0 && typedChar == ' ') return; - if(typedChar == '\u00B6') { + if (typedChar == '\u00B6') { typedChar = '\u00A7'; } textField.setFocused(true); textField.textboxKeyTyped(typedChar, keyCode); - if((options & COLOUR) != 0) { - if(typedChar == '&') { - int pos = textField.getCursorPosition()-2; - if(pos >= 0 && pos < textField.getText().length()) { - if(textField.getText().charAt(pos) == '&') { + if ((options & COLOUR) != 0) { + if (typedChar == '&') { + int pos = textField.getCursorPosition() - 2; + if (pos >= 0 && pos < textField.getText().length()) { + if (textField.getText().charAt(pos) == '&') { String before = textField.getText().substring(0, pos); String after = ""; - if(pos+2 < textField.getText().length()) { - after = textField.getText().substring(pos+2); + if (pos + 2 < textField.getText().length()) { + after = textField.getText().substring(pos + 2); } textField.setText(before + "\u00A7" + after); - textField.setCursorPosition(pos+1); + textField.setCursorPosition(pos + 1); } } - } else if(typedChar == '*') { - int pos = textField.getCursorPosition()-2; - if(pos >= 0 && pos < textField.getText().length()) { - if(textField.getText().charAt(pos) == '*') { + } else if (typedChar == '*') { + int pos = textField.getCursorPosition() - 2; + if (pos >= 0 && pos < textField.getText().length()) { + if (textField.getText().charAt(pos) == '*') { String before = textField.getText().substring(0, pos); String after = ""; - if(pos+2 < textField.getText().length()) { - after = textField.getText().substring(pos+2); + if (pos + 2 < textField.getText().length()) { + after = textField.getText().substring(pos + 2); } textField.setText(before + "\u272A" + after); - textField.setCursorPosition(pos+1); + textField.setCursorPosition(pos + 1); } } } } - if((options & NUM_ONLY) != 0 && textField.getText().matches("[^0-9.]")) textField.setText(old); + if ((options & NUM_ONLY) != 0 && textField.getText().matches("[^0-9.]")) textField.setText(old); } } @@ -414,21 +415,21 @@ public class GuiElementTextField { GlStateManager.disableLighting(); - /** + /* * Search bar */ - int paddingUnscaled = searchBarPadding/scaledresolution.getScaleFactor(); - if(paddingUnscaled < 1) paddingUnscaled = 1; + int paddingUnscaled = searchBarPadding / scaledresolution.getScaleFactor(); + if (paddingUnscaled < 1) paddingUnscaled = 1; - int numLines = org.apache.commons.lang3.StringUtils.countMatches(renderText, "\n")+1; - int extraSize = (searchBarYSize-8)/2+8; - int bottomTextBox = y + searchBarYSize + extraSize*(numLines-1); + int numLines = org.apache.commons.lang3.StringUtils.countMatches(renderText, "\n") + 1; + int extraSize = (searchBarYSize - 8) / 2 + 8; + int bottomTextBox = y + searchBarYSize + extraSize * (numLines - 1); int borderColour = focus ? Color.GREEN.getRGB() : Color.WHITE.getRGB(); - if(customBorderColour != -1) { + if (customBorderColour != -1) { borderColour = customBorderColour; } - if((options & DISABLE_BG) == 0) { + if ((options & DISABLE_BG) == 0) { //bar background Gui.drawRect(x - paddingUnscaled, y - paddingUnscaled, @@ -443,114 +444,114 @@ public class GuiElementTextField { //bar text String text = renderText; String textNoColor = renderText; - if((options & COLOUR) != 0) { - while(true) { + if ((options & COLOUR) != 0) { + while (true) { Matcher matcher = PATTERN_CONTROL_CODE.matcher(text); - if(!matcher.find() || matcher.groupCount() < 1) break; + if (!matcher.find() || matcher.groupCount() < 1) break; String code = matcher.group(1); - if(code.isEmpty()) { + if (code.isEmpty()) { text = matcher.replaceFirst("\u00A7r\u00B6"); } else { - text = matcher.replaceFirst("\u00A7"+code+"\u00B6"+code); + text = matcher.replaceFirst("\u00A7" + code + "\u00B6" + code); } } } - while(true) { + while (true) { Matcher matcher = PATTERN_CONTROL_CODE.matcher(textNoColor); - if(!matcher.find() || matcher.groupCount() < 1) break; + if (!matcher.find() || matcher.groupCount() < 1) break; String code = matcher.group(1); - textNoColor = matcher.replaceFirst("\u00B6"+code); + textNoColor = matcher.replaceFirst("\u00B6" + code); } int xStartOffset = 5; float scale = 1; String[] texts = text.split("\n"); - for(int yOffI = 0; yOffI < texts.length; yOffI++) { - int yOff = yOffI*extraSize; - - if(isScaling() && Minecraft.getMinecraft().fontRendererObj.getStringWidth(texts[yOffI])>searchBarXSize-10) { - scale = (searchBarXSize-2)/(float)Minecraft.getMinecraft().fontRendererObj.getStringWidth(texts[yOffI]); - if(scale > 1) scale=1; - float newLen = Minecraft.getMinecraft().fontRendererObj.getStringWidth(texts[yOffI])*scale; - xStartOffset = (int)((searchBarXSize-newLen)/2f); - - TextRenderUtils.drawStringCenteredScaledMaxWidth(Utils.chromaStringByColourCode(texts[yOffI]), Minecraft.getMinecraft().fontRendererObj, x+searchBarXSize/2f, - y+searchBarYSize/2f+yOff, false, - searchBarXSize-2, customTextColour); + for (int yOffI = 0; yOffI < texts.length; yOffI++) { + int yOff = yOffI * extraSize; + + if (isScaling() && Minecraft.getMinecraft().fontRendererObj.getStringWidth(texts[yOffI]) > searchBarXSize - 10) { + scale = (searchBarXSize - 2) / (float) Minecraft.getMinecraft().fontRendererObj.getStringWidth(texts[yOffI]); + if (scale > 1) scale = 1; + float newLen = Minecraft.getMinecraft().fontRendererObj.getStringWidth(texts[yOffI]) * scale; + xStartOffset = (int) ((searchBarXSize - newLen) / 2f); + + TextRenderUtils.drawStringCenteredScaledMaxWidth(Utils.chromaStringByColourCode(texts[yOffI]), Minecraft.getMinecraft().fontRendererObj, x + searchBarXSize / 2f, + y + searchBarYSize / 2f + yOff, false, + searchBarXSize - 2, customTextColour); } else { - if((options & SCISSOR_TEXT) != 0) { - GlScissorStack.push(x+5, 0, x+searchBarXSize, scaledresolution.getScaledHeight(), scaledresolution); + if ((options & SCISSOR_TEXT) != 0) { + GlScissorStack.push(x + 5, 0, x + searchBarXSize, scaledresolution.getScaledHeight(), scaledresolution); Minecraft.getMinecraft().fontRendererObj.drawString(Utils.chromaStringByColourCode(texts[yOffI]), x + 5, - y+(searchBarYSize-8)/2+yOff, customTextColour); + y + (searchBarYSize - 8) / 2 + yOff, customTextColour); GlScissorStack.pop(scaledresolution); } else { - String toRender = Minecraft.getMinecraft().fontRendererObj.trimStringToWidth(Utils.chromaStringByColourCode(texts[yOffI]), searchBarXSize-10); + String toRender = Minecraft.getMinecraft().fontRendererObj.trimStringToWidth(Utils.chromaStringByColourCode(texts[yOffI]), searchBarXSize - 10); Minecraft.getMinecraft().fontRendererObj.drawString(toRender, x + 5, - y+(searchBarYSize-8)/2+yOff, customTextColour); + y + (searchBarYSize - 8) / 2 + yOff, customTextColour); } } } - if(focus && System.currentTimeMillis()%1000>500) { - String textNCBeforeCursor = textNoColor.substring(0, textField.getCursorPosition()+prependText.length()); + if (focus && System.currentTimeMillis() % 1000 > 500) { + String textNCBeforeCursor = textNoColor.substring(0, textField.getCursorPosition() + prependText.length()); int colorCodes = org.apache.commons.lang3.StringUtils.countMatches(textNCBeforeCursor, "\u00B6"); - String textBeforeCursor = text.substring(0, Math.min(text.length(), textField.getCursorPosition()+prependText.length()+(((options & COLOUR) != 0) ? colorCodes*2 : 0))); + String textBeforeCursor = text.substring(0, Math.min(text.length(), textField.getCursorPosition() + prependText.length() + (((options & COLOUR) != 0) ? colorCodes * 2 : 0))); int numLinesBeforeCursor = org.apache.commons.lang3.StringUtils.countMatches(textBeforeCursor, "\n"); - int yOff = numLinesBeforeCursor*extraSize; + int yOff = numLinesBeforeCursor * extraSize; String[] split = textBeforeCursor.split("\n"); int textBeforeCursorWidth; - if(split.length <= numLinesBeforeCursor || split.length == 0) { + if (split.length <= numLinesBeforeCursor || split.length == 0) { textBeforeCursorWidth = 0; } else { - textBeforeCursorWidth = (int)(Minecraft.getMinecraft().fontRendererObj.getStringWidth(split[split.length-1])*scale); + textBeforeCursorWidth = (int) (Minecraft.getMinecraft().fontRendererObj.getStringWidth(split[split.length - 1]) * scale); } Gui.drawRect(x + xStartOffset + textBeforeCursorWidth, - y+(searchBarYSize-8)/2-1 + yOff, - x + xStartOffset + textBeforeCursorWidth+1, - y+(searchBarYSize-8)/2+9 + yOff, Color.WHITE.getRGB()); + y + (searchBarYSize - 8) / 2 - 1 + yOff, + x + xStartOffset + textBeforeCursorWidth + 1, + y + (searchBarYSize - 8) / 2 + 9 + yOff, Color.WHITE.getRGB()); } String selectedText = textField.getSelectedText(); - if(!selectedText.isEmpty()) { - int leftIndex = Math.min(textField.getCursorPosition()+prependText.length(), textField.getSelectionEnd()+prependText.length()); - int rightIndex = Math.max(textField.getCursorPosition()+prependText.length(), textField.getSelectionEnd()+prependText.length()); + if (!selectedText.isEmpty()) { + int leftIndex = Math.min(textField.getCursorPosition() + prependText.length(), textField.getSelectionEnd() + prependText.length()); + int rightIndex = Math.max(textField.getCursorPosition() + prependText.length(), textField.getSelectionEnd() + prependText.length()); float texX = 0; int texY = 0; boolean sectionSignPrev = false; boolean ignoreNext = false; boolean bold = false; - for(int i=0; i= leftIndex && i < rightIndex) { - Gui.drawRect(x + xStartOffset + (int)texX, - y+(searchBarYSize-8)/2-1 + texY, - x + xStartOffset + (int)texX + 3, - y+(searchBarYSize-8)/2+9 + texY, Color.LIGHT_GRAY.getRGB()); + if (c == '\n') { + if (i >= leftIndex && i < rightIndex) { + Gui.drawRect(x + xStartOffset + (int) texX, + y + (searchBarYSize - 8) / 2 - 1 + texY, + x + xStartOffset + (int) texX + 3, + y + (searchBarYSize - 8) / 2 + 9 + texY, Color.LIGHT_GRAY.getRGB()); } texX = 0; @@ -559,24 +560,24 @@ public class GuiElementTextField { } int len = Minecraft.getMinecraft().fontRendererObj.getStringWidth(String.valueOf(c)); - if(bold) len++; - if(i >= leftIndex && i < rightIndex) { - Gui.drawRect(x + xStartOffset + (int)texX, - y+(searchBarYSize-8)/2-1 + texY, - x + xStartOffset + (int)(texX + len*scale), - y+(searchBarYSize-8)/2+9 + texY, Color.LIGHT_GRAY.getRGB()); + if (bold) len++; + if (i >= leftIndex && i < rightIndex) { + Gui.drawRect(x + xStartOffset + (int) texX, + y + (searchBarYSize - 8) / 2 - 1 + texY, + x + xStartOffset + (int) (texX + len * scale), + y + (searchBarYSize - 8) / 2 + 9 + texY, Color.LIGHT_GRAY.getRGB()); TextRenderUtils.drawStringScaled(String.valueOf(c), Minecraft.getMinecraft().fontRendererObj, x + xStartOffset + texX, - y+searchBarYSize/2f-scale*8/2f + texY, false, Color.BLACK.getRGB(), scale); - if(bold) { + y + searchBarYSize / 2f - scale * 8 / 2f + texY, false, Color.BLACK.getRGB(), scale); + if (bold) { TextRenderUtils.drawStringScaled(String.valueOf(c), Minecraft.getMinecraft().fontRendererObj, x + xStartOffset + texX + 1, - y+searchBarYSize/2f-scale*8/2f + texY, false, Color.BLACK.getRGB(), scale); + y + searchBarYSize / 2f - scale * 8 / 2f + texY, false, Color.BLACK.getRGB(), scale); } } - texX += len*scale; + texX += len * scale; } } } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/Config.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/Config.java index 8be828bd..f5d8488c 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/Config.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/Config.java @@ -2,7 +2,6 @@ package io.github.moulberry.notenoughupdates.core.config; public class Config { - public void executeRunnable(int runnableId) { - } + public void executeRunnable(int runnableId) {} } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/GuiPositionEditor.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/GuiPositionEditor.java index a48f3f1a..1a69789b 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/GuiPositionEditor.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/GuiPositionEditor.java @@ -28,15 +28,15 @@ public class GuiPositionEditor extends GuiScreen { int centerWidth = 176; int centerHeight = 166; - float centerWF = centerWidth/2f / (float)width; - float centerHF = centerHeight/2f / (float)height; + float centerWF = centerWidth / 2f / (float) width; + float centerHF = centerHeight / 2f / (float) height; float left = 0; float top = 0; float right = 0; float bottom = 0; - switch(position.getAnchorX()) { + switch (position.getAnchorX()) { case MIN: { left = 0; right = 0.5f - centerWF; @@ -53,7 +53,7 @@ public class GuiPositionEditor extends GuiScreen { break; } } - switch(position.getAnchorY()) { + switch (position.getAnchorY()) { case MIN: { top = 0; bottom = 0.5f - centerHF; @@ -71,8 +71,8 @@ public class GuiPositionEditor extends GuiScreen { } } - Gui.drawRect((int)(left*width), (int)(top*height), (int)(right*width), (int)(bottom*height), 0x40404040); - Gui.drawRect(x, y, x+200, y+100, 0x80404040); + Gui.drawRect((int) (left * width), (int) (top * height), (int) (right * width), (int) (bottom * height), 0x40404040); + Gui.drawRect(x, y, x + 200, y + 100, 0x80404040); } @Override @@ -81,8 +81,8 @@ public class GuiPositionEditor extends GuiScreen { int x = position.resolveX(scaledResolution, 200); int y = position.resolveY(scaledResolution, 100); - if(mouseX > x && mouseX < x+200 && - mouseY > y && mouseY < y+100) { + if (mouseX > x && mouseX < x + 200 && + mouseY > y && mouseY < y + 100) { clickedX = mouseX; clickedY = mouseY; } else { @@ -99,7 +99,7 @@ public class GuiPositionEditor extends GuiScreen { @Override protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) { - if(clickedX >= 0 && clickedY >= 0) { + if (clickedX >= 0 && clickedY >= 0) { int deltaX = mouseX - clickedX; int deltaY = mouseY - clickedY; diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/KeybindHelper.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/KeybindHelper.java index 7ebacac1..b1013047 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/KeybindHelper.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/KeybindHelper.java @@ -1,23 +1,22 @@ package io.github.moulberry.notenoughupdates.core.config; -import io.github.moulberry.notenoughupdates.NotEnoughUpdates; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; public class KeybindHelper { public static String getKeyName(int keyCode) { - if(keyCode == 0) { + if (keyCode == 0) { return "NONE"; - } else if(keyCode < 0) { - return "Button "+(keyCode+101); + } else if (keyCode < 0) { + return "Button " + (keyCode + 101); } else { String keyName = Keyboard.getKeyName(keyCode); - if(keyName == null) { + if (keyName == null) { keyName = "???"; - } else if(keyName.equalsIgnoreCase("LMENU")) { + } else if (keyName.equalsIgnoreCase("LMENU")) { keyName = "LALT"; - } else if(keyName.equalsIgnoreCase("RMENU")) { + } else if (keyName.equalsIgnoreCase("RMENU")) { keyName = "RALT"; } return keyName; @@ -29,20 +28,20 @@ public class KeybindHelper { } public static boolean isKeyDown(int keyCode) { - if(!isKeyValid(keyCode)) { + if (!isKeyValid(keyCode)) { return false; - } else if(keyCode < 0) { - return Mouse.isButtonDown(keyCode+100); + } else if (keyCode < 0) { + return Mouse.isButtonDown(keyCode + 100); } else { return Keyboard.isKeyDown(keyCode); } } public static boolean isKeyPressed(int keyCode) { - if(!isKeyValid(keyCode)) { + if (!isKeyValid(keyCode)) { return false; - } else if(keyCode < 0) { - return Mouse.getEventButtonState() && Mouse.getEventButton() == keyCode+100; + } else if (keyCode < 0) { + return Mouse.getEventButtonState() && Mouse.getEventButton() == keyCode + 100; } else { return Keyboard.getEventKeyState() && Keyboard.getEventKey() == keyCode; } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/Position.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/Position.java index 66df27c6..270570f8 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/Position.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/Position.java @@ -57,17 +57,17 @@ public class Position { public int getAbsX(ScaledResolution scaledResolution, int objWidth) { int width = scaledResolution.getScaledWidth(); - if(centerX) { - return width/2 + x; + if (centerX) { + return width / 2 + x; } int ret = x; - if(x < 0) { + if (x < 0) { ret = width + x - objWidth; } - if(ret < 0) ret = 0; - if(ret > width - objWidth) ret = width - objWidth; + if (ret < 0) ret = 0; + if (ret > width - objWidth) ret = width - objWidth; return ret; } @@ -75,17 +75,17 @@ public class Position { public int getAbsY(ScaledResolution scaledResolution, int objHeight) { int height = scaledResolution.getScaledHeight(); - if(centerY) { - return height/2 + y; + if (centerY) { + return height / 2 + y; } int ret = y; - if(y < 0) { + if (y < 0) { ret = height + y - objHeight; } - if(ret < 0) ret = 0; - if(ret > height - objHeight) ret = height - objHeight; + if (ret < 0) ret = 0; + if (ret > height - objHeight) ret = height - objHeight; return ret; } @@ -95,45 +95,45 @@ public class Position { boolean wasPositiveX = this.x >= 0; this.x += deltaX; - if(centerX) { - if(wasPositiveX) { - if(this.x > screenWidth/2-objWidth/2) { - deltaX += screenWidth/2-objWidth/2-this.x; - this.x = screenWidth/2-objWidth/2; + if (centerX) { + if (wasPositiveX) { + if (this.x > screenWidth / 2 - objWidth / 2) { + deltaX += screenWidth / 2 - objWidth / 2 - this.x; + this.x = screenWidth / 2 - objWidth / 2; } } else { - if(this.x < -screenWidth/2+objWidth/2) { - deltaX += -screenWidth/2+objWidth/2-this.x; - this.x = -screenWidth/2+objWidth/2; + if (this.x < -screenWidth / 2 + objWidth / 2) { + deltaX += -screenWidth / 2 + objWidth / 2 - this.x; + this.x = -screenWidth / 2 + objWidth / 2; } } return deltaX; } - if(wasPositiveX) { - if(this.x < EDGE_OFFSET) { - deltaX += EDGE_OFFSET-this.x; + if (wasPositiveX) { + if (this.x < EDGE_OFFSET) { + deltaX += EDGE_OFFSET - this.x; this.x = EDGE_OFFSET; } - if(this.x > screenWidth-EDGE_OFFSET) { - deltaX += screenWidth-EDGE_OFFSET-this.x; - this.x = screenWidth-EDGE_OFFSET; + if (this.x > screenWidth - EDGE_OFFSET) { + deltaX += screenWidth - EDGE_OFFSET - this.x; + this.x = screenWidth - EDGE_OFFSET; } } else { - if(this.x+1 > -EDGE_OFFSET) { - deltaX += -EDGE_OFFSET-1-this.x; - this.x = -EDGE_OFFSET-1; + if (this.x + 1 > -EDGE_OFFSET) { + deltaX += -EDGE_OFFSET - 1 - this.x; + this.x = -EDGE_OFFSET - 1; } - if(this.x+screenWidth < EDGE_OFFSET) { - deltaX += EDGE_OFFSET-screenWidth-this.x; - this.x = EDGE_OFFSET-screenWidth; + if (this.x + screenWidth < EDGE_OFFSET) { + deltaX += EDGE_OFFSET - screenWidth - this.x; + this.x = EDGE_OFFSET - screenWidth; } } - if(this.x >= 0 && this.x+objWidth/2 > screenWidth/2) { + if (this.x >= 0 && this.x + objWidth / 2 > screenWidth / 2) { this.x -= screenWidth - objWidth; } - if(this.x < 0 && this.x+objWidth/2 <= -screenWidth/2) { + if (this.x < 0 && this.x + objWidth / 2 <= -screenWidth / 2) { this.x += screenWidth - objWidth; } return deltaX; @@ -144,45 +144,45 @@ public class Position { boolean wasPositiveY = this.y >= 0; this.y += deltaY; - if(centerY) { - if(wasPositiveY) { - if(this.y > screenHeight/2-objHeight/2) { - deltaY += screenHeight/2-objHeight/2-this.y; - this.y = screenHeight/2-objHeight/2; + if (centerY) { + if (wasPositiveY) { + if (this.y > screenHeight / 2 - objHeight / 2) { + deltaY += screenHeight / 2 - objHeight / 2 - this.y; + this.y = screenHeight / 2 - objHeight / 2; } } else { - if(this.y < -screenHeight/2+objHeight/2) { - deltaY += -screenHeight/2+objHeight/2-this.y; - this.y = -screenHeight/2+objHeight/2; + if (this.y < -screenHeight / 2 + objHeight / 2) { + deltaY += -screenHeight / 2 + objHeight / 2 - this.y; + this.y = -screenHeight / 2 + objHeight / 2; } } return deltaY; } - if(wasPositiveY) { - if(this.y < EDGE_OFFSET) { - deltaY += EDGE_OFFSET-this.y; + if (wasPositiveY) { + if (this.y < EDGE_OFFSET) { + deltaY += EDGE_OFFSET - this.y; this.y = EDGE_OFFSET; } - if(this.y > screenHeight-EDGE_OFFSET) { - deltaY += screenHeight-EDGE_OFFSET-this.y; - this.y = screenHeight-EDGE_OFFSET; + if (this.y > screenHeight - EDGE_OFFSET) { + deltaY += screenHeight - EDGE_OFFSET - this.y; + this.y = screenHeight - EDGE_OFFSET; } } else { - if(this.y+1 > -EDGE_OFFSET) { - deltaY += -EDGE_OFFSET-1-this.y; - this.y = -EDGE_OFFSET-1; + if (this.y + 1 > -EDGE_OFFSET) { + deltaY += -EDGE_OFFSET - 1 - this.y; + this.y = -EDGE_OFFSET - 1; } - if(this.y+screenHeight < EDGE_OFFSET) { - deltaY += EDGE_OFFSET-screenHeight-this.y; - this.y = EDGE_OFFSET-screenHeight; + if (this.y + screenHeight < EDGE_OFFSET) { + deltaY += EDGE_OFFSET - screenHeight - this.y; + this.y = EDGE_OFFSET - screenHeight; } } - if(this.y >= 0 && this.y-objHeight/2 > screenHeight/2) { + if (this.y >= 0 && this.y - objHeight / 2 > screenHeight / 2) { this.y -= screenHeight - objHeight; } - if(this.y < 0 && this.y-objHeight/2 <= -screenHeight/2) { + if (this.y < 0 && this.y - objHeight / 2 <= -screenHeight / 2) { this.y += screenHeight - objHeight; } return deltaY; diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/PositionNew.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/PositionNew.java index 842df73d..a0029dd8 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/PositionNew.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/PositionNew.java @@ -64,9 +64,9 @@ public class PositionNew { public int moveX(ScaledResolution scaledResolution, int deltaX, int sizeX) { int originalX = resolveX(scaledResolution, sizeX); - AtomicInteger atomicInteger = new AtomicInteger(x+deltaX); + AtomicInteger atomicInteger = new AtomicInteger(x + deltaX); AtomicReference atomicReference = new AtomicReference<>(anchorX); - move(atomicInteger, atomicReference, anchorY, (int)Math.ceil(sizeX*scaleX), scaledResolution.getScaledWidth(), 176); + move(atomicInteger, atomicReference, anchorY, (int) Math.ceil(sizeX * scaleX), scaledResolution.getScaledWidth(), 176); x = atomicInteger.get(); anchorX = atomicReference.get(); return resolveX(scaledResolution, sizeX) - originalX; @@ -74,25 +74,25 @@ public class PositionNew { public int moveY(ScaledResolution scaledResolution, int deltaY, int sizeY) { int originalY = resolveY(scaledResolution, sizeY); - AtomicInteger atomicInteger = new AtomicInteger(y+deltaY); + AtomicInteger atomicInteger = new AtomicInteger(y + deltaY); AtomicReference atomicReference = new AtomicReference<>(anchorY); - move(atomicInteger, atomicReference, anchorY, (int)Math.ceil(sizeY*scaleY), scaledResolution.getScaledHeight(), 166); + move(atomicInteger, atomicReference, anchorY, (int) Math.ceil(sizeY * scaleY), scaledResolution.getScaledHeight(), 166); y = atomicInteger.get(); anchorY = atomicReference.get(); return resolveY(scaledResolution, sizeY) - originalY; } private void move(AtomicInteger coord, AtomicReference anchor, Anchor oppositeAnchor, int elementSize, int screenSize, int guiSize) { - int centerCoord = resolve(coord.get(), anchor.get(), elementSize, screenSize, guiSize) + elementSize/2; + int centerCoord = resolve(coord.get(), anchor.get(), elementSize, screenSize, guiSize) + elementSize / 2; - if(centerCoord < screenSize/2-guiSize/2) { - if(pinned && centerCoord > screenSize/4-guiSize/4 && oppositeAnchor == Anchor.MID) { + if (centerCoord < screenSize / 2 - guiSize / 2) { + if (pinned && centerCoord > screenSize / 4 - guiSize / 4 && oppositeAnchor == Anchor.MID) { anchor.set(Anchor.GUI_MIN); } else { anchor.set(Anchor.MIN); } - } else if(centerCoord > screenSize/2+guiSize/2) { - if(pinned && centerCoord < screenSize-(screenSize/4-guiSize/4) && oppositeAnchor == Anchor.MID) { + } else if (centerCoord > screenSize / 2 + guiSize / 2) { + if (pinned && centerCoord < screenSize - (screenSize / 4 - guiSize / 4) && oppositeAnchor == Anchor.MID) { anchor.set(Anchor.GUI_MAX); } else { anchor.set(Anchor.MAX); @@ -101,33 +101,33 @@ public class PositionNew { anchor.set(Anchor.MID); } - if(centerCoord - elementSize/2 < 0) centerCoord = elementSize/2; - if(centerCoord + elementSize/2 > screenSize) centerCoord = screenSize - elementSize/2; + if (centerCoord - elementSize / 2 < 0) centerCoord = elementSize / 2; + if (centerCoord + elementSize / 2 > screenSize) centerCoord = screenSize - elementSize / 2; Anchor newAnchor = anchor.get(); - coord.set(Math.round(centerCoord - (elementSize*(newAnchor.elementMult+0.5f)) - screenSize*newAnchor.screenMult - guiSize*newAnchor.guiMult)); + coord.set(Math.round(centerCoord - (elementSize * (newAnchor.elementMult + 0.5f)) - screenSize * newAnchor.screenMult - guiSize * newAnchor.guiMult)); } public int resolveX(ScaledResolution scaledResolution, int sizeX) { - return resolve(x, anchorX, (int)Math.ceil(sizeX*scaleX), scaledResolution.getScaledWidth(), 176); + return resolve(x, anchorX, (int) Math.ceil(sizeX * scaleX), scaledResolution.getScaledWidth(), 176); } public int resolveY(ScaledResolution scaledResolution, int sizeY) { - return resolve(y, anchorY, (int)Math.ceil(sizeY*scaleY), scaledResolution.getScaledHeight(), 166); + return resolve(y, anchorY, (int) Math.ceil(sizeY * scaleY), scaledResolution.getScaledHeight(), 166); } private int resolve(int coord, Anchor anchor, int elementSize, int screenSize, int guiSize) { - return Math.round(screenSize*anchor.screenMult + elementSize*anchor.elementMult + guiSize*anchor.guiMult + coord); + return Math.round(screenSize * anchor.screenMult + elementSize * anchor.elementMult + guiSize * anchor.guiMult + coord); } public void setScaleX(float scaleX) { - if(allowResize) { + if (allowResize) { this.scaleX = scaleX; } } public void setScaleY(float scaleY) { - if(allowResize) { + if (allowResize) { this.scaleY = scaleY; } } @@ -141,7 +141,7 @@ public class PositionNew { } public void setPinned(boolean pinned) { - if(allowPinToggle) { + if (allowPinToggle) { this.pinned = pinned; } } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/Category.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/Category.java index 6a91cae5..2611b466 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/Category.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/Category.java @@ -10,6 +10,7 @@ import java.lang.annotation.Target; public @interface Category { String name(); + String desc(); } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorButton.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorButton.java index 5fe7fcb4..be8363d5 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorButton.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorButton.java @@ -10,6 +10,7 @@ import java.lang.annotation.Target; public @interface ConfigEditorButton { int runnableId(); + String buttonText() default ""; } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorColour.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorColour.java index d1dd5808..e7033f69 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorColour.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorColour.java @@ -1,6 +1,5 @@ package io.github.moulberry.notenoughupdates.core.config.annotations; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorDropdown.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorDropdown.java index d9d2235b..e878d657 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorDropdown.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorDropdown.java @@ -1,6 +1,5 @@ package io.github.moulberry.notenoughupdates.core.config.annotations; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -11,6 +10,7 @@ import java.lang.annotation.Target; public @interface ConfigEditorDropdown { String[] values(); + int initialIndex() default 0; } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorSlider.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorSlider.java index d671f65c..4a6fb5be 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorSlider.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorSlider.java @@ -1,6 +1,5 @@ package io.github.moulberry.notenoughupdates.core.config.annotations; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -11,6 +10,7 @@ import java.lang.annotation.Target; public @interface ConfigEditorSlider { float minValue(); + float maxValue(); float minStep(); diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorText.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorText.java index 9227cf50..556bbb1e 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorText.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigEditorText.java @@ -1,6 +1,5 @@ package io.github.moulberry.notenoughupdates.core.config.annotations; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigOption.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigOption.java index 63c3366a..77738abf 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigOption.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/annotations/ConfigOption.java @@ -1,6 +1,5 @@ package io.github.moulberry.notenoughupdates.core.config.annotations; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -11,7 +10,9 @@ import java.lang.annotation.Target; public @interface ConfigOption { String name(); + String desc(); + int subcategoryId() default -1; } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditor.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditor.java index e28c5a32..3ccb3841 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditor.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditor.java @@ -22,27 +22,27 @@ public abstract class GuiOptionEditor { FontRenderer fr = Minecraft.getMinecraft().fontRendererObj; RenderUtils.drawFloatingRectDark(x, y, width, height, true); TextRenderUtils.drawStringCenteredScaledMaxWidth(option.name, - fr, x+width/6, y+13, true, width/3-10, 0xc0c0c0); + fr, x + width / 6, y + 13, true, width / 3 - 10, 0xc0c0c0); int maxLines = 5; float scale = 1; - int lineCount = fr.listFormattedStringToWidth(option.desc, width*2/3-10).size(); + int lineCount = fr.listFormattedStringToWidth(option.desc, width * 2 / 3 - 10).size(); - if(lineCount <= 0) return; + if (lineCount <= 0) return; float paraHeight = 9 * lineCount - 1; - while(paraHeight >= HEIGHT-10) { - scale -= 1/8f; - lineCount = fr.listFormattedStringToWidth(option.desc, (int)(width*2/3/scale-10)).size(); - paraHeight = (int)(9*scale * lineCount - 1*scale); + while (paraHeight >= HEIGHT - 10) { + scale -= 1 / 8f; + lineCount = fr.listFormattedStringToWidth(option.desc, (int) (width * 2 / 3 / scale - 10)).size(); + paraHeight = (int) (9 * scale * lineCount - 1 * scale); } GlStateManager.pushMatrix(); - GlStateManager.translate(x+5+width/3f, y+HEIGHT/2f-paraHeight/2, 0); + GlStateManager.translate(x + 5 + width / 3f, y + HEIGHT / 2f - paraHeight / 2, 0); GlStateManager.scale(scale, scale, 1); - fr.drawSplitString(option.desc, 0, 0, (int)(width*2/3/scale-10), 0xc0c0c0); + fr.drawSplitString(option.desc, 0, 0, (int) (width * 2 / 3 / scale - 10), 0xc0c0c0); GlStateManager.popMatrix(); } @@ -52,11 +52,13 @@ public abstract class GuiOptionEditor { } public abstract boolean mouseInput(int x, int y, int width, int mouseX, int mouseY); + public abstract boolean keyboardInput(); public boolean mouseInputOverlay(int x, int y, int width, int mouseX, int mouseY) { return false; } - public void renderOverlay(int x, int y, int width) {}; + + public void renderOverlay(int x, int y, int width) {} } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorAccordion.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorAccordion.java index 79667ff8..7406f2c3 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorAccordion.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorAccordion.java @@ -1,11 +1,9 @@ package io.github.moulberry.notenoughupdates.core.config.gui; -import io.github.moulberry.notenoughupdates.core.config.Config; import io.github.moulberry.notenoughupdates.core.config.struct.ConfigProcessor; import io.github.moulberry.notenoughupdates.core.util.render.RenderUtils; import io.github.moulberry.notenoughupdates.core.util.render.TextRenderUtils; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Gui; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; @@ -13,11 +11,9 @@ import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; -import static io.github.moulberry.notenoughupdates.util.GuiTextures.button_tex; - public class GuiOptionEditorAccordion extends GuiOptionEditor { - private int accordionId; + private final int accordionId; private boolean accordionToggled; public GuiOptionEditorAccordion(ConfigProcessor.ProcessedOption option, int accordionId) { @@ -51,27 +47,27 @@ public class GuiOptionEditorAccordion extends GuiOptionEditor { GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); GlStateManager.color(1, 1, 1, 1); worldrenderer.begin(GL11.GL_TRIANGLES, DefaultVertexFormats.POSITION); - if(accordionToggled) { - worldrenderer.pos((double)x+6, (double)y+6, 0.0D).endVertex(); - worldrenderer.pos((double)x+9.75f, (double)y+13.5f, 0.0D).endVertex(); - worldrenderer.pos((double)x+13.5f, (double)y+6, 0.0D).endVertex(); + if (accordionToggled) { + worldrenderer.pos((double) x + 6, (double) y + 6, 0.0D).endVertex(); + worldrenderer.pos((double) x + 9.75f, (double) y + 13.5f, 0.0D).endVertex(); + worldrenderer.pos((double) x + 13.5f, (double) y + 6, 0.0D).endVertex(); } else { - worldrenderer.pos((double)x+6, (double)y+13.5f, 0.0D).endVertex(); - worldrenderer.pos((double)x+13.5f, (double)y+9.75f, 0.0D).endVertex(); - worldrenderer.pos((double)x+6, (double)y+6, 0.0D).endVertex(); + worldrenderer.pos((double) x + 6, (double) y + 13.5f, 0.0D).endVertex(); + worldrenderer.pos((double) x + 13.5f, (double) y + 9.75f, 0.0D).endVertex(); + worldrenderer.pos((double) x + 6, (double) y + 6, 0.0D).endVertex(); } tessellator.draw(); GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); TextRenderUtils.drawStringScaledMaxWidth(option.name, Minecraft.getMinecraft().fontRendererObj, - x+18, y+6, false, width-10, 0xc0c0c0); + x + 18, y + 6, false, width - 10, 0xc0c0c0); } @Override public boolean mouseInput(int x, int y, int width, int mouseX, int mouseY) { - if(Mouse.getEventButtonState() && mouseX > x && mouseX < x+ width && - mouseY > y && mouseY < y+getHeight()) { + if (Mouse.getEventButtonState() && mouseX > x && mouseX < x + width && + mouseY > y && mouseY < y + getHeight()) { accordionToggled = !accordionToggled; return true; } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorBoolean.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorBoolean.java index ba2c9be9..8c8c32b6 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorBoolean.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorBoolean.java @@ -10,7 +10,7 @@ public class GuiOptionEditorBoolean extends GuiOptionEditor { public GuiOptionEditorBoolean(ConfigProcessor.ProcessedOption option) { super(option); - bool = new GuiElementBoolean(0, 0, (boolean)option.get(), 10, option::set); + bool = new GuiElementBoolean(0, 0, (boolean) option.get(), 10, option::set); } @Override @@ -18,16 +18,16 @@ public class GuiOptionEditorBoolean extends GuiOptionEditor { super.render(x, y, width); int height = getHeight(); - bool.x = x+width/6-24; - bool.y = y+height-7-14; + bool.x = x + width / 6 - 24; + bool.y = y + height - 7 - 14; bool.render(); } @Override public boolean mouseInput(int x, int y, int width, int mouseX, int mouseY) { int height = getHeight(); - bool.x = x+width/6-24; - bool.y = y+height-7-14; + bool.x = x + width / 6 - 24; + bool.y = y + height - 7 - 14; return bool.mouseInput(mouseX, mouseY); } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorButton.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorButton.java index 03a01ef2..82d965e3 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorButton.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorButton.java @@ -1,23 +1,20 @@ package io.github.moulberry.notenoughupdates.core.config.gui; -import io.github.moulberry.notenoughupdates.core.ChromaColour; import io.github.moulberry.notenoughupdates.core.config.Config; import io.github.moulberry.notenoughupdates.core.config.struct.ConfigProcessor; import io.github.moulberry.notenoughupdates.core.util.render.RenderUtils; import io.github.moulberry.notenoughupdates.core.util.render.TextRenderUtils; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; -import net.minecraftforge.client.ClientCommandHandler; import org.lwjgl.input.Mouse; import static io.github.moulberry.notenoughupdates.util.GuiTextures.button_tex; -import static io.github.moulberry.notenoughupdates.util.GuiTextures.button_white; public class GuiOptionEditorButton extends GuiOptionEditor { - private int runnableId; + private final int runnableId; private String buttonText; - private Config config; + private final Config config; public GuiOptionEditorButton(ConfigProcessor.ProcessedOption option, int runnableId, String buttonText, Config config) { super(option); @@ -25,7 +22,7 @@ public class GuiOptionEditorButton extends GuiOptionEditor { this.config = config; this.buttonText = buttonText; - if(this.buttonText != null && this.buttonText.isEmpty()) this.buttonText = null; + if (this.buttonText != null && this.buttonText.isEmpty()) this.buttonText = null; } @Override @@ -36,21 +33,21 @@ public class GuiOptionEditorButton extends GuiOptionEditor { GlStateManager.color(1, 1, 1, 1); Minecraft.getMinecraft().getTextureManager().bindTexture(button_tex); - RenderUtils.drawTexturedRect(x+width/6-24, y+height-7-14, 48, 16); + RenderUtils.drawTexturedRect(x + width / 6 - 24, y + height - 7 - 14, 48, 16); - if(buttonText != null) { + if (buttonText != null) { TextRenderUtils.drawStringCenteredScaledMaxWidth(buttonText, Minecraft.getMinecraft().fontRendererObj, - x+width/6, y+height-7-6, + x + width / 6, y + height - 7 - 6, false, 44, 0xFF303030); } } @Override public boolean mouseInput(int x, int y, int width, int mouseX, int mouseY) { - if(Mouse.getEventButtonState()) { + if (Mouse.getEventButtonState()) { int height = getHeight(); - if(mouseX > x+width/6-24 && mouseX < x+width/6+24 && - mouseY > y+height-7-14 && mouseY < y+height-7+2) { + if (mouseX > x + width / 6 - 24 && mouseX < x + width / 6 + 24 && + mouseY > y + height - 7 - 14 && mouseY < y + height - 7 + 2) { config.executeRunnable(runnableId); return true; } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorColour.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorColour.java index d9e8f5a9..4cd74e79 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorColour.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorColour.java @@ -1,17 +1,14 @@ package io.github.moulberry.notenoughupdates.core.config.gui; import io.github.moulberry.notenoughupdates.core.ChromaColour; -import io.github.moulberry.notenoughupdates.core.GlScissorStack; -import io.github.moulberry.notenoughupdates.core.GuiElementBoolean; import io.github.moulberry.notenoughupdates.core.GuiElementColour; import io.github.moulberry.notenoughupdates.core.config.struct.ConfigProcessor; import io.github.moulberry.notenoughupdates.core.util.render.RenderUtils; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import org.lwjgl.input.Mouse; -import org.lwjgl.opengl.GL11; -import static io.github.moulberry.notenoughupdates.util.GuiTextures.*; +import static io.github.moulberry.notenoughupdates.util.GuiTextures.button_white; public class GuiOptionEditorColour extends GuiOptionEditor { @@ -21,7 +18,7 @@ public class GuiOptionEditorColour extends GuiOptionEditor { public GuiOptionEditorColour(ConfigProcessor.ProcessedOption option) { super(option); - this.chromaColour = (String)option.get(); + this.chromaColour = (String) option.get(); } @Override @@ -33,33 +30,30 @@ public class GuiOptionEditorColour extends GuiOptionEditor { int r = (argb >> 16) & 0xFF; int g = (argb >> 8) & 0xFF; int b = argb & 0xFF; - GlStateManager.color(r/255f, g/255f, b/255f, 1); + GlStateManager.color(r / 255f, g / 255f, b / 255f, 1); Minecraft.getMinecraft().getTextureManager().bindTexture(button_white); - RenderUtils.drawTexturedRect(x+width/6-24, y+height-7-14, 48, 16); + RenderUtils.drawTexturedRect(x + width / 6 - 24, y + height - 7 - 14, 48, 16); } @Override public void renderOverlay(int x, int y, int width) { - if(colourElement != null) { + if (colourElement != null) { colourElement.render(); } } @Override public boolean mouseInputOverlay(int x, int y, int width, int mouseX, int mouseY) { - if(colourElement != null && colourElement.mouseInput(mouseX, mouseY)) { - return true; - } - return false; + return colourElement != null && colourElement.mouseInput(mouseX, mouseY); } @Override public boolean mouseInput(int x, int y, int width, int mouseX, int mouseY) { int height = getHeight(); - if(Mouse.getEventButtonState() && Mouse.getEventButton() == 0 && - mouseX > x+width/6-24 && mouseX < x+width/6+24 && - mouseY > y+height-7-14 && mouseY < y+height-7+2) { + if (Mouse.getEventButtonState() && Mouse.getEventButton() == 0 && + mouseX > x + width / 6 - 24 && mouseX < x + width / 6 + 24 && + mouseY > y + height - 7 - 14 && mouseY < y + height - 7 + 2) { colourElement = new GuiElementColour(mouseX, mouseY, (String) option.get(), (val) -> { option.set(val); chromaColour = val; @@ -71,11 +65,7 @@ public class GuiOptionEditorColour extends GuiOptionEditor { @Override public boolean keyboardInput() { - if(colourElement != null && colourElement.keyboardInput()) { - return true; - } - - return false; + return colourElement != null && colourElement.keyboardInput(); } } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorDraggableList.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorDraggableList.java index 03c5bc6c..c91f2b6a 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorDraggableList.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorDraggableList.java @@ -1,6 +1,5 @@ package io.github.moulberry.notenoughupdates.core.config.gui; -import io.github.moulberry.notenoughupdates.core.config.Config; import io.github.moulberry.notenoughupdates.core.config.struct.ConfigProcessor; import io.github.moulberry.notenoughupdates.core.util.lerp.LerpUtils; import io.github.moulberry.notenoughupdates.core.util.render.RenderUtils; @@ -13,7 +12,6 @@ import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; -import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; @@ -26,8 +24,8 @@ public class GuiOptionEditorDraggableList extends GuiOptionEditor { private static final ResourceLocation DELETE = new ResourceLocation("notenoughupdates:core/delete.png"); - private String[] exampleText; - private List activeText; + private final String[] exampleText; + private final List activeText; private int currentDragging = -1; private int dragStartIndex = -1; @@ -49,7 +47,7 @@ public class GuiOptionEditorDraggableList extends GuiOptionEditor { public int getHeight() { int height = super.getHeight() + 13; - for(int strIndex : activeText) { + for (int strIndex : activeText) { String str = exampleText[strIndex]; height += 10 * str.split("\n").length; } @@ -65,42 +63,42 @@ public class GuiOptionEditorDraggableList extends GuiOptionEditor { GlStateManager.color(1, 1, 1, 1); Minecraft.getMinecraft().getTextureManager().bindTexture(button_tex); - RenderUtils.drawTexturedRect(x+width/6-24, y+45-7-14, 48, 16); + RenderUtils.drawTexturedRect(x + width / 6 - 24, y + 45 - 7 - 14, 48, 16); TextRenderUtils.drawStringCenteredScaledMaxWidth("Add", Minecraft.getMinecraft().fontRendererObj, - x+width/6, y+45-7-6, + x + width / 6, y + 45 - 7 - 6, false, 44, 0xFF303030); long currentTime = System.currentTimeMillis(); - if(trashHoverTime < 0) { - float greenBlue = LerpUtils.clampZeroOne((currentTime + trashHoverTime)/250f); + if (trashHoverTime < 0) { + float greenBlue = LerpUtils.clampZeroOne((currentTime + trashHoverTime) / 250f); GlStateManager.color(1, greenBlue, greenBlue, 1); } else { - float greenBlue = LerpUtils.clampZeroOne((250 + trashHoverTime - currentTime)/250f); + float greenBlue = LerpUtils.clampZeroOne((250 + trashHoverTime - currentTime) / 250f); GlStateManager.color(1, greenBlue, greenBlue, 1); } Minecraft.getMinecraft().getTextureManager().bindTexture(DELETE); - Utils.drawTexturedRect(x+width/6+27, y+45-7-13, 11, 14, GL11.GL_NEAREST); + Utils.drawTexturedRect(x + width / 6 + 27, y + 45 - 7 - 13, 11, 14, GL11.GL_NEAREST); - Gui.drawRect(x+5, y+45, x+width-5, y+height-5, 0xffdddddd); - Gui.drawRect(x+6, y+46, x+width-6, y+height-6, 0xff000000); + Gui.drawRect(x + 5, y + 45, x + width - 5, y + height - 5, 0xffdddddd); + Gui.drawRect(x + 6, y + 46, x + width - 6, y + height - 6, 0xff000000); int i = 0; - int yOff=0; - for(int strIndex : activeText) { + int yOff = 0; + for (int strIndex : activeText) { String str = exampleText[strIndex]; String[] multilines = str.split("\n"); int ySize = multilines.length * 10; - if(i++ != dragStartIndex) { - for(int multilineIndex=0; multilineIndex remaining = new ArrayList<>(); - for(int i=0; i= 0) { + } else if (currentDragging >= 0) { int opacity = 0x80; long currentTime = System.currentTimeMillis(); - if(trashHoverTime < 0) { - float greenBlue = LerpUtils.clampZeroOne((currentTime + trashHoverTime)/250f); - opacity = (int)(opacity * greenBlue); + if (trashHoverTime < 0) { + float greenBlue = LerpUtils.clampZeroOne((currentTime + trashHoverTime) / 250f); + opacity = (int) (opacity * greenBlue); } else { - float greenBlue = LerpUtils.clampZeroOne((250 + trashHoverTime - currentTime)/250f); - opacity = (int)(opacity * greenBlue); + float greenBlue = LerpUtils.clampZeroOne((250 + trashHoverTime - currentTime) / 250f); + opacity = (int) (opacity * greenBlue); } - if(opacity < 20) return; + if (opacity < 20) return; ScaledResolution scaledResolution = new ScaledResolution(Minecraft.getMinecraft()); int mouseX = Mouse.getX() * scaledResolution.getScaledWidth() / Minecraft.getMinecraft().displayWidth; @@ -165,67 +163,67 @@ public class GuiOptionEditorDraggableList extends GuiOptionEditor { String[] multilines = str.split("\n"); GlStateManager.enableBlend(); - for(int multilineIndex=0; multilineIndex= 0 && Mouse.getEventButton() == 0 && - mouseX >= x+width/6+27-3 && mouseX <= x+width/6+27+11+3 && - mouseY >= y+45-7-13-3 && mouseY <= y+45-7-13+14+3) { + mouseX >= x + width / 6 + 27 - 3 && mouseX <= x + width / 6 + 27 + 11 + 3 && + mouseY >= y + 45 - 7 - 13 - 3 && mouseY <= y + 45 - 7 - 13 + 14 + 3) { activeText.remove(dragStartIndex); currentDragging = -1; dragStartIndex = -1; return false; } - if(!Mouse.isButtonDown(0) || dropdownOpen) { + if (!Mouse.isButtonDown(0) || dropdownOpen) { currentDragging = -1; dragStartIndex = -1; - if(trashHoverTime > 0) trashHoverTime = -System.currentTimeMillis(); - } else if(currentDragging >= 0 && - mouseX >= x+width/6+27-3 && mouseX <= x+width/6+27+11+3 && - mouseY >= y+45-7-13-3 && mouseY <= y+45-7-13+14+3) { - if(trashHoverTime < 0) trashHoverTime = System.currentTimeMillis(); + if (trashHoverTime > 0) trashHoverTime = -System.currentTimeMillis(); + } else if (currentDragging >= 0 && + mouseX >= x + width / 6 + 27 - 3 && mouseX <= x + width / 6 + 27 + 11 + 3 && + mouseY >= y + 45 - 7 - 13 - 3 && mouseY <= y + 45 - 7 - 13 + 14 + 3) { + if (trashHoverTime < 0) trashHoverTime = System.currentTimeMillis(); } else { - if(trashHoverTime > 0) trashHoverTime = -System.currentTimeMillis(); + if (trashHoverTime > 0) trashHoverTime = -System.currentTimeMillis(); } - if(Mouse.getEventButtonState()) { + if (Mouse.getEventButtonState()) { int height = getHeight(); - if(dropdownOpen) { + if (dropdownOpen) { List remaining = new ArrayList<>(); - for(int i=0; i left && mouseX < left+dropdownWidth && + if (mouseX > left && mouseX < left + dropdownWidth && mouseY > top && mouseY < top + dropdownHeight) { int dropdownY = -1; - for(int strIndex : remaining) { - if(mouseY < top+dropdownY+12) { + for (int strIndex : remaining) { + if (mouseY < top + dropdownY + 12) { activeText.add(0, strIndex); - if(remaining.size() == 1) dropdownOpen = false; + if (remaining.size() == 1) dropdownOpen = false; return true; } @@ -237,25 +235,25 @@ public class GuiOptionEditorDraggableList extends GuiOptionEditor { return true; } - if(activeText.size() < exampleText.length && - mouseX > x+width/6-24 && mouseX < x+width/6+24 && - mouseY > y+45-7-14 && mouseY < y+45-7+2) { + if (activeText.size() < exampleText.length && + mouseX > x + width / 6 - 24 && mouseX < x + width / 6 + 24 && + mouseY > y + 45 - 7 - 14 && mouseY < y + 45 - 7 + 2) { dropdownOpen = !dropdownOpen; dragOffsetX = mouseX; dragOffsetY = mouseY; return true; } - if(Mouse.getEventButton() == 0 && - mouseX > x+5 && mouseX < x+width-5 && - mouseY > y+45 && mouseY < y+height-6) { - int yOff=0; + if (Mouse.getEventButton() == 0 && + mouseX > x + 5 && mouseX < x + width - 5 && + mouseY > y + 45 && mouseY < y + height - 6) { + int yOff = 0; int i = 0; - for(int strIndex : activeText) { + for (int strIndex : activeText) { int ySize = 10 * exampleText[strIndex].split("\n").length; - if(mouseY < y+50+yOff+ySize) { - dragOffsetX = x+10 - mouseX; - dragOffsetY = y+50+yOff - mouseY; + if (mouseY < y + 50 + yOff + ySize) { + dragOffsetX = x + 10 - mouseX; + dragOffsetY = y + 50 + yOff - mouseY; currentDragging = strIndex; dragStartIndex = i; @@ -265,11 +263,11 @@ public class GuiOptionEditorDraggableList extends GuiOptionEditor { i++; } } - } else if(Mouse.getEventButton() == -1 && currentDragging >= 0) { - int yOff=0; + } else if (Mouse.getEventButton() == -1 && currentDragging >= 0) { + int yOff = 0; int i = 0; - for(int strIndex : activeText) { - if(dragOffsetY + mouseY + 4 < y+50+yOff+10) { + for (int strIndex : activeText) { + if (dragOffsetY + mouseY + 4 < y + 50 + yOff + 10) { activeText.remove(dragStartIndex); activeText.add(i, currentDragging); diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorDropdown.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorDropdown.java index 0451b459..c003f135 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorDropdown.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorDropdown.java @@ -6,9 +6,7 @@ import io.github.moulberry.notenoughupdates.core.util.render.TextRenderUtils; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; -import net.minecraft.client.renderer.GlStateManager; import org.lwjgl.input.Mouse; -import org.lwjgl.opengl.GL11; public class GuiOptionEditorDropdown extends GuiOptionEditor { @@ -19,7 +17,7 @@ public class GuiOptionEditorDropdown extends GuiOptionEditor { public GuiOptionEditorDropdown(ConfigProcessor.ProcessedOption option, String[] values, int selected, boolean useOrdinal) { super(option); - if(selected >= values.length) selected = values.length; + if (selected >= values.length) selected = values.length; this.values = values; this.selected = selected; this.useOrdinal = useOrdinal; @@ -29,68 +27,67 @@ public class GuiOptionEditorDropdown extends GuiOptionEditor { public void render(int x, int y, int width) { super.render(x, y, width); - if(!open) { + if (!open) { int height = getHeight(); FontRenderer fr = Minecraft.getMinecraft().fontRendererObj; - int dropdownWidth = Math.min(width/3-10, 80); - int left = x+width/6-dropdownWidth/2; - int top = y+height-7-14; + int dropdownWidth = Math.min(width / 3 - 10, 80); + int left = x + width / 6 - dropdownWidth / 2; + int top = y + height - 7 - 14; String selectedString = " - Select - "; - if(selected >= 0 && selected < values.length) { + if (selected >= 0 && selected < values.length) { selectedString = values[selected]; } RenderUtils.drawFloatingRectDark(left, top, dropdownWidth, 14, false); - TextRenderUtils.drawStringScaled("\u25BC", fr, left+dropdownWidth-10, y+height-7-15, false, 0xffa0a0a0, 2); + TextRenderUtils.drawStringScaled("\u25BC", fr, left + dropdownWidth - 10, y + height - 7 - 15, false, 0xffa0a0a0, 2); - TextRenderUtils.drawStringScaledMaxWidth(selectedString, fr, left+3, top+3, false, - dropdownWidth-16, 0xffa0a0a0); + TextRenderUtils.drawStringScaledMaxWidth(selectedString, fr, left + 3, top + 3, false, + dropdownWidth - 16, 0xffa0a0a0); } } @Override public void renderOverlay(int x, int y, int width) { - if(open) { + if (open) { String selectedString = " - Select - "; - if(selected >= 0 && selected < values.length) { + if (selected >= 0 && selected < values.length) { selectedString = values[selected]; } int height = getHeight(); FontRenderer fr = Minecraft.getMinecraft().fontRendererObj; - int dropdownWidth = Math.min(width/3-10, 80); - int left = x+width/6-dropdownWidth/2; - int top = y+height-7-14; + int dropdownWidth = Math.min(width / 3 - 10, 80); + int left = x + width / 6 - dropdownWidth / 2; + int top = y + height - 7 - 14; - int dropdownHeight = 13 + 12*values.length; + int dropdownHeight = 13 + 12 * values.length; int main = 0xff202026; int blue = 0xff2355ad; - Gui.drawRect(left, top, left+1, top+dropdownHeight, blue); //Left - Gui.drawRect(left+1, top, left+dropdownWidth, top+1, blue); //Top - Gui.drawRect(left+dropdownWidth-1, top+1, left+dropdownWidth, top+dropdownHeight, blue); //Right - Gui.drawRect(left+1, top+dropdownHeight-1, left+dropdownWidth-1, top+dropdownHeight, blue); //Bottom - Gui.drawRect(left+1, top+1, left+dropdownWidth-1, top+dropdownHeight-1, main); //Middle + Gui.drawRect(left, top, left + 1, top + dropdownHeight, blue); //Left + Gui.drawRect(left + 1, top, left + dropdownWidth, top + 1, blue); //Top + Gui.drawRect(left + dropdownWidth - 1, top + 1, left + dropdownWidth, top + dropdownHeight, blue); //Right + Gui.drawRect(left + 1, top + dropdownHeight - 1, left + dropdownWidth - 1, top + dropdownHeight, blue); //Bottom + Gui.drawRect(left + 1, top + 1, left + dropdownWidth - 1, top + dropdownHeight - 1, main); //Middle - Gui.drawRect(left+1, top+14-1, left+dropdownWidth-1, top+14, blue); //Bar + Gui.drawRect(left + 1, top + 14 - 1, left + dropdownWidth - 1, top + 14, blue); //Bar int dropdownY = 13; - for(String option : values) { - if(option.isEmpty()) { + for (String option : values) { + if (option.isEmpty()) { option = ""; } - TextRenderUtils.drawStringScaledMaxWidth(option, fr, left+3, top+3+dropdownY, false, dropdownWidth-6, 0xffa0a0a0); + TextRenderUtils.drawStringScaledMaxWidth(option, fr, left + 3, top + 3 + dropdownY, false, dropdownWidth - 6, 0xffa0a0a0); dropdownY += 12; } - TextRenderUtils.drawStringScaled("\u25B2", fr, left+dropdownWidth-10, y+height-7-15, false, 0xffa0a0a0, 2); + TextRenderUtils.drawStringScaled("\u25B2", fr, left + dropdownWidth - 10, y + height - 7 - 15, false, 0xffa0a0a0, 2); - - TextRenderUtils.drawStringScaledMaxWidth(selectedString, fr, left+3, top+3, false, - dropdownWidth-16, 0xffa0a0a0); + TextRenderUtils.drawStringScaledMaxWidth(selectedString, fr, left + 3, top + 3, false, + dropdownWidth - 16, 0xffa0a0a0); } } @@ -98,12 +95,12 @@ public class GuiOptionEditorDropdown extends GuiOptionEditor { public boolean mouseInput(int x, int y, int width, int mouseX, int mouseY) { int height = getHeight(); - int left = x+width/6-40; - int top = y+height-7-14; + int left = x + width / 6 - 40; + int top = y + height - 7 - 14; - if(Mouse.getEventButtonState() && Mouse.getEventButton() == 0) { - if(mouseX >= left && mouseX <= left+80 && - mouseY >= top && mouseY <= top+14) { + if (Mouse.getEventButtonState() && Mouse.getEventButton() == 0) { + if (mouseX >= left && mouseX <= left + 80 && + mouseY >= top && mouseY <= top + 14) { open = !open; return true; } @@ -116,19 +113,19 @@ public class GuiOptionEditorDropdown extends GuiOptionEditor { public boolean mouseInputOverlay(int x, int y, int width, int mouseX, int mouseY) { int height = getHeight(); - int left = x+width/6-40; - int top = y+height-7-14; + int left = x + width / 6 - 40; + int top = y + height - 7 - 14; - if(Mouse.getEventButtonState() && Mouse.getEventButton() == 0) { - if(!(mouseX >= left && mouseX <= left+80 && - mouseY >= top && mouseY <= top+14) && open) { + if (Mouse.getEventButtonState() && Mouse.getEventButton() == 0) { + if (!(mouseX >= left && mouseX <= left + 80 && + mouseY >= top && mouseY <= top + 14) && open) { open = false; - if(mouseX >= left && mouseX <= left+80) { + if (mouseX >= left && mouseX <= left + 80) { int dropdownY = 13; - for(int ordinal=0; ordinal < values.length; ordinal++) { - if(mouseY >= top+3+dropdownY && mouseY <= top+3+dropdownY+12) { + for (int ordinal = 0; ordinal < values.length; ordinal++) { + if (mouseY >= top + 3 + dropdownY && mouseY <= top + 3 + dropdownY + 12) { selected = ordinal; - if(useOrdinal) { + if (useOrdinal) { option.set(selected); } else { option.set(values[selected]); diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorKeybind.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorKeybind.java index 601cc6b1..c1297668 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorKeybind.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorKeybind.java @@ -1,6 +1,5 @@ package io.github.moulberry.notenoughupdates.core.config.gui; -import io.github.moulberry.notenoughupdates.core.config.Config; import io.github.moulberry.notenoughupdates.core.config.KeybindHelper; import io.github.moulberry.notenoughupdates.core.config.struct.ConfigProcessor; import io.github.moulberry.notenoughupdates.core.util.render.RenderUtils; @@ -19,7 +18,7 @@ public class GuiOptionEditorKeybind extends GuiOptionEditor { private static final ResourceLocation RESET = new ResourceLocation("notenoughupdates:itemcustomize/reset.png"); private int keyCode; - private int defaultKeyCode; + private final int defaultKeyCode; private boolean editingKeycode; public GuiOptionEditorKeybind(ConfigProcessor.ProcessedOption option, int keyCode, int defaultKeyCode) { @@ -36,38 +35,38 @@ public class GuiOptionEditorKeybind extends GuiOptionEditor { GlStateManager.color(1, 1, 1, 1); Minecraft.getMinecraft().getTextureManager().bindTexture(button_tex); - RenderUtils.drawTexturedRect(x+width/6-24, y+height-7-14, 48, 16); + RenderUtils.drawTexturedRect(x + width / 6 - 24, y + height - 7 - 14, 48, 16); String keyName = KeybindHelper.getKeyName(keyCode); - String text = editingKeycode ? "> "+keyName+" <" : keyName; + String text = editingKeycode ? "> " + keyName + " <" : keyName; TextRenderUtils.drawStringCenteredScaledMaxWidth(text, Minecraft.getMinecraft().fontRendererObj, - x+width/6, y+height-7-6, + x + width / 6, y + height - 7 - 6, false, 40, 0xFF303030); Minecraft.getMinecraft().getTextureManager().bindTexture(RESET); GlStateManager.color(1, 1, 1, 1); - RenderUtils.drawTexturedRect(x+width/6-24+48+3, y+height-7-14+3, 10, 11, GL11.GL_NEAREST); + RenderUtils.drawTexturedRect(x + width / 6 - 24 + 48 + 3, y + height - 7 - 14 + 3, 10, 11, GL11.GL_NEAREST); } @Override public boolean mouseInput(int x, int y, int width, int mouseX, int mouseY) { - if(Mouse.getEventButtonState() && Mouse.getEventButton() != -1 && editingKeycode) { + if (Mouse.getEventButtonState() && Mouse.getEventButton() != -1 && editingKeycode) { editingKeycode = false; - keyCode = Mouse.getEventButton()-100; + keyCode = Mouse.getEventButton() - 100; option.set(keyCode); return true; } - if(Mouse.getEventButtonState() && Mouse.getEventButton() == 0) { + if (Mouse.getEventButtonState() && Mouse.getEventButton() == 0) { int height = getHeight(); - if(mouseX > x+width/6-24 && mouseX < x+width/6+24 && - mouseY > y+height-7-14 && mouseY < y+height-7+2) { + if (mouseX > x + width / 6 - 24 && mouseX < x + width / 6 + 24 && + mouseY > y + height - 7 - 14 && mouseY < y + height - 7 + 2) { editingKeycode = true; return true; } - if(mouseX > x+width/6-24+48+3 && mouseX < x+width/6-24+48+13 && - mouseY > y+height-7-14+3 && mouseY < y+height-7-14+3+11) { + if (mouseX > x + width / 6 - 24 + 48 + 3 && mouseX < x + width / 6 - 24 + 48 + 13 && + mouseY > y + height - 7 - 14 + 3 && mouseY < y + height - 7 - 14 + 3 + 11) { keyCode = defaultKeyCode; option.set(keyCode); return true; @@ -79,14 +78,14 @@ public class GuiOptionEditorKeybind extends GuiOptionEditor { @Override public boolean keyboardInput() { - if(editingKeycode) { + if (editingKeycode) { editingKeycode = false; - if(Keyboard.getEventKey() == Keyboard.KEY_ESCAPE) { + if (Keyboard.getEventKey() == Keyboard.KEY_ESCAPE) { keyCode = 0; - } else if(Keyboard.getEventKey() != 0) { + } else if (Keyboard.getEventKey() != 0) { keyCode = Keyboard.getEventKey(); } - if(keyCode > 256) keyCode = 0; + if (keyCode > 256) keyCode = 0; option.set(keyCode); return true; } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorSlider.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorSlider.java index a3665436..50e98a1d 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorSlider.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorSlider.java @@ -1,6 +1,5 @@ package io.github.moulberry.notenoughupdates.core.config.gui; -import io.github.moulberry.notenoughupdates.core.GuiElementBoolean; import io.github.moulberry.notenoughupdates.core.GuiElementTextField; import io.github.moulberry.notenoughupdates.core.config.struct.ConfigProcessor; import io.github.moulberry.notenoughupdates.core.util.GuiElementSlider; @@ -15,13 +14,13 @@ public class GuiOptionEditorSlider extends GuiOptionEditor { public GuiOptionEditorSlider(ConfigProcessor.ProcessedOption option, float minValue, float maxValue, float minStep) { super(option); - if(minStep < 0) minStep = 0.01f; + if (minStep < 0) minStep = 0.01f; - float floatVal = ((Number)option.get()).floatValue(); + float floatVal = ((Number) option.get()).floatValue(); { String strVal; - if(floatVal % 1 == 0) { - strVal = Integer.toString((int)floatVal); + if (floatVal % 1 == 0) { + strVal = Integer.toString((int) floatVal); } else { strVal = Float.toString(floatVal); } @@ -33,7 +32,7 @@ public class GuiOptionEditorSlider extends GuiOptionEditor { option.set(val); String strVal; - if(val % 1 == 0) { + if (val % 1 == 0) { strVal = Integer.toString(val.intValue()); } else { strVal = Float.toString(val); @@ -49,54 +48,54 @@ public class GuiOptionEditorSlider extends GuiOptionEditor { super.render(x, y, width); int height = getHeight(); - int fullWidth = Math.min(width/3-10, 80); - int sliderWidth = (fullWidth-5)*3/4; - int textFieldWidth = (fullWidth-5)/4; + int fullWidth = Math.min(width / 3 - 10, 80); + int sliderWidth = (fullWidth - 5) * 3 / 4; + int textFieldWidth = (fullWidth - 5) / 4; - slider.x = x+width/6-fullWidth/2; - slider.y = y+height-7-14; + slider.x = x + width / 6 - fullWidth / 2; + slider.y = y + height - 7 - 14; slider.width = sliderWidth; slider.render(); - if(textField.getFocus()) { + if (textField.getFocus()) { textField.setOptions(GuiElementTextField.NO_SPACE | GuiElementTextField.NUM_ONLY); - textField.setSize(Minecraft.getMinecraft().fontRendererObj.getStringWidth(textField.getText())+10, + textField.setSize(Minecraft.getMinecraft().fontRendererObj.getStringWidth(textField.getText()) + 10, 16); } else { textField.setSize(textFieldWidth, 16); textField.setOptions(GuiElementTextField.NO_SPACE | GuiElementTextField.NUM_ONLY | GuiElementTextField.SCALE_TEXT); } - textField.render(x+width/6-fullWidth/2+sliderWidth+5, y+height-7-14); + textField.render(x + width / 6 - fullWidth / 2 + sliderWidth + 5, y + height - 7 - 14); } @Override public boolean mouseInput(int x, int y, int width, int mouseX, int mouseY) { int height = getHeight(); - int fullWidth = Math.min(width/3-10, 80); - int sliderWidth = (fullWidth-5)*3/4; - int textFieldWidth = (fullWidth-5)/4; + int fullWidth = Math.min(width / 3 - 10, 80); + int sliderWidth = (fullWidth - 5) * 3 / 4; + int textFieldWidth = (fullWidth - 5) / 4; - slider.x = x+width/6-fullWidth/2; - slider.y = y+height-7-14; + slider.x = x + width / 6 - fullWidth / 2; + slider.y = y + height - 7 - 14; slider.width = sliderWidth; - if(slider.mouseInput(mouseX, mouseY)) { + if (slider.mouseInput(mouseX, mouseY)) { textField.unfocus(); return true; } - if(textField.getFocus()) { - textFieldWidth = Minecraft.getMinecraft().fontRendererObj.getStringWidth(textField.getText())+10; + if (textField.getFocus()) { + textFieldWidth = Minecraft.getMinecraft().fontRendererObj.getStringWidth(textField.getText()) + 10; } - int textFieldX = x+width/6-fullWidth/2+sliderWidth+5; - int textFieldY = y+height-7-14; + int textFieldX = x + width / 6 - fullWidth / 2 + sliderWidth + 5; + int textFieldY = y + height - 7 - 14; textField.setSize(textFieldWidth, 16); - if(Mouse.getEventButtonState() && (Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1)) { - if(mouseX > textFieldX && mouseX < textFieldX+textFieldWidth && - mouseY > textFieldY && mouseY < textFieldY+16) { + if (Mouse.getEventButtonState() && (Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1)) { + if (mouseX > textFieldX && mouseX < textFieldX + textFieldWidth && + mouseY > textFieldY && mouseY < textFieldY + 16) { textField.mouseClicked(mouseX, mouseY, Mouse.getEventButton()); return true; } @@ -108,18 +107,18 @@ public class GuiOptionEditorSlider extends GuiOptionEditor { @Override public boolean keyboardInput() { - if(Keyboard.getEventKeyState() && textField.getFocus()) { + if (Keyboard.getEventKeyState() && textField.getFocus()) { textField.keyTyped(Keyboard.getEventCharacter(), Keyboard.getEventKey()); try { textField.setCustomBorderColour(0xffffffff); float f = Float.parseFloat(textField.getText()); - if(option.set(f)) { + if (option.set(f)) { slider.setValue(f); } else { textField.setCustomBorderColour(0xff0000ff); } - } catch(Exception e) { + } catch (Exception e) { textField.setCustomBorderColour(0xffff0000); } @@ -128,5 +127,4 @@ public class GuiOptionEditorSlider extends GuiOptionEditor { return false; } - } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorText.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorText.java index bf50bda8..b05c3ee3 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorText.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiOptionEditorText.java @@ -1,9 +1,7 @@ package io.github.moulberry.notenoughupdates.core.config.gui; -import io.github.moulberry.notenoughupdates.core.GuiElementBoolean; import io.github.moulberry.notenoughupdates.core.GuiElementTextField; import io.github.moulberry.notenoughupdates.core.config.struct.ConfigProcessor; -import io.github.moulberry.notenoughupdates.core.util.GuiElementSlider; import net.minecraft.client.Minecraft; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; @@ -15,7 +13,7 @@ public class GuiOptionEditorText extends GuiOptionEditor { public GuiOptionEditorText(ConfigProcessor.ProcessedOption option) { super(option); - textField = new GuiElementTextField((String)option.get(), 0); + textField = new GuiElementTextField((String) option.get(), 0); } @Override @@ -23,36 +21,36 @@ public class GuiOptionEditorText extends GuiOptionEditor { super.render(x, y, width); int height = getHeight(); - int fullWidth = Math.min(width/3-10, 80); + int fullWidth = Math.min(width / 3 - 10, 80); - int textFieldX = x+width/6-fullWidth/2; - if(textField.getFocus()) { - fullWidth = Math.max(fullWidth, Minecraft.getMinecraft().fontRendererObj.getStringWidth(textField.getText())+10); + int textFieldX = x + width / 6 - fullWidth / 2; + if (textField.getFocus()) { + fullWidth = Math.max(fullWidth, Minecraft.getMinecraft().fontRendererObj.getStringWidth(textField.getText()) + 10); } textField.setSize(fullWidth, 16); - textField.render(textFieldX, y+height-7-14); + textField.render(textFieldX, y + height - 7 - 14); } @Override public boolean mouseInput(int x, int y, int width, int mouseX, int mouseY) { int height = getHeight(); - int fullWidth = Math.min(width/3-10, 80); + int fullWidth = Math.min(width / 3 - 10, 80); - int textFieldX = x+width/6-fullWidth/2; + int textFieldX = x + width / 6 - fullWidth / 2; - if(textField.getFocus()) { - fullWidth = Math.max(fullWidth, Minecraft.getMinecraft().fontRendererObj.getStringWidth(textField.getText())+10); + if (textField.getFocus()) { + fullWidth = Math.max(fullWidth, Minecraft.getMinecraft().fontRendererObj.getStringWidth(textField.getText()) + 10); } - int textFieldY = y+height-7-14; + int textFieldY = y + height - 7 - 14; textField.setSize(fullWidth, 16); - if(Mouse.getEventButtonState() && (Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1)) { - if(mouseX > textFieldX && mouseX < textFieldX+fullWidth && - mouseY > textFieldY && mouseY < textFieldY+16) { + if (Mouse.getEventButtonState() && (Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1)) { + if (mouseX > textFieldX && mouseX < textFieldX + fullWidth && + mouseY > textFieldY && mouseY < textFieldY + 16) { textField.mouseClicked(mouseX, mouseY, Mouse.getEventButton()); return true; } @@ -64,14 +62,14 @@ public class GuiOptionEditorText extends GuiOptionEditor { @Override public boolean keyboardInput() { - if(Keyboard.getEventKeyState() && textField.getFocus()) { + if (Keyboard.getEventKeyState() && textField.getFocus()) { Keyboard.enableRepeatEvents(true); textField.keyTyped(Keyboard.getEventCharacter(), Keyboard.getEventKey()); try { textField.setCustomBorderColour(0xffffffff); option.set(textField.getText()); - } catch(Exception e) { + } catch (Exception e) { textField.setCustomBorderColour(0xffff0000); } @@ -80,5 +78,4 @@ public class GuiOptionEditorText extends GuiOptionEditor { return false; } - } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiPositionEditor.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiPositionEditor.java index e979e832..467d2b93 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiPositionEditor.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/gui/GuiPositionEditor.java @@ -14,7 +14,7 @@ import java.io.IOException; public class GuiPositionEditor extends GuiScreen { private final Position position; - private Position originalPosition; + private final Position originalPosition; private final int elementWidth; private final int elementHeight; private final Runnable renderCallback; @@ -27,9 +27,9 @@ public class GuiPositionEditor extends GuiScreen { private int guiScaleOverride = -1; public GuiPositionEditor(Position position, int elementWidth, int elementHeight, - Runnable renderCallback, - Runnable positionChangedCallback, - Runnable closedCallback) { + Runnable renderCallback, + Runnable positionChangedCallback, + Runnable closedCallback) { this.position = position; this.originalPosition = position.clone(); this.elementWidth = elementWidth; @@ -54,7 +54,7 @@ public class GuiPositionEditor extends GuiScreen { public void drawScreen(int mouseX, int mouseY, float partialTicks) { super.drawScreen(mouseX, mouseY, partialTicks); ScaledResolution scaledResolution; - if(guiScaleOverride >= 0) { + if (guiScaleOverride >= 0) { scaledResolution = Utils.pushGuiScale(guiScaleOverride); } else { scaledResolution = new ScaledResolution(Minecraft.getMinecraft()); @@ -67,7 +67,7 @@ public class GuiPositionEditor extends GuiScreen { drawDefaultBackground(); - if(clicked) { + if (clicked) { grabbedX += position.moveX(mouseX - grabbedX, elementWidth, scaledResolution); grabbedY += position.moveY(mouseY - grabbedY, elementHeight, scaledResolution); } @@ -77,28 +77,28 @@ public class GuiPositionEditor extends GuiScreen { int x = position.getAbsX(scaledResolution, elementWidth); int y = position.getAbsY(scaledResolution, elementHeight); - if(position.isCenterX()) x -= elementWidth/2; - if(position.isCenterY()) y -= elementHeight/2; - Gui.drawRect(x, y, x+elementWidth, y+elementHeight, 0x80404040); + if (position.isCenterX()) x -= elementWidth / 2; + if (position.isCenterY()) y -= elementHeight / 2; + Gui.drawRect(x, y, x + elementWidth, y + elementHeight, 0x80404040); - if(guiScaleOverride >= 0) { + if (guiScaleOverride >= 0) { Utils.pushGuiScale(-1); } scaledResolution = new ScaledResolution(Minecraft.getMinecraft()); Utils.drawStringCentered("Position Editor", Minecraft.getMinecraft().fontRendererObj, - scaledResolution.getScaledWidth()/2, 8, true, 0xffffff); + scaledResolution.getScaledWidth() / 2, 8, true, 0xffffff); Utils.drawStringCentered("R to Reset - Arrow keys/mouse to move", Minecraft.getMinecraft().fontRendererObj, - scaledResolution.getScaledWidth()/2, 18, true, 0xffffff); + scaledResolution.getScaledWidth() / 2, 18, true, 0xffffff); } @Override protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { super.mouseClicked(mouseX, mouseY, mouseButton); - if(mouseButton == 0) { + if (mouseButton == 0) { ScaledResolution scaledResolution; - if(guiScaleOverride >= 0) { + if (guiScaleOverride >= 0) { scaledResolution = Utils.pushGuiScale(guiScaleOverride); } else { scaledResolution = new ScaledResolution(Minecraft.getMinecraft()); @@ -108,17 +108,17 @@ public class GuiPositionEditor extends GuiScreen { int x = position.getAbsX(scaledResolution, elementWidth); int y = position.getAbsY(scaledResolution, elementHeight); - if(position.isCenterX()) x -= elementWidth/2; - if(position.isCenterY()) y -= elementHeight/2; + if (position.isCenterX()) x -= elementWidth / 2; + if (position.isCenterY()) y -= elementHeight / 2; - if(mouseX >= x && mouseY >= y && - mouseX <= x+elementWidth && mouseY <= y+elementHeight) { + if (mouseX >= x && mouseY >= y && + mouseX <= x + elementWidth && mouseY <= y + elementHeight) { clicked = true; grabbedX = mouseX; grabbedY = mouseY; } - if(guiScaleOverride >= 0) { + if (guiScaleOverride >= 0) { Utils.pushGuiScale(-1); } } @@ -128,18 +128,18 @@ public class GuiPositionEditor extends GuiScreen { protected void keyTyped(char typedChar, int keyCode) throws IOException { Keyboard.enableRepeatEvents(true); - if(keyCode == Keyboard.KEY_R) { + if (keyCode == Keyboard.KEY_R) { position.set(originalPosition); - } else if(!clicked) { + } else if (!clicked) { boolean shiftHeld = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); int dist = shiftHeld ? 10 : 1; - if(keyCode == Keyboard.KEY_DOWN) { + if (keyCode == Keyboard.KEY_DOWN) { position.moveY(dist, elementHeight, new ScaledResolution(Minecraft.getMinecraft())); - } else if(keyCode == Keyboard.KEY_UP) { + } else if (keyCode == Keyboard.KEY_UP) { position.moveY(-dist, elementHeight, new ScaledResolution(Minecraft.getMinecraft())); - } else if(keyCode == Keyboard.KEY_LEFT) { + } else if (keyCode == Keyboard.KEY_LEFT) { position.moveX(-dist, elementWidth, new ScaledResolution(Minecraft.getMinecraft())); - } else if(keyCode == Keyboard.KEY_RIGHT) { + } else if (keyCode == Keyboard.KEY_RIGHT) { position.moveX(dist, elementWidth, new ScaledResolution(Minecraft.getMinecraft())); } } @@ -156,9 +156,9 @@ public class GuiPositionEditor extends GuiScreen { protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) { super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick); - if(clicked) { + if (clicked) { ScaledResolution scaledResolution; - if(guiScaleOverride >= 0) { + if (guiScaleOverride >= 0) { scaledResolution = Utils.pushGuiScale(guiScaleOverride); } else { scaledResolution = new ScaledResolution(Minecraft.getMinecraft()); @@ -170,7 +170,7 @@ public class GuiPositionEditor extends GuiScreen { grabbedY += position.moveY(mouseY - grabbedY, elementHeight, scaledResolution); positionChangedCallback.run(); - if(guiScaleOverride >= 0) { + if (guiScaleOverride >= 0) { Utils.pushGuiScale(-1); } } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/config/struct/ConfigProcessor.java b/src/main/java/io/github/moulberry/notenoughupdates/core/config/struct/ConfigProcessor.java index 4ce10162..b1581458 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/config/struct/ConfigProcessor.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/config/struct/ConfigProcessor.java @@ -4,7 +4,6 @@ import com.google.gson.annotations.Expose; import io.github.moulberry.notenoughupdates.core.config.Config; import io.github.moulberry.notenoughupdates.core.config.annotations.*; import io.github.moulberry.notenoughupdates.core.config.gui.*; -import io.github.moulberry.notenoughupdates.core.config.Config; import java.lang.reflect.Field; import java.util.LinkedHashMap; @@ -46,20 +45,20 @@ public class ConfigProcessor { public Object get() { try { return field.get(container); - } catch(Exception e) { + } catch (Exception e) { return null; } } public boolean set(Object value) { try { - if(field.getType() == int.class && value instanceof Number) { - field.set(container, ((Number)value).intValue()); + if (field.getType() == int.class && value instanceof Number) { + field.set(container, ((Number) value).intValue()); } else { field.set(container, value); } return true; - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); return false; } @@ -68,15 +67,15 @@ public class ConfigProcessor { public static LinkedHashMap create(Config config) { LinkedHashMap processedConfig = new LinkedHashMap<>(); - for(Field categoryField : config.getClass().getDeclaredFields()) { + for (Field categoryField : config.getClass().getDeclaredFields()) { boolean exposePresent = categoryField.isAnnotationPresent(Expose.class); boolean categoryPresent = categoryField.isAnnotationPresent(Category.class); - if(exposePresent && categoryPresent) { + if (exposePresent && categoryPresent) { Object categoryObj; try { categoryObj = categoryField.get(config); - } catch(Exception e) { + } catch (Exception e) { //System.err.printf("Failed to load config category %s. Field was not accessible.\n", categoryField.getName()); continue; } @@ -88,10 +87,10 @@ public class ConfigProcessor { ); processedConfig.put(categoryField.getName(), cat); - for(Field optionField : categoryObj.getClass().getDeclaredFields()) { + for (Field optionField : categoryObj.getClass().getDeclaredFields()) { boolean optionPresent = optionField.isAnnotationPresent(ConfigOption.class); - if(optionPresent) { + if (optionPresent) { ConfigOption optionAnnotation = optionField.getAnnotation(ConfigOption.class); ProcessedOption option = new ProcessedOption( optionAnnotation.name(), @@ -100,70 +99,70 @@ public class ConfigProcessor { optionField, categoryObj ); - if(optionField.isAnnotationPresent(ConfigAccordionId.class)) { + if (optionField.isAnnotationPresent(ConfigAccordionId.class)) { ConfigAccordionId annotation = optionField.getAnnotation(ConfigAccordionId.class); option.accordionId = annotation.id(); } GuiOptionEditor editor = null; Class optionType = optionField.getType(); - if(optionType.isAssignableFrom(int.class) && + if (optionType.isAssignableFrom(int.class) && optionField.isAnnotationPresent(ConfigEditorKeybind.class)) { ConfigEditorKeybind configEditorAnnotation = optionField.getAnnotation(ConfigEditorKeybind.class); - editor = new GuiOptionEditorKeybind(option, (int)option.get(), configEditorAnnotation.defaultKey()); + editor = new GuiOptionEditorKeybind(option, (int) option.get(), configEditorAnnotation.defaultKey()); } - if(optionField.isAnnotationPresent(ConfigEditorButton.class)) { + if (optionField.isAnnotationPresent(ConfigEditorButton.class)) { ConfigEditorButton configEditorAnnotation = optionField.getAnnotation(ConfigEditorButton.class); editor = new GuiOptionEditorButton(option, configEditorAnnotation.runnableId(), configEditorAnnotation.buttonText(), config); } - if(optionType.isAssignableFrom(boolean.class) && + if (optionType.isAssignableFrom(boolean.class) && optionField.isAnnotationPresent(ConfigEditorBoolean.class)) { editor = new GuiOptionEditorBoolean(option); } - if(optionType.isAssignableFrom(boolean.class) && + if (optionType.isAssignableFrom(boolean.class) && optionField.isAnnotationPresent(ConfigEditorAccordion.class)) { ConfigEditorAccordion configEditorAnnotation = optionField.getAnnotation(ConfigEditorAccordion.class); editor = new GuiOptionEditorAccordion(option, configEditorAnnotation.id()); } - if(optionType.isAssignableFrom(int.class)) { - if(optionField.isAnnotationPresent(ConfigEditorDropdown.class)) { + if (optionType.isAssignableFrom(int.class)) { + if (optionField.isAnnotationPresent(ConfigEditorDropdown.class)) { ConfigEditorDropdown configEditorAnnotation = optionField.getAnnotation(ConfigEditorDropdown.class); - editor = new GuiOptionEditorDropdown(option, configEditorAnnotation.values(), (int)option.get(), true); + editor = new GuiOptionEditorDropdown(option, configEditorAnnotation.values(), (int) option.get(), true); } } - if(optionType.isAssignableFrom(List.class)) { - if(optionField.isAnnotationPresent(ConfigEditorDraggableList.class)) { + if (optionType.isAssignableFrom(List.class)) { + if (optionField.isAnnotationPresent(ConfigEditorDraggableList.class)) { ConfigEditorDraggableList configEditorAnnotation = optionField.getAnnotation(ConfigEditorDraggableList.class); editor = new GuiOptionEditorDraggableList(option, configEditorAnnotation.exampleText()); } } - if(optionType.isAssignableFrom(String.class)) { - if(optionField.isAnnotationPresent(ConfigEditorDropdown.class)) { + if (optionType.isAssignableFrom(String.class)) { + if (optionField.isAnnotationPresent(ConfigEditorDropdown.class)) { ConfigEditorDropdown configEditorAnnotation = optionField.getAnnotation(ConfigEditorDropdown.class); editor = new GuiOptionEditorDropdown(option, configEditorAnnotation.values(), configEditorAnnotation.initialIndex(), false); - } else if(optionField.isAnnotationPresent(ConfigEditorColour.class)) { + } else if (optionField.isAnnotationPresent(ConfigEditorColour.class)) { editor = new GuiOptionEditorColour(option); - } else if(optionField.isAnnotationPresent(ConfigEditorText.class)) { + } else if (optionField.isAnnotationPresent(ConfigEditorText.class)) { editor = new GuiOptionEditorText(option); } } - if(optionType.isAssignableFrom(int.class) || + if (optionType.isAssignableFrom(int.class) || optionType.isAssignableFrom(float.class) || optionType.isAssignableFrom(double.class)) { - if(optionField.isAnnotationPresent(ConfigEditorSlider.class)) { + if (optionField.isAnnotationPresent(ConfigEditorSlider.class)) { ConfigEditorSlider configEditorAnnotation = optionField.getAnnotation(ConfigEditorSlider.class); editor = new GuiOptionEditorSlider(option, configEditorAnnotation.minValue(), configEditorAnnotation.maxValue(), configEditorAnnotation.minStep()); } } - if(optionType.isAssignableFrom(String.class)) { - if(optionField.isAnnotationPresent(ConfigEditorDropdown.class)) { + if (optionType.isAssignableFrom(String.class)) { + if (optionField.isAnnotationPresent(ConfigEditorDropdown.class)) { ConfigEditorDropdown configEditorAnnotation = optionField.getAnnotation(ConfigEditorDropdown.class); - editor = new GuiOptionEditorDropdown(option, configEditorAnnotation.values(), 0,false); + editor = new GuiOptionEditorDropdown(option, configEditorAnnotation.values(), 0, false); } } - if(editor == null) { + if (editor == null) { //System.err.printf("Failed to load config option %s. Could not find suitable editor.\n", optionField.getName()); continue; } @@ -171,7 +170,7 @@ public class ConfigProcessor { cat.options.put(optionField.getName(), option); } } - } else if(exposePresent || categoryPresent) { + } else if (exposePresent || categoryPresent) { //System.err.printf("Failed to load config category %s. Both @Expose and @Category must be present.\n", categoryField.getName()); } } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/util/GuiElementSlider.java b/src/main/java/io/github/moulberry/notenoughupdates/core/util/GuiElementSlider.java index 89feaf17..cc8e9708 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/util/GuiElementSlider.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/util/GuiElementSlider.java @@ -19,18 +19,18 @@ public class GuiElementSlider extends GuiElement { public int width; private static final int HEIGHT = 16; - private float minValue; - private float maxValue; - private float minStep; + private final float minValue; + private final float maxValue; + private final float minStep; private float value; - private Consumer setCallback; + private final Consumer setCallback; private boolean clicked = false; public GuiElementSlider(int x, int y, int width, float minValue, float maxValue, float minStep, float value, Consumer setCallback) { - if(minStep < 0) minStep = 0.01f; + if (minStep < 0) minStep = 0.01f; this.x = x; this.y = y; @@ -52,62 +52,62 @@ public class GuiElementSlider extends GuiElement { int mouseX = Mouse.getX() * scaledResolution.getScaledWidth() / Minecraft.getMinecraft().displayWidth; float value = this.value; - if(clicked) { - value = (mouseX-x)*(maxValue-minValue)/width+minValue; + if (clicked) { + value = (mouseX - x) * (maxValue - minValue) / width + minValue; value = Math.max(minValue, Math.min(maxValue, value)); - value = Math.round(value/minStep)*minStep; + value = Math.round(value / minStep) * minStep; } - float sliderAmount = Math.max(0, Math.min(1, (value-minValue)/(maxValue-minValue))); - int sliderAmountI = (int)(width*sliderAmount); + float sliderAmount = Math.max(0, Math.min(1, (value - minValue) / (maxValue - minValue))); + int sliderAmountI = (int) (width * sliderAmount); GlStateManager.color(1f, 1f, 1f, 1f); Minecraft.getMinecraft().getTextureManager().bindTexture(slider_on_cap); Utils.drawTexturedRect(x, y, 4, HEIGHT, GL11.GL_NEAREST); Minecraft.getMinecraft().getTextureManager().bindTexture(slider_off_cap); - Utils.drawTexturedRect(x+width-4, y, 4, HEIGHT, GL11.GL_NEAREST); + Utils.drawTexturedRect(x + width - 4, y, 4, HEIGHT, GL11.GL_NEAREST); - if(sliderAmountI > 5) { + if (sliderAmountI > 5) { Minecraft.getMinecraft().getTextureManager().bindTexture(slider_on_segment); - Utils.drawTexturedRect(x+4, y, sliderAmountI-4, HEIGHT, GL11.GL_NEAREST); + Utils.drawTexturedRect(x + 4, y, sliderAmountI - 4, HEIGHT, GL11.GL_NEAREST); } - if(sliderAmountI < width-5) { + if (sliderAmountI < width - 5) { Minecraft.getMinecraft().getTextureManager().bindTexture(slider_off_segment); - Utils.drawTexturedRect(x+sliderAmountI, y, width-4-sliderAmountI, HEIGHT, GL11.GL_NEAREST); + Utils.drawTexturedRect(x + sliderAmountI, y, width - 4 - sliderAmountI, HEIGHT, GL11.GL_NEAREST); } - for(int i=1; i<4; i++) { - int notchX = x+width*i/4-1; - Minecraft.getMinecraft().getTextureManager().bindTexture(notchX > x+sliderAmountI ? slider_off_notch : slider_on_notch); - Utils.drawTexturedRect(notchX, y+(HEIGHT-4)/2, 2, 4, GL11.GL_NEAREST); + for (int i = 1; i < 4; i++) { + int notchX = x + width * i / 4 - 1; + Minecraft.getMinecraft().getTextureManager().bindTexture(notchX > x + sliderAmountI ? slider_off_notch : slider_on_notch); + Utils.drawTexturedRect(notchX, y + (HEIGHT - 4) / 2, 2, 4, GL11.GL_NEAREST); } Minecraft.getMinecraft().getTextureManager().bindTexture(slider_button_new); - Utils.drawTexturedRect(x+sliderAmountI-4, y, 8, HEIGHT, GL11.GL_NEAREST); + Utils.drawTexturedRect(x + sliderAmountI - 4, y, 8, HEIGHT, GL11.GL_NEAREST); } @Override public boolean mouseInput(int mouseX, int mouseY) { - if(!Mouse.isButtonDown(0)) { + if (!Mouse.isButtonDown(0)) { clicked = false; } - if(Mouse.getEventButton() == 0) { - clicked = Mouse.getEventButtonState() && mouseX > x && mouseX < x+width && mouseY > y && mouseY < y+HEIGHT; - if(clicked) { - value = (mouseX-x)*(maxValue-minValue)/width+minValue; + if (Mouse.getEventButton() == 0) { + clicked = Mouse.getEventButtonState() && mouseX > x && mouseX < x + width && mouseY > y && mouseY < y + HEIGHT; + if (clicked) { + value = (mouseX - x) * (maxValue - minValue) / width + minValue; value = Math.max(minValue, Math.min(maxValue, value)); - value = (float)(Math.round(value/minStep)*(double)minStep); + value = (float) (Math.round(value / minStep) * (double) minStep); setCallback.accept(value); return true; } } - if(!Mouse.getEventButtonState() && Mouse.getEventButton() == -1 && clicked) { - value = (mouseX-x)*(maxValue-minValue)/width+minValue; + if (!Mouse.getEventButtonState() && Mouse.getEventButton() == -1 && clicked) { + value = (mouseX - x) * (maxValue - minValue) / width + minValue; value = Math.max(minValue, Math.min(maxValue, value)); - value = Math.round(value/minStep)*minStep; + value = Math.round(value / minStep) * minStep; setCallback.accept(value); return true; } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/util/MiscUtils.java b/src/main/java/io/github/moulberry/notenoughupdates/core/util/MiscUtils.java index 3e9fc4ca..6e3ad7d1 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/util/MiscUtils.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/util/MiscUtils.java @@ -25,14 +25,15 @@ public class MiscUtils { Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(new StringSelection(str), null); } + private static void unzip(InputStream src, File dest) { //buffer for read and write data to file byte[] buffer = new byte[1024]; try { ZipInputStream zis = new ZipInputStream(src); ZipEntry ze = zis.getNextEntry(); - while(ze != null){ - if(!ze.isDirectory()) { + while (ze != null) { + if (!ze.isDirectory()) { String fileName = ze.getName(); File newFile = new File(dest, fileName); //create directories for sub directories in zip @@ -57,8 +58,8 @@ public class MiscUtils { } public static void recursiveDelete(File file) { - if(file.isDirectory() && !Files.isSymbolicLink(file.toPath())) { - for(File child : file.listFiles()) { + if (file.isDirectory() && !Files.isSymbolicLink(file.toPath())) { + for (File child : file.listFiles()) { recursiveDelete(child); } } @@ -68,15 +69,17 @@ public class MiscUtils { private static String currentCursor = null; public static void resetCursor() { - if(currentCursor == null) { + if (currentCursor == null) { return; } currentCursor = null; - try { Mouse.setNativeCursor(null); } catch(Exception ignored) {} + try { + Mouse.setNativeCursor(null); + } catch (Exception ignored) {} } public static void setCursor(ResourceLocation loc, int hotspotX, int hotspotY) { - if(currentCursor != null && loc.getResourcePath().equals(currentCursor)) { + if (currentCursor != null && loc.getResourcePath().equals(currentCursor)) { return; } currentCursor = loc.getResourcePath(); @@ -84,20 +87,20 @@ public class MiscUtils { BufferedImage image = ImageIO.read(Minecraft.getMinecraft() .getResourceManager().getResource(loc).getInputStream()); int maxSize = Cursor.getMaxCursorSize(); - IntBuffer buffer = BufferUtils.createIntBuffer(maxSize*maxSize); - for(int i=0; i= image.getWidth() || cursorY >= image.getHeight()) { + IntBuffer buffer = BufferUtils.createIntBuffer(maxSize * maxSize); + for (int i = 0; i < maxSize * maxSize; i++) { + int cursorX = i % maxSize; + int cursorY = i / maxSize; + if (cursorX >= image.getWidth() || cursorY >= image.getHeight()) { buffer.put(0x00000000); } else { - buffer.put(image.getRGB(cursorX, image.getHeight()-1-cursorY)); + buffer.put(image.getRGB(cursorX, image.getHeight() - 1 - cursorY)); } } buffer.flip(); Mouse.setNativeCursor(new Cursor(maxSize, maxSize, hotspotX, hotspotY, 1, buffer, null)); - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); } } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/util/Splitters.java b/src/main/java/io/github/moulberry/notenoughupdates/core/util/Splitters.java index 555e0d79..66458e2f 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/util/Splitters.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/util/Splitters.java @@ -6,5 +6,4 @@ public class Splitters { public static final Splitter NEWLINE_SPLITTER = Splitter.on('\n'); - } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/util/StringUtils.java b/src/main/java/io/github/moulberry/notenoughupdates/core/util/StringUtils.java index a3d8204a..80308938 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/util/StringUtils.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/util/StringUtils.java @@ -22,13 +22,13 @@ public class StringUtils { FontRenderer fr = Minecraft.getMinecraft().fontRendererObj; String trim = fr.trimStringToWidth(str, len); - if(str.length() != trim.length() && !trim.endsWith(" ")) { + if (str.length() != trim.length() && !trim.endsWith(" ")) { char next = str.charAt(trim.length()); - if(next != ' ') { + if (next != ' ') { String[] split = trim.split(" "); - String last = split[split.length-1]; - if(last.length() < 8) { - trim = trim.substring(0, trim.length()-last.length()); + String last = split[split.length - 1]; + if (last.length() < 8) { + trim = trim.substring(0, trim.length() - last.length()); } } } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/util/lerp/LerpUtils.java b/src/main/java/io/github/moulberry/notenoughupdates/core/util/lerp/LerpUtils.java index 73287f05..46d00293 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/util/lerp/LerpUtils.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/util/lerp/LerpUtils.java @@ -7,20 +7,20 @@ public class LerpUtils { } public static float sigmoid(float val) { - return (float)(1/(1 + Math.exp(-val))); + return (float) (1 / (1 + Math.exp(-val))); } private static final float sigmoidStr = 8; - private static final float sigmoidA = -1/(sigmoid(-0.5f * sigmoidStr) - sigmoid(0.5f * sigmoidStr)); - private static final float sigmoidB = sigmoidA*sigmoid(-0.5f * sigmoidStr); + private static final float sigmoidA = -1 / (sigmoid(-0.5f * sigmoidStr) - sigmoid(0.5f * sigmoidStr)); + private static final float sigmoidB = sigmoidA * sigmoid(-0.5f * sigmoidStr); + public static float sigmoidZeroOne(float f) { f = clampZeroOne(f); - return sigmoidA*sigmoid(sigmoidStr*(f-0.5f))-sigmoidB; + return sigmoidA * sigmoid(sigmoidStr * (f - 0.5f)) - sigmoidB; } public static float lerp(float a, float b, float amount) { return b + (a - b) * clampZeroOne(amount); } - } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/util/lerp/LerpingFloat.java b/src/main/java/io/github/moulberry/notenoughupdates/core/util/lerp/LerpingFloat.java index 250facfc..afd805f6 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/util/lerp/LerpingFloat.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/util/lerp/LerpingFloat.java @@ -4,7 +4,7 @@ public class LerpingFloat { private int timeSpent; private long lastMillis; - private int timeToReachTarget; + private final int timeToReachTarget; private float targetValue; private float lerpValue; @@ -22,23 +22,23 @@ public class LerpingFloat { int lastTimeSpent = timeSpent; this.timeSpent += System.currentTimeMillis() - lastMillis; - float lastDistPercentToTarget = lastTimeSpent/(float)timeToReachTarget; - float distPercentToTarget = timeSpent/(float)timeToReachTarget; - float fac = (1-lastDistPercentToTarget)/lastDistPercentToTarget; + float lastDistPercentToTarget = lastTimeSpent / (float) timeToReachTarget; + float distPercentToTarget = timeSpent / (float) timeToReachTarget; + float fac = (1 - lastDistPercentToTarget) / lastDistPercentToTarget; - float startValue = lerpValue - (targetValue - lerpValue)/fac; + float startValue = lerpValue - (targetValue - lerpValue) / fac; float dist = targetValue - startValue; - if(dist == 0) return; + if (dist == 0) return; float oldLerpValue = lerpValue; - if(distPercentToTarget >= 1) { + if (distPercentToTarget >= 1) { lerpValue = targetValue; } else { - lerpValue = startValue + dist*distPercentToTarget; + lerpValue = startValue + dist * distPercentToTarget; } - if(lerpValue == oldLerpValue) { + if (lerpValue == oldLerpValue) { timeSpent = lastTimeSpent; } else { this.lastMillis = System.currentTimeMillis(); diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/util/lerp/LerpingInteger.java b/src/main/java/io/github/moulberry/notenoughupdates/core/util/lerp/LerpingInteger.java index b3dd9d6f..cfb44029 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/util/lerp/LerpingInteger.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/util/lerp/LerpingInteger.java @@ -22,23 +22,23 @@ public class LerpingInteger { int lastTimeSpent = timeSpent; this.timeSpent += System.currentTimeMillis() - lastMillis; - float lastDistPercentToTarget = lastTimeSpent/(float)timeToReachTarget; - float distPercentToTarget = timeSpent/(float)timeToReachTarget; - float fac = (1-lastDistPercentToTarget)/lastDistPercentToTarget; + float lastDistPercentToTarget = lastTimeSpent / (float) timeToReachTarget; + float distPercentToTarget = timeSpent / (float) timeToReachTarget; + float fac = (1 - lastDistPercentToTarget) / lastDistPercentToTarget; - int startValue = lerpValue - (int)((targetValue - lerpValue)/fac); + int startValue = lerpValue - (int) ((targetValue - lerpValue) / fac); int dist = targetValue - startValue; - if(dist == 0) return; + if (dist == 0) return; int oldLerpValue = lerpValue; - if(distPercentToTarget >= 1) { + if (distPercentToTarget >= 1) { lerpValue = targetValue; } else { - lerpValue = startValue + (int)(dist*distPercentToTarget); + lerpValue = startValue + (int) (dist * distPercentToTarget); } - if(lerpValue == oldLerpValue) { + if (lerpValue == oldLerpValue) { timeSpent = lastTimeSpent; } else { this.lastMillis = System.currentTimeMillis(); diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/util/render/RenderUtils.java b/src/main/java/io/github/moulberry/notenoughupdates/core/util/render/RenderUtils.java index 5f0ad94f..6d847928 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/util/render/RenderUtils.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/util/render/RenderUtils.java @@ -27,7 +27,7 @@ public class RenderUtils { public static void drawFloatingRectDark(int x, int y, int width, int height, boolean shadow) { int alpha = 0xf0000000; - if(OpenGlHelper.isFramebufferEnabled()) { + if (OpenGlHelper.isFramebufferEnabled()) { ScaledResolution scaledResolution = new ScaledResolution(Minecraft.getMinecraft()); BackgroundBlur.renderBlurredBackground(15, scaledResolution.getScaledWidth(), scaledResolution.getScaledHeight(), x, y, width, height, true); @@ -38,14 +38,14 @@ public class RenderUtils { int main = alpha | 0x202026; int light = 0xff303036; int dark = 0xff101016; - Gui.drawRect(x, y, x+1, y+height, light); //Left - Gui.drawRect(x+1, y, x+width, y+1, light); //Top - Gui.drawRect(x+width-1, y+1, x+width, y+height, dark); //Right - Gui.drawRect(x+1, y+height-1, x+width-1, y+height, dark); //Bottom - Gui.drawRect(x+1, y+1, x+width-1, y+height-1, main); //Middle - if(shadow) { - Gui.drawRect(x+width, y+2, x+width+2, y+height+2, 0x70000000); //Right shadow - Gui.drawRect(x+2, y+height, x+width, y+height+2, 0x70000000); //Bottom shadow + Gui.drawRect(x, y, x + 1, y + height, light); //Left + Gui.drawRect(x + 1, y, x + width, y + 1, light); //Top + Gui.drawRect(x + width - 1, y + 1, x + width, y + height, dark); //Right + Gui.drawRect(x + 1, y + height - 1, x + width - 1, y + height, dark); //Bottom + Gui.drawRect(x + 1, y + 1, x + width - 1, y + height - 1, main); //Middle + if (shadow) { + Gui.drawRect(x + width, y + 2, x + width + 2, y + height + 2, 0x70000000); //Right shadow + Gui.drawRect(x + 2, y + height, x + width, y + height + 2, 0x70000000); //Bottom shadow } } @@ -57,27 +57,27 @@ public class RenderUtils { int main = (alpha << 24) | 0xc0c0c0; int light = (alpha << 24) | 0xf0f0f0; int dark = (alpha << 24) | 0x909090; - Gui.drawRect(x, y, x+1, y+height, light); //Left - Gui.drawRect(x+1, y, x+width, y+1, light); //Top - Gui.drawRect(x+width-1, y+1, x+width, y+height, dark); //Right - Gui.drawRect(x+1, y+height-1, x+width-1, y+height, dark); //Bottom - Gui.drawRect(x+1, y+1, x+width-1, y+height-1, main); //Middle - if(shadow) { - Gui.drawRect(x+width, y+2, x+width+2, y+height+2, (alpha*3/5) << 24); //Right shadow - Gui.drawRect(x+2, y+height, x+width, y+height+2, (alpha*3/5) << 24); //Bottom shadow + Gui.drawRect(x, y, x + 1, y + height, light); //Left + Gui.drawRect(x + 1, y, x + width, y + 1, light); //Top + Gui.drawRect(x + width - 1, y + 1, x + width, y + height, dark); //Right + Gui.drawRect(x + 1, y + height - 1, x + width - 1, y + height, dark); //Bottom + Gui.drawRect(x + 1, y + 1, x + width - 1, y + height - 1, main); //Middle + if (shadow) { + Gui.drawRect(x + width, y + 2, x + width + 2, y + height + 2, (alpha * 3 / 5) << 24); //Right shadow + Gui.drawRect(x + 2, y + height, x + width, y + height + 2, (alpha * 3 / 5) << 24); //Bottom shadow } } public static void drawTexturedRect(float x, float y, float width, float height) { - drawTexturedRect(x, y, width, height, 0, 1, 0 , 1); + drawTexturedRect(x, y, width, height, 0, 1, 0, 1); } public static void drawTexturedRect(float x, float y, float width, float height, int filter) { - drawTexturedRect(x, y, width, height, 0, 1, 0 , 1, filter); + drawTexturedRect(x, y, width, height, 0, 1, 0, 1, filter); } public static void drawTexturedRect(float x, float y, float width, float height, float uMin, float uMax, float vMin, float vMax) { - drawTexturedRect(x, y, width, height, uMin, uMax, vMin , vMax, GL11.GL_NEAREST); + drawTexturedRect(x, y, width, height, uMin, uMax, vMin, vMax, GL11.GL_NEAREST); } public static void drawTexturedRect(float x, float y, float width, float height, float uMin, float uMax, float vMin, float vMax, int filter) { @@ -99,13 +99,13 @@ public class RenderUtils { WorldRenderer worldrenderer = tessellator.getWorldRenderer(); worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); worldrenderer - .pos(x, y+height, 0.0D) + .pos(x, y + height, 0.0D) .tex(uMin, vMax).endVertex(); worldrenderer - .pos(x+width, y+height, 0.0D) + .pos(x + width, y + height, 0.0D) .tex(uMax, vMax).endVertex(); worldrenderer - .pos(x+width, y, 0.0D) + .pos(x + width, y, 0.0D) .tex(uMax, vMin).endVertex(); worldrenderer .pos(x, y, 0.0D) @@ -117,14 +117,14 @@ public class RenderUtils { } public static void drawGradientRect(int zLevel, int left, int top, int right, int bottom, int startColor, int endColor) { - float startAlpha = (float)(startColor >> 24 & 255) / 255.0F; - float startRed = (float)(startColor >> 16 & 255) / 255.0F; - float startGreen = (float)(startColor >> 8 & 255) / 255.0F; - float startBlue = (float)(startColor & 255) / 255.0F; - float endAlpha = (float)(endColor >> 24 & 255) / 255.0F; - float endRed = (float)(endColor >> 16 & 255) / 255.0F; - float endGreen = (float)(endColor >> 8 & 255) / 255.0F; - float endBlue = (float)(endColor & 255) / 255.0F; + float startAlpha = (float) (startColor >> 24 & 255) / 255.0F; + float startRed = (float) (startColor >> 16 & 255) / 255.0F; + float startGreen = (float) (startColor >> 8 & 255) / 255.0F; + float startBlue = (float) (startColor & 255) / 255.0F; + float endAlpha = (float) (endColor >> 24 & 255) / 255.0F; + float endRed = (float) (endColor >> 16 & 255) / 255.0F; + float endGreen = (float) (endColor >> 8 & 255) / 255.0F; + float endBlue = (float) (endColor & 255) / 255.0F; GlStateManager.disableTexture2D(); GlStateManager.enableBlend(); @@ -150,7 +150,7 @@ public class RenderUtils { private static final ResourceLocation beaconBeam = new ResourceLocation("textures/entity/beacon_beam.png"); private static void renderBeaconBeam(double x, double y, double z, int rgb, float alphaMult, - float partialTicks, Boolean disableDepth) { + float partialTicks, Boolean disableDepth) { int height = 300; int bottomOffset = 0; int topOffset = bottomOffset + height; @@ -172,8 +172,8 @@ public class RenderUtils { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); - double time = Minecraft.getMinecraft().theWorld.getTotalWorldTime() + (double)partialTicks; - double d1 = MathHelper.func_181162_h(-time * 0.2D - (double)MathHelper.floor_double(-time * 0.1D)); + double time = Minecraft.getMinecraft().theWorld.getTotalWorldTime() + (double) partialTicks; + double d1 = MathHelper.func_181162_h(-time * 0.2D - (double) MathHelper.floor_double(-time * 0.1D)); float r = ((rgb >> 16) & 0xFF) / 255f; float g = ((rgb >> 8) & 0xFF) / 255f; @@ -188,24 +188,24 @@ public class RenderUtils { double d10 = 0.5D + Math.cos(d2 + 5.497787143782138D) * 0.2D; double d11 = 0.5D + Math.sin(d2 + 5.497787143782138D) * 0.2D; double d14 = -1.0D + d1; - double d15 = (double)(height) * 2.5D + d14; + double d15 = (double) (height) * 2.5D + d14; worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); - worldrenderer.pos(x + d4, y + topOffset, z + d5).tex(1.0D, d15).color(r, g, b, 1.0F*alphaMult).endVertex(); + worldrenderer.pos(x + d4, y + topOffset, z + d5).tex(1.0D, d15).color(r, g, b, 1.0F * alphaMult).endVertex(); worldrenderer.pos(x + d4, y + bottomOffset, z + d5).tex(1.0D, d14).color(r, g, b, 1.0F).endVertex(); worldrenderer.pos(x + d6, y + bottomOffset, z + d7).tex(0.0D, d14).color(r, g, b, 1.0F).endVertex(); - worldrenderer.pos(x + d6, y + topOffset, z + d7).tex(0.0D, d15).color(r, g, b, 1.0F*alphaMult).endVertex(); - worldrenderer.pos(x + d10, y + topOffset, z + d11).tex(1.0D, d15).color(r, g, b, 1.0F*alphaMult).endVertex(); + worldrenderer.pos(x + d6, y + topOffset, z + d7).tex(0.0D, d15).color(r, g, b, 1.0F * alphaMult).endVertex(); + worldrenderer.pos(x + d10, y + topOffset, z + d11).tex(1.0D, d15).color(r, g, b, 1.0F * alphaMult).endVertex(); worldrenderer.pos(x + d10, y + bottomOffset, z + d11).tex(1.0D, d14).color(r, g, b, 1.0F).endVertex(); worldrenderer.pos(x + d8, y + bottomOffset, z + d9).tex(0.0D, d14).color(r, g, b, 1.0F).endVertex(); - worldrenderer.pos(x + d8, y + topOffset, z + d9).tex(0.0D, d15).color(r, g, b, 1.0F*alphaMult).endVertex(); - worldrenderer.pos(x + d6, y + topOffset, z + d7).tex(1.0D, d15).color(r, g, b, 1.0F*alphaMult).endVertex(); + worldrenderer.pos(x + d8, y + topOffset, z + d9).tex(0.0D, d15).color(r, g, b, 1.0F * alphaMult).endVertex(); + worldrenderer.pos(x + d6, y + topOffset, z + d7).tex(1.0D, d15).color(r, g, b, 1.0F * alphaMult).endVertex(); worldrenderer.pos(x + d6, y + bottomOffset, z + d7).tex(1.0D, d14).color(r, g, b, 1.0F).endVertex(); worldrenderer.pos(x + d10, y + bottomOffset, z + d11).tex(0.0D, d14).color(r, g, b, 1.0F).endVertex(); - worldrenderer.pos(x + d10, y + topOffset, z + d11).tex(0.0D, d15).color(r, g, b, 1.0F*alphaMult).endVertex(); - worldrenderer.pos(x + d8, y + topOffset, z + d9).tex(1.0D, d15).color(r, g, b, 1.0F*alphaMult).endVertex(); + worldrenderer.pos(x + d10, y + topOffset, z + d11).tex(0.0D, d15).color(r, g, b, 1.0F * alphaMult).endVertex(); + worldrenderer.pos(x + d8, y + topOffset, z + d9).tex(1.0D, d15).color(r, g, b, 1.0F * alphaMult).endVertex(); worldrenderer.pos(x + d8, y + bottomOffset, z + d9).tex(1.0D, d14).color(r, g, b, 1.0F).endVertex(); worldrenderer.pos(x + d4, y + bottomOffset, z + d5).tex(0.0D, d14).color(r, g, b, 1.0F).endVertex(); - worldrenderer.pos(x + d4, y + topOffset, z + d5).tex(0.0D, d15).color(r, g, b, 1.0F*alphaMult).endVertex(); + worldrenderer.pos(x + d4, y + topOffset, z + d5).tex(0.0D, d15).color(r, g, b, 1.0F * alphaMult).endVertex(); tessellator.draw(); GlStateManager.disableCull(); @@ -213,22 +213,22 @@ public class RenderUtils { double d13 = height + d12; worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); - worldrenderer.pos(x + 0.2D, y + topOffset, z + 0.2D).tex(1.0D, d13).color(r, g, b, 0.25F*alphaMult).endVertex(); + worldrenderer.pos(x + 0.2D, y + topOffset, z + 0.2D).tex(1.0D, d13).color(r, g, b, 0.25F * alphaMult).endVertex(); worldrenderer.pos(x + 0.2D, y + bottomOffset, z + 0.2D).tex(1.0D, d12).color(r, g, b, 0.25F).endVertex(); worldrenderer.pos(x + 0.8D, y + bottomOffset, z + 0.2D).tex(0.0D, d12).color(r, g, b, 0.25F).endVertex(); - worldrenderer.pos(x + 0.8D, y + topOffset, z + 0.2D).tex(0.0D, d13).color(r, g, b, 0.25F*alphaMult).endVertex(); - worldrenderer.pos(x + 0.8D, y + topOffset, z + 0.8D).tex(1.0D, d13).color(r, g, b, 0.25F*alphaMult).endVertex(); + worldrenderer.pos(x + 0.8D, y + topOffset, z + 0.2D).tex(0.0D, d13).color(r, g, b, 0.25F * alphaMult).endVertex(); + worldrenderer.pos(x + 0.8D, y + topOffset, z + 0.8D).tex(1.0D, d13).color(r, g, b, 0.25F * alphaMult).endVertex(); worldrenderer.pos(x + 0.8D, y + bottomOffset, z + 0.8D).tex(1.0D, d12).color(r, g, b, 0.25F).endVertex(); worldrenderer.pos(x + 0.2D, y + bottomOffset, z + 0.8D).tex(0.0D, d12).color(r, g, b, 0.25F).endVertex(); - worldrenderer.pos(x + 0.2D, y + topOffset, z + 0.8D).tex(0.0D, d13).color(r, g, b, 0.25F*alphaMult).endVertex(); - worldrenderer.pos(x + 0.8D, y + topOffset, z + 0.2D).tex(1.0D, d13).color(r, g, b, 0.25F*alphaMult).endVertex(); + worldrenderer.pos(x + 0.2D, y + topOffset, z + 0.8D).tex(0.0D, d13).color(r, g, b, 0.25F * alphaMult).endVertex(); + worldrenderer.pos(x + 0.8D, y + topOffset, z + 0.2D).tex(1.0D, d13).color(r, g, b, 0.25F * alphaMult).endVertex(); worldrenderer.pos(x + 0.8D, y + bottomOffset, z + 0.2D).tex(1.0D, d12).color(r, g, b, 0.25F).endVertex(); worldrenderer.pos(x + 0.8D, y + bottomOffset, z + 0.8D).tex(0.0D, d12).color(r, g, b, 0.25F).endVertex(); - worldrenderer.pos(x + 0.8D, y + topOffset, z + 0.8D).tex(0.0D, d13).color(r, g, b, 0.25F*alphaMult).endVertex(); - worldrenderer.pos(x + 0.2D, y + topOffset, z + 0.8D).tex(1.0D, d13).color(r, g, b, 0.25F*alphaMult).endVertex(); + worldrenderer.pos(x + 0.8D, y + topOffset, z + 0.8D).tex(0.0D, d13).color(r, g, b, 0.25F * alphaMult).endVertex(); + worldrenderer.pos(x + 0.2D, y + topOffset, z + 0.8D).tex(1.0D, d13).color(r, g, b, 0.25F * alphaMult).endVertex(); worldrenderer.pos(x + 0.2D, y + bottomOffset, z + 0.8D).tex(1.0D, d12).color(r, g, b, 0.25F).endVertex(); worldrenderer.pos(x + 0.2D, y + bottomOffset, z + 0.2D).tex(0.0D, d12).color(r, g, b, 0.25F).endVertex(); - worldrenderer.pos(x + 0.2D, y + topOffset, z + 0.2D).tex(0.0D, d13).color(r, g, b, 0.25F*alphaMult).endVertex(); + worldrenderer.pos(x + 0.2D, y + topOffset, z + 0.2D).tex(0.0D, d13).color(r, g, b, 0.25F * alphaMult).endVertex(); tessellator.draw(); GlStateManager.disableLighting(); @@ -239,7 +239,7 @@ public class RenderUtils { } private static void renderBoundingBox(double x, double y, double z, int rgb, float alphaMult, float partialTicks) { - AxisAlignedBB bb = new AxisAlignedBB(x, y, z, x+1, y+1, z+1); + AxisAlignedBB bb = new AxisAlignedBB(x, y, z, x + 1, y + 1, z + 1); GlStateManager.disableDepth(); GlStateManager.disableCull(); @@ -256,7 +256,7 @@ public class RenderUtils { double viewerZ; Vector3f aoteInterpPos = CustomItemEffects.INSTANCE.getCurrentPosition(); - if(aoteInterpPos != null) { + if (aoteInterpPos != null) { viewerX = aoteInterpPos.x; viewerY = aoteInterpPos.y; viewerZ = aoteInterpPos.z; @@ -271,13 +271,9 @@ public class RenderUtils { double y = block.getY() - viewerY; double z = block.getZ() - viewerZ; - double distSq = x*x + y*y + z*z; + double distSq = x * x + y * y + z * z; - if(distSq > 10*10) { - RenderUtils.renderBeaconBeam(x, y, z, rgb, 1.0f, partialTicks, true); - } else { - RenderUtils.renderBeaconBeam(x, y, z, rgb, 1.0f, partialTicks, false); - } + RenderUtils.renderBeaconBeam(x, y, z, rgb, 1.0f, partialTicks, distSq > 10 * 10); } public static void renderBeaconBeamOrBoundingBox(BlockPos block, int rgb, float alphaMult, float partialTicks) { @@ -286,7 +282,7 @@ public class RenderUtils { double viewerZ; Vector3f aoteInterpPos = CustomItemEffects.INSTANCE.getCurrentPosition(); - if(aoteInterpPos != null) { + if (aoteInterpPos != null) { viewerX = aoteInterpPos.x; viewerY = aoteInterpPos.y; viewerZ = aoteInterpPos.z; @@ -301,9 +297,9 @@ public class RenderUtils { double y = block.getY() - viewerY; double z = block.getZ() - viewerZ; - double distSq = x*x + y*y + z*z; + double distSq = x * x + y * y + z * z; - if(distSq > 10*10) { + if (distSq > 10 * 10) { RenderUtils.renderBeaconBeam(x, y, z, rgb, 1.0f, partialTicks, true); } else { RenderUtils.renderBoundingBox(x, y, z, rgb, 1.0f, partialTicks); @@ -324,16 +320,16 @@ public class RenderUtils { double viewerY = viewer.lastTickPosY + (viewer.posY - viewer.lastTickPosY) * partialTicks; double viewerZ = viewer.lastTickPosZ + (viewer.posZ - viewer.lastTickPosZ) * partialTicks; - double x = loc.x-viewerX+0.5f; - double y = loc.y-viewerY-viewer.getEyeHeight(); - double z = loc.z-viewerZ+0.5f; + double x = loc.x - viewerX + 0.5f; + double y = loc.y - viewerY - viewer.getEyeHeight(); + double z = loc.z - viewerZ + 0.5f; - double distSq = x*x + y*y + z*z; + double distSq = x * x + y * y + z * z; double dist = Math.sqrt(distSq); - if(distSq > 144) { - x *= 12/dist; - y *= 12/dist; - z *= 12/dist; + if (distSq > 144) { + x *= 12 / dist; + y *= 12 / dist; + z *= 12 / dist; } GlStateManager.translate(x, y, z); GlStateManager.translate(0, viewer.getEyeHeight(), 0); @@ -346,7 +342,7 @@ public class RenderUtils { GlStateManager.rotate(-Minecraft.getMinecraft().getRenderManager().playerViewX, 1.0F, 0.0F, 0.0F); GlStateManager.rotate(Minecraft.getMinecraft().getRenderManager().playerViewY, 0.0F, 1.0F, 0.0F); - renderNametag(EnumChatFormatting.YELLOW.toString()+Math.round(dist)+"m"); + renderNametag(EnumChatFormatting.YELLOW.toString() + Math.round(dist) + "m"); GlStateManager.popMatrix(); @@ -374,10 +370,10 @@ public class RenderUtils { int j = fontrenderer.getStringWidth(str) / 2; GlStateManager.disableTexture2D(); worldrenderer.begin(7, DefaultVertexFormats.POSITION_COLOR); - worldrenderer.pos((double)(-j - 1), (double)(-1 + i), 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex(); - worldrenderer.pos((double)(-j - 1), (double)(8 + i), 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex(); - worldrenderer.pos((double)(j + 1), (double)(8 + i), 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex(); - worldrenderer.pos((double)(j + 1), (double)(-1 + i), 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex(); + worldrenderer.pos(-j - 1, -1 + i, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex(); + worldrenderer.pos(-j - 1, 8 + i, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex(); + worldrenderer.pos(j + 1, 8 + i, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex(); + worldrenderer.pos(j + 1, -1 + i, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex(); tessellator.draw(); GlStateManager.enableTexture2D(); fontrenderer.drawString(str, -fontrenderer.getStringWidth(str) / 2, i, 553648127); diff --git a/src/main/java/io/github/moulberry/notenoughupdates/core/util/render/TextRenderUtils.java b/src/main/java/io/github/moulberry/notenoughupdates/core/util/render/TextRenderUtils.java index 541fd67a..9a3ac351 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/core/util/render/TextRenderUtils.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/core/util/render/TextRenderUtils.java @@ -15,7 +15,7 @@ import java.util.List; public class TextRenderUtils { public static int getCharVertLen(char c) { - if("acegmnopqrsuvwxyz".indexOf(c) >= 0) { + if ("acegmnopqrsuvwxyz".indexOf(c) >= 0) { return 5; } else { return 7; @@ -25,9 +25,9 @@ public class TextRenderUtils { public static float getVerticalHeight(String str) { str = StringUtils.cleanColour(str); float height = 0; - for(int i=0; i textLines, final int mouseX, final int mouseY, final int screenWidth, final int screenHeight, final int maxTextWidth, FontRenderer font) { @@ -139,7 +139,7 @@ public class TextRenderUtils { if (needsWrap) { int wrappedTooltipWidth = 0; - List wrappedTextLines = new ArrayList(); + List wrappedTextLines = new ArrayList<>(); for (int i = 0; i < textLines.size(); i++) { String textLine = textLines.get(i); List wrappedLine = font.listFormattedStringToWidth(textLine, tooltipTextWidth); diff --git a/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/CapeManager.java b/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/CapeManager.java index 0ec52ec8..d1344150 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/CapeManager.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/CapeManager.java @@ -2,33 +2,23 @@ package io.github.moulberry.notenoughupdates.cosmetics; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; -import com.google.common.collect.Maps; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import io.github.moulberry.notenoughupdates.NEUManager; import io.github.moulberry.notenoughupdates.NotEnoughUpdates; -import io.github.moulberry.notenoughupdates.util.HypixelApi; import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.shader.Framebuffer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.potion.Potion; import net.minecraftforge.client.event.RenderPlayerEvent; -import net.minecraftforge.client.event.RenderWorldEvent; -import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; -import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; -import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL30; -import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Set; @@ -42,11 +32,11 @@ public class CapeManager { public long lastCapeSynced = 0; public Pair localCape = null; - private HashMap> capeMap = new HashMap<>(); + private final HashMap> capeMap = new HashMap<>(); private int permSyncTries = 5; private boolean allAvailable = false; - private HashSet availableCapes = new HashSet<>(); + private final HashSet availableCapes = new HashSet<>(); public JsonObject lastJsonSync = null; @@ -114,7 +104,6 @@ public class CapeManager { new CapeData("tunnel", false, false), new CapeData("planets", false, false) - }; /*private String[] capes = new String[]{"patreon1", "patreon2", "fade", "contrib", "nullzee", @@ -129,8 +118,8 @@ public class CapeManager { } public void tryUnlockCape(String unlock) { - for(CapeData data : capes) { - if(data.capeName.equalsIgnoreCase(unlock)) { + for (CapeData data : capes) { + if (data.capeName.equalsIgnoreCase(unlock)) { data.hidden = false; } } @@ -138,7 +127,7 @@ public class CapeManager { public void tick() { long currentTime = System.currentTimeMillis(); - if(currentTime - lastCapeUpdate > 60*1000) { + if (currentTime - lastCapeUpdate > 60 * 1000) { lastCapeUpdate = currentTime; updateCapes(); } @@ -147,38 +136,36 @@ public class CapeManager { private void updateCapes() { NotEnoughUpdates.INSTANCE.manager.hypixelApi.getMyApiAsync("activecapes.json", (jsonObject) -> { - if(jsonObject.get("success").getAsBoolean()) { + if (jsonObject.get("success").getAsBoolean()) { lastJsonSync = jsonObject; lastCapeSynced = System.currentTimeMillis(); capeMap.clear(); - for(JsonElement active : jsonObject.get("active").getAsJsonArray()) { - if(active.isJsonObject()) { + for (JsonElement active : jsonObject.get("active").getAsJsonArray()) { + if (active.isJsonObject()) { JsonObject activeObj = (JsonObject) active; setCape(activeObj.get("_id").getAsString(), activeObj.get("capeType").getAsString(), false); } } } - }, () -> { - System.out.println("[MBAPI] Update capes errored"); - }); + }, () -> System.out.println("[MBAPI] Update capes errored")); - if(Minecraft.getMinecraft().thePlayer != null && permSyncTries > 0) { + if (Minecraft.getMinecraft().thePlayer != null && permSyncTries > 0) { String uuid = Minecraft.getMinecraft().thePlayer.getUniqueID().toString().replace("-", ""); permSyncTries--; NotEnoughUpdates.INSTANCE.manager.hypixelApi.getMyApiAsync("permscapes.json", (jsonObject) -> { - if(jsonObject.get("success").getAsBoolean()) { + if (jsonObject.get("success").getAsBoolean()) { permSyncTries = 0; availableCapes.clear(); - for(JsonElement permPlayer : jsonObject.get("perms").getAsJsonArray()) { - if(permPlayer.isJsonObject()) { + for (JsonElement permPlayer : jsonObject.get("perms").getAsJsonArray()) { + if (permPlayer.isJsonObject()) { String playerUuid = permPlayer.getAsJsonObject().get("_id").getAsString(); - if(playerUuid != null && playerUuid.equals(uuid)) { - for(JsonElement perm : permPlayer.getAsJsonObject().get("perms").getAsJsonArray()) { - if(perm.isJsonPrimitive()) { + if (playerUuid != null && playerUuid.equals(uuid)) { + for (JsonElement perm : permPlayer.getAsJsonObject().get("perms").getAsJsonArray()) { + if (perm.isJsonPrimitive()) { String cape = perm.getAsString(); - if(cape.equals("*")) { + if (cape.equals("*")) { allAvailable = true; } else { availableCapes.add(cape); @@ -190,9 +177,7 @@ public class CapeManager { } } } - }, () -> { - System.out.println("[MBAPI] Update capes errored - perms"); - }); + }, () -> System.out.println("[MBAPI] Update capes errored - perms")); } } @@ -204,30 +189,30 @@ public class CapeManager { boolean none = capename == null || capename.equals("null"); updateConfig = updateConfig && playerUUID.equals(Minecraft.getMinecraft().thePlayer.getUniqueID().toString().replace("-", "")); - if(updateConfig) { + if (updateConfig) { NotEnoughUpdates.INSTANCE.config.hidden.selectedCape = String.valueOf(capename); } - if(updateConfig) { - if(none) { + if (updateConfig) { + if (none) { localCape = null; } else { localCape = new MutablePair<>(new NEUCape(capename), capename); } - } else if(capeMap.containsKey(playerUUID)) { - if(none) { + } else if (capeMap.containsKey(playerUUID)) { + if (none) { capeMap.remove(playerUUID); } else { Pair capePair = capeMap.get(playerUUID); capePair.setValue(capename); } - } else if(!none) { + } else if (!none) { capeMap.put(playerUUID, new MutablePair<>(new NEUCape(capename), capename)); } } public String getCape(String player) { - if(capeMap.containsKey(player)) { + if (capeMap.containsKey(player)) { return capeMap.get(player).getRight(); } return null; @@ -236,18 +221,18 @@ public class CapeManager { private static BiMap playerMap = null; public EntityPlayer getPlayerForUUID(String uuid) { - if(playerMap == null) { + if (playerMap == null) { return null; } - if(playerMap.containsKey(uuid)) { + if (playerMap.containsKey(uuid)) { return playerMap.get(uuid); } return null; } private static Framebuffer checkFramebufferSizes(Framebuffer framebuffer, int width, int height) { - if(framebuffer == null || framebuffer.framebufferWidth != width || framebuffer.framebufferHeight != height) { - if(framebuffer == null) { + if (framebuffer == null || framebuffer.framebufferWidth != width || framebuffer.framebufferHeight != height) { + if (framebuffer == null) { framebuffer = new Framebuffer(width, height, true); } else { framebuffer.createBindFramebuffer(width, height); @@ -266,7 +251,7 @@ public class CapeManager { backgroundFramebuffer = checkFramebufferSizes(backgroundFramebuffer, width, height); - if(OpenGlHelper.isFramebufferEnabled() && updateWorldFramebuffer) { + if (OpenGlHelper.isFramebufferEnabled() && updateWorldFramebuffer) { GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, Minecraft.getMinecraft().getFramebuffer().framebufferObject); GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, backgroundFramebuffer.framebufferObject); GL30.glBlitFramebuffer(0, 0, width, height, @@ -281,47 +266,48 @@ public class CapeManager { @SubscribeEvent public void onWorldLoad(WorldEvent.Unload event) { - if(playerMap != null) playerMap.clear(); + if (playerMap != null) playerMap.clear(); } @SubscribeEvent public void onRenderPlayer(RenderPlayerEvent.Post e) { - if(e.partialRenderTick == 1.0F) return; //rendering in inventory + if (e.partialRenderTick == 1.0F) return; //rendering in inventory try { String uuid = e.entityPlayer.getUniqueID().toString().replace("-", ""); String clientUuid = Minecraft.getMinecraft().thePlayer.getUniqueID().toString().replace("-", ""); - if(Minecraft.getMinecraft().thePlayer != null && uuid.equals(clientUuid)) { + if (Minecraft.getMinecraft().thePlayer != null && uuid.equals(clientUuid)) { String selCape = NotEnoughUpdates.INSTANCE.config.hidden.selectedCape; - if(selCape != null && !selCape.isEmpty()) { - if(localCape == null) { + if (selCape != null && !selCape.isEmpty()) { + if (localCape == null) { localCape = new MutablePair<>(new NEUCape(selCape), selCape); } else { localCape.setValue(selCape); } } } - if(uuid.equals(clientUuid) && localCape != null && localCape.getRight() != null && !localCape.getRight().equals("null")) { + if (uuid.equals(clientUuid) && localCape != null && localCape.getRight() != null && !localCape.getRight().equals("null")) { localCape.getLeft().onRenderPlayer(e); - } else if(!Minecraft.getMinecraft().thePlayer.isPotionActive(Potion.blindness) && capeMap.containsKey(uuid)) { + } else if (!Minecraft.getMinecraft().thePlayer.isPotionActive(Potion.blindness) && capeMap.containsKey(uuid)) { capeMap.get(uuid).getLeft().onRenderPlayer(e); } - } catch(Exception ignored) {} + } catch (Exception ignored) { + } } public static void onTickSlow() { - if(Minecraft.getMinecraft().theWorld == null) return; + if (Minecraft.getMinecraft().theWorld == null) return; - if(playerMap == null) { + if (playerMap == null) { playerMap = HashBiMap.create(Minecraft.getMinecraft().theWorld.playerEntities.size()); } playerMap.clear(); - for(EntityPlayer player : Minecraft.getMinecraft().theWorld.playerEntities) { + for (EntityPlayer player : Minecraft.getMinecraft().theWorld.playerEntities) { String uuid = player.getUniqueID().toString().replace("-", ""); try { playerMap.put(uuid, player); - } catch(IllegalArgumentException ignored){} + } catch (IllegalArgumentException ignored) {} } } @@ -330,14 +316,14 @@ public class CapeManager { @SubscribeEvent public void onTick(TickEvent.ClientTickEvent event) { if (event.phase != TickEvent.Phase.END) return; - if(Minecraft.getMinecraft().theWorld == null) return; + if (Minecraft.getMinecraft().theWorld == null) return; - if(playerMap == null) { + if (playerMap == null) { return; } String clientUuid = null; - if(Minecraft.getMinecraft().thePlayer != null) { + if (Minecraft.getMinecraft().thePlayer != null) { clientUuid = Minecraft.getMinecraft().thePlayer.getUniqueID().toString().replace("-", ""); } @@ -345,37 +331,33 @@ public class CapeManager { Set toRemove = new HashSet<>(); try { - for(String playerUUID : capeMap.keySet()) { + for (String playerUUID : capeMap.keySet()) { EntityPlayer player; - if(playerUUID.equals(clientUuid)) { + if (playerUUID.equals(clientUuid)) { player = Minecraft.getMinecraft().thePlayer; } else { player = getPlayerForUUID(playerUUID); } - if(player != null) { + if (player != null) { String capeName = capeMap.get(playerUUID).getRight(); - if(capeName != null && !capeName.equals("null")) { - if(player == Minecraft.getMinecraft().thePlayer && hasLocalCape) { + if (capeName != null && !capeName.equals("null")) { + if (player == Minecraft.getMinecraft().thePlayer && hasLocalCape) { continue; } capeMap.get(playerUUID).getLeft().setCapeTexture(capeName); - capeTicker.submit(() -> { - capeMap.get(playerUUID).getLeft().onTick(event, player); - }); + capeTicker.submit(() -> capeMap.get(playerUUID).getLeft().onTick(event, player)); } else { toRemove.add(playerUUID); } } } - } catch(Exception e) {} + } catch (Exception ignored) {} - if(hasLocalCape) { + if (hasLocalCape) { localCape.getLeft().setCapeTexture(localCape.getValue()); - capeTicker.submit(() -> { - localCape.getLeft().onTick(event, Minecraft.getMinecraft().thePlayer); - }); + capeTicker.submit(() -> localCape.getLeft().onTick(event, Minecraft.getMinecraft().thePlayer)); } - for(String playerName : toRemove) { + for (String playerName : toRemove) { capeMap.remove(playerName); } } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/CapeNode.java b/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/CapeNode.java index 06bc6db4..0ab08706 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/CapeNode.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/CapeNode.java @@ -1,14 +1,8 @@ package io.github.moulberry.notenoughupdates.cosmetics; -import net.minecraft.block.Block; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; -import net.minecraft.util.BlockPos; -import net.minecraft.util.MathHelper; -import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; import org.lwjgl.util.vector.Vector2f; import org.lwjgl.util.vector.Vector3f; @@ -60,13 +54,13 @@ public class CapeNode { private List getConstaints() { List constaints = new ArrayList<>(); - for(NEUCape.Direction cardinal : cardinals) { - for(int i=1; i<=2; i++) { + for (NEUCape.Direction cardinal : cardinals) { + for (int i = 1; i <= 2; i++) { NEUCape.Offset offset = new NEUCape.Offset(cardinal, i); CapeNode other = neighbors.get(offset); - if(other != null) { + if (other != null) { int iOffset = offset.getXOffset() + NEUCape.HORZ_NODES * offset.getYOffset(); - constaints.add(new Vector2f(iOffset, i*NEUCape.targetDist*(cardinal.yOff==0?horzDistMult:vertDistMult))); + constaints.add(new Vector2f(iOffset, i * NEUCape.targetDist * (cardinal.yOff == 0 ? horzDistMult : vertDistMult))); } } @@ -78,8 +72,8 @@ public class CapeNode { loadVec3IntoBuffer(buffer, position); List containts = getConstaints(); buffer.put(containts.size()); - for(int i=0; i<8; i++) { - if(i < containts.size()) { + for (int i = 0; i < 8; i++) { + if (i < containts.size()) { loadVec2IntoBuffer(buffer, containts.get(i)); } else { loadVec2IntoBuffer(buffer, new Vector2f()); @@ -89,7 +83,7 @@ public class CapeNode { public void readFromBuffer(FloatBuffer buffer) { readVec3FromBuffer(buffer, position); - buffer.position(buffer.position()+17); + buffer.position(buffer.position() + 17); } private void readVec3FromBuffer(FloatBuffer buffer, Vector3f vec) { @@ -110,8 +104,8 @@ public class CapeNode { } public void update() { - if(!fixed) { - velocity.y -= gravity * (resistance)/(1-resistance); + if (!fixed) { + velocity.y -= gravity * (resistance) / (1 - resistance); float actualResistance = resistance; /*BlockPos pos = new BlockPos( @@ -123,7 +117,7 @@ public class CapeNode { actualResistance = 0.8f; }*/ - velocity.scale(1-actualResistance); + velocity.scale(1 - actualResistance); Vector3f.add(position, velocity, position); } @@ -168,28 +162,28 @@ public class CapeNode { double dY = position.y - other.position.y; double dZ = position.z - other.position.z; - double distSq = dX*dX + dY*dY + dZ*dZ; + double distSq = dX * dX + dY * dY + dZ * dZ; - double factor = (distSq - targetDist*targetDist)/(40*distSq)*strength; + double factor = (distSq - targetDist * targetDist) / (40 * distSq) * strength; factor = Math.max(-0.5f, factor); dX *= factor; dY *= factor; dZ *= factor; - if(fixed || other.fixed) { + if (fixed || other.fixed) { dX *= 2; dY *= 2; dZ *= 2; } - if(!fixed) { + if (!fixed) { position.x -= dX; position.y -= dY; position.z -= dZ; } - if(!other.fixed) { + if (!other.fixed) { other.position.x += dX; other.position.y += dY; other.position.z += dZ; @@ -197,46 +191,46 @@ public class CapeNode { } public void resolveStruct(float horzDistMult, boolean opt) { - for(NEUCape.Direction cardinal : cardinals) { + for (NEUCape.Direction cardinal : cardinals) { NEUCape.Offset offset = new NEUCape.Offset(cardinal, 1); CapeNode other = neighbors.get(offset); - if(other != null) { - resolve(other, NEUCape.targetDist*(cardinal.yOff==0?horzDistMult:1), 2f*7.5f, opt); + if (other != null) { + resolve(other, NEUCape.targetDist * (cardinal.yOff == 0 ? horzDistMult : 1), 2f * 7.5f, opt); } } } public void resolveShear(float horzDistMult, boolean opt) { - for(NEUCape.Direction d : new NEUCape.Direction[]{NEUCape.Direction.DOWNLEFT, NEUCape.Direction.UPLEFT, NEUCape.Direction.DOWNRIGHT, NEUCape.Direction.DOWNLEFT}) { + for (NEUCape.Direction d : new NEUCape.Direction[]{NEUCape.Direction.DOWNLEFT, NEUCape.Direction.UPLEFT, NEUCape.Direction.DOWNRIGHT, NEUCape.Direction.DOWNLEFT}) { NEUCape.Offset o = new NEUCape.Offset(d, 1); CapeNode neighbor = getNeighbor(o); - if(neighbor != null) { - resolve(neighbor, 1f*NEUCape.targetDist*(d.yOff==0?horzDistMult:1f), 0.5f*7.5f, opt); + if (neighbor != null) { + resolve(neighbor, 1f * NEUCape.targetDist * (d.yOff == 0 ? horzDistMult : 1f), 0.5f * 7.5f, opt); } } } public void resolveBend(float horzDistMult, boolean opt) { - for(NEUCape.Direction cardinal : cardinals) { + for (NEUCape.Direction cardinal : cardinals) { NEUCape.Offset offset = new NEUCape.Offset(cardinal, 2); CapeNode other = neighbors.get(offset); - if(other != null) { - resolve(other, 2f*NEUCape.targetDist*(cardinal.yOff==0?horzDistMult:1), 1f*7.5f, opt); + if (other != null) { + resolve(other, 2f * NEUCape.targetDist * (cardinal.yOff == 0 ? horzDistMult : 1), 1f * 7.5f, opt); } } } public Vector3f normal() { - if(normal != null) return normal; + if (normal != null) return normal; normal = new Vector3f(); - for(int i=0; i cosmeticsInfoTooltip = null; - - - public GuiCosmetics(){ + public GuiCosmetics() { Gson gson = new Gson(); JsonElement cosmeticHelpTextElement = Utils.getElement(Constants.MISC, "cosmeticsinfo.lore"); - if(cosmeticHelpTextElement.isJsonArray()) { - cosmeticsInfoTooltip = gson.fromJson(cosmeticHelpTextElement, new TypeToken>(){}.getType()); + if (cosmeticHelpTextElement.isJsonArray()) { + cosmeticsInfoTooltip = gson.fromJson(cosmeticHelpTextElement, new TypeToken>() {}.getType()); } } @@ -76,14 +74,14 @@ public class GuiCosmetics extends GuiScreen { public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.sizeX = 431; this.sizeY = 202; - this.guiLeft = (this.width-this.sizeX)/2; - this.guiTop = (this.height-this.sizeY)/2; + this.guiLeft = (this.width - this.sizeX) / 2; + this.guiTop = (this.height - this.sizeY) / 2; super.drawScreen(mouseX, mouseY, partialTicks); drawDefaultBackground(); blurBackground(); - renderBlurredBackground(width, height, guiLeft+2, guiTop+2, sizeX-4, sizeY-4); + renderBlurredBackground(width, height, guiLeft + 2, guiTop + 2, sizeX - 4, sizeY - 4); GlStateManager.enableDepth(); GlStateManager.translate(0, 0, 5); @@ -111,9 +109,9 @@ public class GuiCosmetics extends GuiScreen { drawCapesPage(mouseX, mouseY, partialTicks); break; } - int helpX = guiLeft+sizeX-20; - if(mouseX >= helpX && mouseX <= helpX+20 && mouseY >= guiTop-20 && mouseY <= guiTop) { - if(cosmeticsInfoTooltip != null) { + int helpX = guiLeft + sizeX - 20; + if (mouseX >= helpX && mouseX <= helpX + 20 && mouseY >= guiTop - 20 && mouseY <= guiTop) { + if (cosmeticsInfoTooltip != null) { List grayTooltip = new ArrayList<>(cosmeticsInfoTooltip.size()); for (String line : cosmeticsInfoTooltip) { grayTooltip.add(EnumChatFormatting.GRAY + line); @@ -124,75 +122,66 @@ public class GuiCosmetics extends GuiScreen { } StringBuilder statusMsg = new StringBuilder("Last Sync: "); - if(CapeManager.INSTANCE.lastCapeSynced == 0) { + if (CapeManager.INSTANCE.lastCapeSynced == 0) { statusMsg.append("Not Synced"); } else { - statusMsg.append((System.currentTimeMillis() - CapeManager.INSTANCE.lastCapeSynced)/1000).append("s ago"); + statusMsg.append((System.currentTimeMillis() - CapeManager.INSTANCE.lastCapeSynced) / 1000).append("s ago"); } statusMsg.append(" - Next Sync: "); - if(CapeManager.INSTANCE.lastCapeUpdate == 0) { + if (CapeManager.INSTANCE.lastCapeUpdate == 0) { statusMsg.append("ASAP"); } else { - statusMsg.append(60 - (System.currentTimeMillis() - CapeManager.INSTANCE.lastCapeUpdate)/1000).append("s"); + statusMsg.append(60 - (System.currentTimeMillis() - CapeManager.INSTANCE.lastCapeUpdate) / 1000).append("s"); } - Minecraft.getMinecraft().fontRendererObj.drawString(EnumChatFormatting.AQUA+statusMsg.toString(), - guiLeft+sizeX-Minecraft.getMinecraft().fontRendererObj.getStringWidth(statusMsg.toString())-20, guiTop-12, 0, true); + Minecraft.getMinecraft().fontRendererObj.drawString(EnumChatFormatting.AQUA + statusMsg.toString(), + guiLeft + sizeX - Minecraft.getMinecraft().fontRendererObj.getStringWidth(statusMsg.toString()) - 20, guiTop - 12, 0, true); - if(currentPage == CosmeticsPage.CAPES) { + if (currentPage == CosmeticsPage.CAPES) { GlStateManager.color(1, 1, 1, 1); Minecraft.getMinecraft().getTextureManager().bindTexture(pv_dropdown); - Utils.drawTexturedRect(guiLeft+sizeX/2f-50, guiTop+sizeY+5, 100, 20, 0, 100/200f, 0, 20/185f, GL11.GL_NEAREST); + Utils.drawTexturedRect(guiLeft + sizeX / 2f - 50, guiTop + sizeY + 5, 100, 20, 0, 100 / 200f, 0, 20 / 185f, GL11.GL_NEAREST); String equipMsg; - if(wantToEquipCape != null) { + if (wantToEquipCape != null) { equipMsg = EnumChatFormatting.GREEN + "Equip Cape"; - if(System.currentTimeMillis() - lastCapeEquip < 20*1000) { - equipMsg += " - " + (20 - (System.currentTimeMillis() - lastCapeEquip)/1000) + "s"; - } } else { equipMsg = EnumChatFormatting.GREEN + "Unequip"; - if(System.currentTimeMillis() - lastCapeEquip < 20*1000) { - equipMsg += " - " + (20 - (System.currentTimeMillis() - lastCapeEquip)/1000) + "s"; - } + } + if (System.currentTimeMillis() - lastCapeEquip < 20 * 1000) { + equipMsg += " - " + (20 - (System.currentTimeMillis() - lastCapeEquip) / 1000) + "s"; } Utils.drawStringCenteredScaledMaxWidth(equipMsg, Minecraft.getMinecraft().fontRendererObj, - guiLeft+sizeX/2f, guiTop+sizeY+5+10, false, 90, 0); + guiLeft + sizeX / 2f, guiTop + sizeY + 5 + 10, false, 90, 0); } - if(unlockTextField.getFocus() || !unlockTextField.getText().isEmpty()) { + if (unlockTextField.getFocus() || !unlockTextField.getText().isEmpty()) { unlockTextField.setPrependText(""); } else { unlockTextField.setPrependText("\u00a77Creator Code"); } unlockTextField.setSize(80, 20); - unlockTextField.render(guiLeft+sizeX-80, guiTop+sizeY+2); - - - + unlockTextField.render(guiLeft + sizeX - 80, guiTop + sizeY + 2); Minecraft.getMinecraft().getTextureManager().bindTexture(GuiTextures.help); GlStateManager.color(1, 1, 1, 1); - Utils.drawTexturedRect(helpX, guiTop-20, 20, 20, GL11.GL_LINEAR); - - - + Utils.drawTexturedRect(helpX, guiTop - 20, 20, 20, GL11.GL_LINEAR); } private void renderTabs(boolean renderPressed) { int ignoredTabs = 0; - for(int i = 0; i< CosmeticsPage.values().length; i++) { + for (int i = 0; i < CosmeticsPage.values().length; i++) { CosmeticsPage page = CosmeticsPage.values()[i]; - if(page.stack == null) { + if (page.stack == null) { ignoredTabs++; continue; } boolean pressed = page == currentPage; - if(pressed == renderPressed) { - renderTab(page.stack, i-ignoredTabs, pressed); + if (pressed == renderPressed) { + renderTab(page.stack, i - ignoredTabs, pressed); } } } @@ -204,25 +193,25 @@ public class GuiCosmetics extends GuiScreen { GlStateManager.enableAlpha(); GlStateManager.alphaFunc(516, 0.1F); - int x = guiLeft+xIndex*28; - int y = guiTop-28; + int x = guiLeft + xIndex * 28; + int y = guiTop - 28; float uMin = 0; - float uMax = 28/256f; - float vMin = 20/256f; - float vMax = 51/256f; - if(pressed) { - vMin = 52/256f; - vMax = 84/256f; - - if(xIndex != 0) { - uMin = 28/256f; - uMax = 56/256f; + float uMax = 28 / 256f; + float vMin = 20 / 256f; + float vMax = 51 / 256f; + if (pressed) { + vMin = 52 / 256f; + vMax = 84 / 256f; + + if (xIndex != 0) { + uMin = 28 / 256f; + uMax = 56 / 256f; } - renderBlurredBackground(width, height, x+2, y+2, 28-4, 28-4); + renderBlurredBackground(width, height, x + 2, y + 2, 28 - 4, 28 - 4); } else { - renderBlurredBackground(width, height, x+2, y+4, 28-4, 28-4); + renderBlurredBackground(width, height, x + 2, y + 4, 28 - 4, 28 - 4); } GlStateManager.disableLighting(); @@ -232,16 +221,16 @@ public class GuiCosmetics extends GuiScreen { GlStateManager.alphaFunc(516, 0.1F); Minecraft.getMinecraft().getTextureManager().bindTexture(pv_elements); - Utils.drawTexturedRect(x, y, 28, pressed?32:31, uMin, uMax, vMin, vMax, GL11.GL_NEAREST); + Utils.drawTexturedRect(x, y, 28, pressed ? 32 : 31, uMin, uMax, vMin, vMax, GL11.GL_NEAREST); GlStateManager.enableDepth(); - Utils.drawItemStack(stack, x+6, y+9); + Utils.drawItemStack(stack, x + 6, y + 9); } @Override protected void keyTyped(char typedChar, int keyCode) throws IOException { - if(unlockTextField.getFocus()) { - if(keyCode == Keyboard.KEY_ESCAPE || keyCode == Keyboard.KEY_RETURN) { + if (unlockTextField.getFocus()) { + if (keyCode == Keyboard.KEY_ESCAPE || keyCode == Keyboard.KEY_RETURN) { CapeManager.INSTANCE.tryUnlockCape(unlockTextField.getText().trim()); unlockTextField.setText(""); unlockTextField.setFocus(false); @@ -257,8 +246,8 @@ public class GuiCosmetics extends GuiScreen { protected void mouseClicked(int mouseX, int mouseY, int mouseButton) { //guiLeft+sizeX-140, guiTop+sizeY+2 - if(mouseX > guiLeft+sizeX-140 & mouseX < guiLeft+sizeX && - mouseY > guiTop+sizeY && mouseY < guiTop+sizeY+22) { + if (mouseX > guiLeft + sizeX - 140 & mouseX < guiLeft + sizeX && + mouseY > guiTop + sizeY && mouseY < guiTop + sizeY + 22) { unlockTextField.mouseClicked(mouseX, mouseY, mouseButton); } @@ -275,39 +264,39 @@ public class GuiCosmetics extends GuiScreen { } } } - if(mouseY > guiTop+177 && mouseY < guiTop+177+12) { - if(mouseX > guiLeft+15+371*scroll && mouseX < guiLeft+15+371*scroll+32) { - scrollClickedX = mouseX - (int)(guiLeft+15+371*scroll); + if (mouseY > guiTop + 177 && mouseY < guiTop + 177 + 12) { + if (mouseX > guiLeft + 15 + 371 * scroll && mouseX < guiLeft + 15 + 371 * scroll + 32) { + scrollClickedX = mouseX - (int) (guiLeft + 15 + 371 * scroll); return; } } int index = 0; int displayingCapes = 0; - for(CapeManager.CapeData cape : CapeManager.INSTANCE.getCapes()) { + for (CapeManager.CapeData cape : CapeManager.INSTANCE.getCapes()) { boolean equipable = CapeManager.INSTANCE.getAvailableCapes() == null || CapeManager.INSTANCE.getAvailableCapes().contains(cape.capeName); if (cape.canShow() || equipable) { displayingCapes++; } } - float totalNeeded = 91*displayingCapes; - float totalAvail = sizeX-20; - float xOffset = scroll*(totalNeeded-totalAvail); + float totalNeeded = 91 * displayingCapes; + float totalAvail = sizeX - 20; + float xOffset = scroll * (totalNeeded - totalAvail); index = 0; int displayIndex = 0; - for(CapeManager.CapeData cape : CapeManager.INSTANCE.getCapes()) { + for (CapeManager.CapeData cape : CapeManager.INSTANCE.getCapes()) { boolean equipable = CapeManager.INSTANCE.getAvailableCapes() == null || CapeManager.INSTANCE.getAvailableCapes().contains(cape.capeName); - if(!cape.canShow() && !equipable) continue; + if (!cape.canShow() && !equipable) continue; GlStateManager.color(1, 1, 1, 1); Utils.drawTexturedRect(guiLeft + 20 + 91 * displayIndex - xOffset, guiTop + 123, 81, 20, 0, 81 / 256f, 216 / 256f, 236 / 256f, GL11.GL_NEAREST); - if(mouseX > guiLeft + 20 + 91 * displayIndex - xOffset && mouseX < guiLeft + 20 + 91 * displayIndex - xOffset+81) { - if(mouseY > guiTop + 123 && mouseY < guiTop + 123 + 20) { - if(CapeManager.INSTANCE.localCape != null && CapeManager.INSTANCE.localCape.getRight().equals(cape.capeName)) { + if (mouseX > guiLeft + 20 + 91 * displayIndex - xOffset && mouseX < guiLeft + 20 + 91 * displayIndex - xOffset + 81) { + if (mouseY > guiTop + 123 && mouseY < guiTop + 123 + 20) { + if (CapeManager.INSTANCE.localCape != null && CapeManager.INSTANCE.localCape.getRight().equals(cape.capeName)) { CapeManager.INSTANCE.setCape(Minecraft.getMinecraft().thePlayer.getUniqueID().toString().replace("-", ""), "null", true); } else { @@ -316,8 +305,8 @@ public class GuiCosmetics extends GuiScreen { } return; - } else if(equipable && mouseY > guiTop + 149 && mouseY < guiTop + 149 + 20) { - if(cape.capeName.equals(wantToEquipCape)) { + } else if (equipable && mouseY > guiTop + 149 && mouseY < guiTop + 149 + 20) { + if (cape.capeName.equals(wantToEquipCape)) { wantToEquipCape = null; } else { wantToEquipCape = cape.capeName; @@ -329,13 +318,13 @@ public class GuiCosmetics extends GuiScreen { displayIndex++; } - if(currentPage == CosmeticsPage.CAPES) { + if (currentPage == CosmeticsPage.CAPES) { Minecraft.getMinecraft().getTextureManager().bindTexture(pv_dropdown); - Utils.drawTexturedRect(guiLeft+sizeX/2f-50, guiTop+sizeY+5, 100, 20, 0, 100/200f, 0, 20/185f, GL11.GL_NEAREST); + Utils.drawTexturedRect(guiLeft + sizeX / 2f - 50, guiTop + sizeY + 5, 100, 20, 0, 100 / 200f, 0, 20 / 185f, GL11.GL_NEAREST); - if(mouseX > guiLeft+sizeX/2f-50 && mouseX < guiLeft+sizeX/2f+50) { - if(mouseY > guiTop+sizeY+5 && mouseY < guiTop+sizeY+25) { - if(System.currentTimeMillis() - lastCapeEquip > 20*1000) { + if (mouseX > guiLeft + sizeX / 2f - 50 && mouseX < guiLeft + sizeX / 2f + 50) { + if (mouseY > guiTop + sizeY + 5 && mouseY < guiTop + sizeY + 25) { + if (System.currentTimeMillis() - lastCapeEquip > 20 * 1000) { CapeManager.INSTANCE.setCape(Minecraft.getMinecraft().thePlayer.getUniqueID().toString().replace("-", ""), wantToEquipCape, true); @@ -343,7 +332,7 @@ public class GuiCosmetics extends GuiScreen { try { String userName = Minecraft.getMinecraft().thePlayer.getName(); - String accessToken = Minecraft.getMinecraft().getSession().getToken(); + String accessToken = Minecraft.getMinecraft().getSession().getToken(); Random r1 = new Random(); Random r2 = new Random(System.identityHashCode(new Object())); BigInteger random1Bi = new BigInteger(128, r1); @@ -352,23 +341,18 @@ public class GuiCosmetics extends GuiScreen { String serverId = serverBi.toString(16); Minecraft.getMinecraft().getSessionService().joinServer(Minecraft.getMinecraft().getSession().getProfile(), accessToken, serverId); - if(wantToEquipCape == null) { - NotEnoughUpdates.INSTANCE.manager.hypixelApi.getMyApiAsync("cgi-bin/changecape.py?capeType=null&serverId="+ - serverId+"&username="+userName, (jsonObject) -> { System.out.println(jsonObject); }, () -> { - System.out.println("Change cape error"); - }); + if (wantToEquipCape == null) { + NotEnoughUpdates.INSTANCE.manager.hypixelApi.getMyApiAsync("cgi-bin/changecape.py?capeType=null&serverId=" + + serverId + "&username=" + userName, System.out::println, () -> System.out.println("Change cape error")); } else { - NotEnoughUpdates.INSTANCE.manager.hypixelApi.getMyApiAsync("cgi-bin/changecape.py?capeType="+wantToEquipCape+"&serverId="+ - serverId+"&username="+userName, (jsonObject) -> { System.out.println(jsonObject); }, () -> { - System.out.println("Change cape error"); - }); + NotEnoughUpdates.INSTANCE.manager.hypixelApi.getMyApiAsync("cgi-bin/changecape.py?capeType=" + wantToEquipCape + "&serverId=" + + serverId + "&username=" + userName, System.out::println, () -> System.out.println("Change cape error")); } - } catch(Exception e) { + } catch (Exception e) { System.out.println("Exception while generating mojang shared secret"); e.printStackTrace(); } - } } } @@ -386,96 +370,97 @@ public class GuiCosmetics extends GuiScreen { protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) { super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick); - if(scrollClickedX >= 0) { + if (scrollClickedX >= 0) { float scrollStartX = mouseX - scrollClickedX; - scroll = (scrollStartX-(guiLeft+15))/371f; + scroll = (scrollStartX - (guiLeft + 15)) / 371f; scroll = Math.max(0, Math.min(1, scroll)); } } - private HashMap capesLocation = new HashMap<>(); + private final HashMap capesLocation = new HashMap<>(); private float scroll = 0f; private int scrollClickedX = -1; + private void drawCapesPage(int mouseX, int mouseY, float partialTicks) { Minecraft.getMinecraft().getTextureManager().bindTexture(cosmetics_fg); Utils.drawTexturedRect(guiLeft, guiTop, sizeX, sizeY, GL11.GL_NEAREST); Minecraft.getMinecraft().getTextureManager().bindTexture(pv_elements); - Utils.drawTexturedRect(guiLeft+15+371*scroll, guiTop+177, 32, 12, - 0, 32/256f, 192/256f, 204/256f, GL11.GL_NEAREST); + Utils.drawTexturedRect(guiLeft + 15 + 371 * scroll, guiTop + 177, 32, 12, + 0, 32 / 256f, 192 / 256f, 204 / 256f, GL11.GL_NEAREST); GL11.glEnable(GL11.GL_SCISSOR_TEST); - GL11.glScissor(Minecraft.getMinecraft().displayWidth*(guiLeft+3)/width, 0, - Minecraft.getMinecraft().displayWidth*(sizeX-6)/width, Minecraft.getMinecraft().displayHeight); + GL11.glScissor(Minecraft.getMinecraft().displayWidth * (guiLeft + 3) / width, 0, + Minecraft.getMinecraft().displayWidth * (sizeX - 6) / width, Minecraft.getMinecraft().displayHeight); int index = 0; int displayingCapes = 0; - for(CapeManager.CapeData capeData : CapeManager.INSTANCE.getCapes()) { + for (CapeManager.CapeData capeData : CapeManager.INSTANCE.getCapes()) { boolean equipable = CapeManager.INSTANCE.getAvailableCapes() == null || CapeManager.INSTANCE.getAvailableCapes().contains(capeData.capeName); if (capeData.canShow() || equipable) { displayingCapes++; } } - float totalNeeded = 91*displayingCapes; - float totalAvail = sizeX-20; - float xOffset = scroll*(totalNeeded-totalAvail); + float totalNeeded = 91 * displayingCapes; + float totalAvail = sizeX - 20; + float xOffset = scroll * (totalNeeded - totalAvail); index = 0; int displayIndex = 0; - for(CapeManager.CapeData capeData : CapeManager.INSTANCE.getCapes()) { + for (CapeManager.CapeData capeData : CapeManager.INSTANCE.getCapes()) { boolean equipable = CapeManager.INSTANCE.getAvailableCapes() == null || CapeManager.INSTANCE.getAvailableCapes().contains(capeData.capeName); - if(!capeData.canShow() && !equipable) continue; + if (!capeData.canShow() && !equipable) continue; - if(capeData.capeName.equals(CapeManager.INSTANCE.getCape(Minecraft.getMinecraft().thePlayer.getUniqueID().toString().replace("-", "")))) { + if (capeData.capeName.equals(CapeManager.INSTANCE.getCape(Minecraft.getMinecraft().thePlayer.getUniqueID().toString().replace("-", "")))) { GlStateManager.color(250 / 255f, 200 / 255f, 0 / 255f, 1); Utils.drawGradientRect(guiLeft + 20 + 91 * displayIndex - (int) xOffset, guiTop + 10, guiLeft + 20 + 91 * displayIndex - (int) xOffset + 81, guiTop + 10 + 108, new Color(150, 100, 0, 40).getRGB(), new Color(250, 200, 0, 40).getRGB()); - } else if(capeData.capeName.equals(wantToEquipCape)) { + } else if (capeData.capeName.equals(wantToEquipCape)) { GlStateManager.color(0, 200 / 255f, 250 / 255f, 1); Utils.drawGradientRect(guiLeft + 20 + 91 * displayIndex - (int) xOffset, guiTop + 10, guiLeft + 20 + 91 * displayIndex - (int) xOffset + 81, guiTop + 10 + 108, new Color(0, 100, 150, 40).getRGB(), new Color(0, 200, 250, 40).getRGB()); - } else if(CapeManager.INSTANCE.localCape != null && CapeManager.INSTANCE.localCape.getRight().equals(capeData.capeName)) { - GlStateManager.color(100/255f, 250/255f, 150/255f, 1); - Utils.drawGradientRect(guiLeft+20+91*displayIndex-(int)xOffset, guiTop+10, - guiLeft+20+91*displayIndex-(int)xOffset+81, guiTop+10+108, + } else if (CapeManager.INSTANCE.localCape != null && CapeManager.INSTANCE.localCape.getRight().equals(capeData.capeName)) { + GlStateManager.color(100 / 255f, 250 / 255f, 150 / 255f, 1); + Utils.drawGradientRect(guiLeft + 20 + 91 * displayIndex - (int) xOffset, guiTop + 10, + guiLeft + 20 + 91 * displayIndex - (int) xOffset + 81, guiTop + 10 + 108, new Color(50, 100, 75, 40).getRGB(), new Color(100, 250, 150, 40).getRGB()); } Minecraft.getMinecraft().getTextureManager().bindTexture(pv_elements); - Utils.drawTexturedRect(guiLeft+20+91*displayIndex-xOffset, guiTop+10, 81, 108, - 0, 81/256f, 84/256f, 192/256f, GL11.GL_NEAREST); + Utils.drawTexturedRect(guiLeft + 20 + 91 * displayIndex - xOffset, guiTop + 10, 81, 108, + 0, 81 / 256f, 84 / 256f, 192 / 256f, GL11.GL_NEAREST); GlStateManager.color(1, 1, 1, 1); - Utils.drawTexturedRect(guiLeft+20+91*displayIndex-xOffset, guiTop+123, 81, 20, - 0, 81/256f, 216/256f, 236/256f, GL11.GL_NEAREST); + Utils.drawTexturedRect(guiLeft + 20 + 91 * displayIndex - xOffset, guiTop + 123, 81, 20, + 0, 81 / 256f, 216 / 256f, 236 / 256f, GL11.GL_NEAREST); boolean equipPressed = capeData.capeName.equals(wantToEquipCape); - if(!equipable) GlStateManager.color(1, 1, 1, 0.5f); - Utils.drawTexturedRect(guiLeft+20+91*displayIndex-xOffset, guiTop+149, 81, 20, - equipPressed?81/256f:0, equipPressed?0:81/256f, equipPressed?236/256f:216/256f, equipPressed?216/256f:236/256f, GL11.GL_NEAREST); + if (!equipable) GlStateManager.color(1, 1, 1, 0.5f); + Utils.drawTexturedRect(guiLeft + 20 + 91 * displayIndex - xOffset, guiTop + 149, 81, 20, + equipPressed ? 81 / 256f : 0, equipPressed ? 0 : 81 / 256f, equipPressed ? 236 / 256f : 216 / 256f, equipPressed ? 216 / 256f : 236 / 256f, GL11.GL_NEAREST); Utils.drawStringCenteredScaledMaxWidth("Try it out", Minecraft.getMinecraft().fontRendererObj, - guiLeft+20+91*displayIndex+81/2f-xOffset, guiTop+123+10, false, 75, new Color(100, 250, 150).getRGB()); - if(equipable) { + guiLeft + 20 + 91 * displayIndex + 81 / 2f - xOffset, guiTop + 123 + 10, false, 75, new Color(100, 250, 150).getRGB()); + if (equipable) { Utils.drawStringCenteredScaledMaxWidth("Equip", Minecraft.getMinecraft().fontRendererObj, - guiLeft+20+91*displayIndex+81/2f-xOffset, guiTop+149+10, false, 75, new Color(100, 250, 150).getRGB()); + guiLeft + 20 + 91 * displayIndex + 81 / 2f - xOffset, guiTop + 149 + 10, false, 75, new Color(100, 250, 150).getRGB()); } else { Utils.drawStringCenteredScaledMaxWidth("Not Unlocked", Minecraft.getMinecraft().fontRendererObj, - guiLeft+20+91*displayIndex+81/2f-xOffset, guiTop+149+10, false, 75, new Color(200, 50, 50, 100).getRGB()); + guiLeft + 20 + 91 * displayIndex + 81 / 2f - xOffset, guiTop + 149 + 10, false, 75, new Color(200, 50, 50, 100).getRGB()); } GlStateManager.color(1, 1, 1, 1); ResourceLocation capeTexture = capesLocation.computeIfAbsent(capeData.capeName, - k -> new ResourceLocation("notenoughupdates", "capes/"+capeData.capeName+"_preview.png")); + k -> new ResourceLocation("notenoughupdates", "capes/" + capeData.capeName + "_preview.png")); Minecraft.getMinecraft().getTextureManager().bindTexture(capeTexture); - Utils.drawTexturedRect(guiLeft+31+91*displayIndex-xOffset, guiTop+24, 59, 84, GL11.GL_NEAREST); + Utils.drawTexturedRect(guiLeft + 31 + 91 * displayIndex - xOffset, guiTop + 24, 59, 84, GL11.GL_NEAREST); displayIndex++; } - GL11.glScissor(0, 0, Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayHeight); + GL11.glScissor(0, 0, Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayHeight); GL11.glDisable(GL11.GL_SCISSOR_TEST); Minecraft.getMinecraft().getTextureManager().bindTexture(pv_elements); @@ -489,15 +474,15 @@ public class GuiCosmetics extends GuiScreen { /** * Creates a projection matrix that projects from our coordinate space [0->width; 0->height] to OpenGL coordinate * space [-1 -> 1; 1 -> -1] (Note: flipped y-axis). - * + *

* This is so that we can render to and from the framebuffer in a way that is familiar to us, instead of needing to * apply scales and translations manually. */ private Matrix4f createProjectionMatrix(int width, int height) { - Matrix4f projMatrix = new Matrix4f(); + Matrix4f projMatrix = new Matrix4f(); projMatrix.setIdentity(); - projMatrix.m00 = 2.0F / (float)width; - projMatrix.m11 = 2.0F / (float)(-height); + projMatrix.m00 = 2.0F / (float) width; + projMatrix.m11 = 2.0F / (float) (-height); projMatrix.m22 = -0.0020001999F; projMatrix.m33 = 1.0F; projMatrix.m03 = -1.0F; @@ -513,49 +498,50 @@ public class GuiCosmetics extends GuiScreen { * if framebuffers are not available. (Apple machines, for example, have poor framebuffer support). */ private double lastBgBlurFactor = -1; + private void blurBackground() { int width = Minecraft.getMinecraft().displayWidth; int height = Minecraft.getMinecraft().displayHeight; - if(blurOutputHorz == null) { + if (blurOutputHorz == null) { blurOutputHorz = new Framebuffer(width, height, false); blurOutputHorz.setFramebufferFilter(GL11.GL_NEAREST); } - if(blurOutputVert == null) { + if (blurOutputVert == null) { blurOutputVert = new Framebuffer(width, height, false); blurOutputVert.setFramebufferFilter(GL11.GL_NEAREST); } - if(blurOutputHorz.framebufferWidth != width || blurOutputHorz.framebufferHeight != height) { + if (blurOutputHorz.framebufferWidth != width || blurOutputHorz.framebufferHeight != height) { blurOutputHorz.createBindFramebuffer(width, height); blurShaderHorz.setProjectionMatrix(createProjectionMatrix(width, height)); Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false); } - if(blurOutputVert.framebufferWidth != width || blurOutputVert.framebufferHeight != height) { + if (blurOutputVert.framebufferWidth != width || blurOutputVert.framebufferHeight != height) { blurOutputVert.createBindFramebuffer(width, height); blurShaderVert.setProjectionMatrix(createProjectionMatrix(width, height)); Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false); } - if(blurShaderHorz == null) { + if (blurShaderHorz == null) { try { blurShaderHorz = new Shader(Minecraft.getMinecraft().getResourceManager(), "blur", Minecraft.getMinecraft().getFramebuffer(), blurOutputHorz); blurShaderHorz.getShaderManager().getShaderUniform("BlurDir").set(1, 0); blurShaderHorz.setProjectionMatrix(createProjectionMatrix(width, height)); - } catch(Exception e) { } + } catch (Exception ignored) {} } - if(blurShaderVert == null) { + if (blurShaderVert == null) { try { blurShaderVert = new Shader(Minecraft.getMinecraft().getResourceManager(), "blur", blurOutputHorz, blurOutputVert); blurShaderVert.getShaderManager().getShaderUniform("BlurDir").set(0, 1); blurShaderVert.setProjectionMatrix(createProjectionMatrix(width, height)); - } catch(Exception e) { } + } catch (Exception ignored) {} } - if(blurShaderHorz != null && blurShaderVert != null) { - if(15 != lastBgBlurFactor) { - blurShaderHorz.getShaderManager().getShaderUniform("Radius").set((float)15); - blurShaderVert.getShaderManager().getShaderUniform("Radius").set((float)15); + if (blurShaderHorz != null && blurShaderVert != null) { + if (15 != lastBgBlurFactor) { + blurShaderHorz.getShaderManager().getShaderUniform("Radius").set((float) 15); + blurShaderVert.getShaderManager().getShaderUniform("Radius").set((float) 15); lastBgBlurFactor = 15; } GL11.glPushMatrix(); @@ -573,10 +559,10 @@ public class GuiCosmetics extends GuiScreen { * Essentially, this method will "blur" the background inside the bounds specified by [x->x+blurWidth, y->y+blurHeight] */ public void renderBlurredBackground(int width, int height, int x, int y, int blurWidth, int blurHeight) { - float uMin = x/(float)width; - float uMax = (x+blurWidth)/(float)width; - float vMin = (height-y)/(float)height; - float vMax = (height-y-blurHeight)/(float)height; + float uMin = x / (float) width; + float uMax = (x + blurWidth) / (float) width; + float vMin = (height - y) / (float) height; + float vMax = (height - y - blurHeight) / (float) height; blurOutputVert.bindFramebufferTexture(); GlStateManager.color(1f, 1f, 1f, 1f); diff --git a/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/NEUCape.java b/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/NEUCape.java index 3b0e0928..2142f1e8 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/NEUCape.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/NEUCape.java @@ -1,14 +1,8 @@ package io.github.moulberry.notenoughupdates.cosmetics; import io.github.moulberry.notenoughupdates.NotEnoughUpdates; -import io.github.moulberry.notenoughupdates.core.util.lerp.LerpUtils; -import io.github.moulberry.notenoughupdates.util.ReverseWorldRenderer; -import io.github.moulberry.notenoughupdates.util.TexLoc; -import io.github.moulberry.notenoughupdates.util.Utils; -import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; @@ -18,16 +12,11 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.potion.Potion; -import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -import net.minecraft.util.Vec3; -import net.minecraft.world.gen.NoiseGeneratorSimplex; import net.minecraftforge.client.event.RenderPlayerEvent; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import org.lwjgl.BufferUtils; -import org.lwjgl.Sys; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.*; import org.lwjgl.util.vector.Vector2f; @@ -35,8 +24,6 @@ import org.lwjgl.util.vector.Vector3f; import java.nio.ByteBuffer; import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.security.Key; import java.util.*; public class NEUCape { @@ -48,21 +35,21 @@ public class NEUCape { private long lastFrameUpdate = 0; - private static int ANIM_MODE_LOOP = 0; - private static int ANIM_MODE_PINGPONG = 1; - private int animMode = ANIM_MODE_LOOP; + private static final int ANIM_MODE_LOOP = 0; + private static final int ANIM_MODE_PINGPONG = 1; + private final int animMode = ANIM_MODE_LOOP; private CapeNode[] nodes = null; - private Random random = new Random(); + private final Random random = new Random(); private long eventMillis; private float eventLength; private float eventRandom; - private static double vertOffset = 1.4; - private static double shoulderLength = 0.24; - private static double shoulderWidth = 0.13; + private static final double vertOffset = 1.4; + private static final double shoulderLength = 0.24; + private static final double shoulderWidth = 0.13; public static final int HORZ_NODES = 6; public static final int VERT_NODES = 22; @@ -79,20 +66,20 @@ public class NEUCape { } public void setCapeTexture(String capeName) { - if(this.capeName != null && this.capeName.equalsIgnoreCase(capeName)) return; + if (this.capeName != null && this.capeName.equalsIgnoreCase(capeName)) return; startTime = System.currentTimeMillis(); boolean defaultBehaviour = true; - if(NotEnoughUpdates.INSTANCE.config.hidden.disableBrokenCapes){ - if(capeName.equals("negative")){ + if (NotEnoughUpdates.INSTANCE.config.hidden.disableBrokenCapes) { + if (capeName.equals("negative")) { defaultBehaviour = false; this.capeName = "fade"; this.shaderName = "fade_cape"; } - + } - if(defaultBehaviour){ + if (defaultBehaviour) { this.capeName = capeName; if (capeName.equalsIgnoreCase("fade")) { @@ -101,7 +88,7 @@ public class NEUCape { shaderName = "space_cape"; } else if (capeName.equalsIgnoreCase("mcworld")) { shaderName = "mcworld_cape"; - } else if(capeName.equalsIgnoreCase("lava") || capeName.equalsIgnoreCase("skyclient")) { + } else if (capeName.equalsIgnoreCase("lava") || capeName.equalsIgnoreCase("skyclient")) { shaderName = "lava_cape"; } else if (capeName.equalsIgnoreCase("lightning")) { shaderName = "lightning_cape"; @@ -126,29 +113,29 @@ public class NEUCape { } private void bindTexture() { - if(capeName.equalsIgnoreCase("negative")) { + if (capeName.equalsIgnoreCase("negative")) { CapeManager.getInstance().updateWorldFramebuffer = true; - if(CapeManager.getInstance().backgroundFramebuffer != null) { + if (CapeManager.getInstance().backgroundFramebuffer != null) { CapeManager.getInstance().backgroundFramebuffer.bindFramebufferTexture(); } - } else if(capeTextures != null && capeTextures.length > 0) { + } else if (capeTextures != null && capeTextures.length > 0) { long currentTime = System.currentTimeMillis(); - if(currentTime - lastFrameUpdate > 100) { + if (currentTime - lastFrameUpdate > 100) { lastFrameUpdate = currentTime / 100 * 100; currentFrame++; - if(animMode == ANIM_MODE_PINGPONG) { - if(capeTextures.length == 1) { + if (animMode == ANIM_MODE_PINGPONG) { + if (capeTextures.length == 1) { currentFrame = displayFrame = 0; } else { int frameCount = 2 * capeTextures.length - 2; currentFrame %= frameCount; displayFrame = currentFrame; - if(currentFrame >= capeTextures.length) { + if (currentFrame >= capeTextures.length) { displayFrame = frameCount - displayFrame; } } - } else if(animMode == ANIM_MODE_LOOP) { + } else if (animMode == ANIM_MODE_LOOP) { currentFrame %= capeTextures.length; displayFrame = currentFrame; } @@ -176,11 +163,11 @@ public class NEUCape { float vMaxSide = 404 / 1024f; float vMaxCenter = 419 / 1024f; - for(int i = 0; i < VERT_NODES; i++) { + for (int i = 0; i < VERT_NODES; i++) { float uMin = uMinTop + (uMinBottom - uMinTop) * i / (float) (VERT_NODES - 1); float uMax = uMaxTop + (uMaxBottom - uMaxTop) * i / (float) (VERT_NODES - 1); - for(int j = 0; j < HORZ_NODES; j++) { + for (int j = 0; j < HORZ_NODES; j++) { float vMin = 0f; float centerMult = 1 - Math.abs(j - (HORZ_NODES - 1) / 2f) / ((HORZ_NODES - 1) / 2f);//0-(horzCapeNodes) -> 0-1-0 float vMax = vMaxSide + (vMaxCenter - vMaxSide) * centerMult; @@ -191,36 +178,36 @@ public class NEUCape { node.horzDistMult = 2f + 1f * i / (float) (VERT_NODES - 1); - if(j == 0 || j == HORZ_NODES - 1) { + if (j == 0 || j == HORZ_NODES - 1) { node.horzSideTexU = 406 / 1024f * i / (float) (VERT_NODES - 1); - if(j == 0) { + if (j == 0) { node.horzSideTexVTop = 1 - 20 / 1024f; } else { node.horzSideTexVTop = 1 - 40 / 1024f; } } - if(i == 0) { + if (i == 0) { node.vertSideTexU = 198 / 1024f * j / (float) (HORZ_NODES - 1); node.vertSideTexVTop = 1 - 60 / 1024f; - } else if(i == VERT_NODES - 1) { + } else if (i == VERT_NODES - 1) { node.vertSideTexU = 300 / 1024f * j / (float) (HORZ_NODES - 1); node.vertSideTexVTop = 1 - 80 / 1024f; } nodes[j + i * HORZ_NODES] = node; } } - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { CapeNode node = nodes[x + y * HORZ_NODES]; - for(Direction dir : Direction.values()) { - for(int i = 1; i <= 2; i++) { + for (Direction dir : Direction.values()) { + for (int i = 1; i <= 2; i++) { Offset offset = new Offset(dir, i); int xNeighbor = x + offset.getXOffset(); int yNeighbor = y + offset.getYOffset(); - if(xNeighbor >= 0 && xNeighbor < HORZ_NODES + if (xNeighbor >= 0 && xNeighbor < HORZ_NODES && yNeighbor >= 0 && yNeighbor < VERT_NODES) { CapeNode neighbor = nodes[xNeighbor + yNeighbor * HORZ_NODES]; node.setNeighbor(offset, neighbor); @@ -232,7 +219,7 @@ public class NEUCape { } public void ensureCapeNodesCreated(EntityPlayer player) { - if(nodes == null) createCapeNodes(player); + if (nodes == null) createCapeNodes(player); } public enum Direction { @@ -256,8 +243,8 @@ public class NEUCape { public Direction rotateRight90() { int wantXOff = -yOff; int wantYOff = xOff; - for(Direction dir : values()) { - if(dir.xOff == wantXOff && dir.yOff == wantYOff) { + for (Direction dir : values()) { + if (dir.xOff == wantXOff && dir.yOff == wantYOff) { return dir; } } @@ -267,8 +254,8 @@ public class NEUCape { public Direction rotateLeft90() { int wantXOff = yOff; int wantYOff = -xOff; - for(Direction dir : values()) { - if(dir.xOff == wantXOff && dir.yOff == wantYOff) { + for (Direction dir : values()) { + if (dir.xOff == wantXOff && dir.yOff == wantYOff) { return dir; } } @@ -294,7 +281,7 @@ public class NEUCape { } public boolean equals(Object obj) { - if(obj instanceof Offset) { + if (obj instanceof Offset) { Offset other = (Offset) obj; return other.direction == direction && other.steps == steps; } @@ -309,27 +296,27 @@ public class NEUCape { private void loadShaderUniforms(ShaderManager shaderManager) { String shaderId = "capes/" + shaderName + "/" + shaderName; - if(shaderName.equalsIgnoreCase("fade_cape") || shaderName.equalsIgnoreCase("planets")) { + if (shaderName.equalsIgnoreCase("fade_cape") || shaderName.equalsIgnoreCase("planets")) { shaderManager.loadData(shaderId, "millis", (int) (System.currentTimeMillis() - startTime)); - } else if(shaderName.equalsIgnoreCase("space_cape")) { + } else if (shaderName.equalsIgnoreCase("space_cape")) { shaderManager.loadData(shaderId, "millis", (int) (System.currentTimeMillis() - startTime)); shaderManager.loadData(shaderId, "eventMillis", (int) (System.currentTimeMillis() - eventMillis)); shaderManager.loadData(shaderId, "eventRand", eventRandom); - } else if(shaderName.equalsIgnoreCase("mcworld_cape")) { + } else if (shaderName.equalsIgnoreCase("mcworld_cape")) { shaderManager.loadData(shaderId, "millis", (int) (System.currentTimeMillis() - startTime)); - } else if(shaderName.equalsIgnoreCase("lava_cape")) { + } else if (shaderName.equalsIgnoreCase("lava_cape")) { shaderManager.loadData(shaderId, "millis", (int) (System.currentTimeMillis() - startTime)); - } else if(shaderName.equalsIgnoreCase("tunnel")) { + } else if (shaderName.equalsIgnoreCase("tunnel")) { shaderManager.loadData(shaderId, "millis", (int) (System.currentTimeMillis() - startTime)); - } else if(shaderName.equalsIgnoreCase("biscuit_cape") || shaderName.equalsIgnoreCase("shiny_cape")) { + } else if (shaderName.equalsIgnoreCase("biscuit_cape") || shaderName.equalsIgnoreCase("shiny_cape")) { shaderManager.loadData(shaderId, "millis", (int) (System.currentTimeMillis() - startTime)); shaderManager.loadData(shaderId, "eventMillis", (int) (System.currentTimeMillis() - eventMillis)); - } else if(shaderName.equalsIgnoreCase("negative")) { + } else if (shaderName.equalsIgnoreCase("negative")) { shaderManager.loadData(shaderId, "screensize", new Vector2f( Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayHeight )); - } else if(shaderName.equalsIgnoreCase("void")) { + } else if (shaderName.equalsIgnoreCase("void")) { shaderManager.loadData(shaderId, "millis", (int) (System.currentTimeMillis() - startTime)); shaderManager.loadData(shaderId, "screensize", new Vector2f( Minecraft.getMinecraft().displayWidth, @@ -343,10 +330,10 @@ public class NEUCape { public void onRenderPlayer(RenderPlayerEvent.Post e) { EntityPlayer player = e.entityPlayer; - if(currentPlayer != null && keepCurrentPlayer && currentPlayer != player) return; + if (currentPlayer != null && keepCurrentPlayer && currentPlayer != player) return; - if(player.getActivePotionEffect(Potion.invisibility) != null) return; - if(player.isSpectator() || player.isInvisible()) return; + if (player.getActivePotionEffect(Potion.invisibility) != null) return; + if (player.isSpectator() || player.isInvisible()) return; ensureCapeNodesCreated(player); @@ -366,7 +353,7 @@ public class NEUCape { GlStateManager.disableLighting(); GlStateManager.color(1, 1, 1, 1); - if(shaderName.equals("mcworld_cape")) { + if (shaderName.equals("mcworld_cape")) { GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); } else { @@ -397,21 +384,21 @@ public class NEUCape { } public void onTick(TickEvent.ClientTickEvent event, EntityPlayer player) { - if(player == null) return; - if(Minecraft.getMinecraft().isGamePaused()) return; + if (player == null) return; + if (Minecraft.getMinecraft().isGamePaused()) return; - if(System.currentTimeMillis() - lastRender < 500) { - if(currentPlayer == null || !keepCurrentPlayer) { + if (System.currentTimeMillis() - lastRender < 500) { + if (currentPlayer == null || !keepCurrentPlayer) { keepCurrentPlayer = true; currentPlayer = player; - } else if(currentPlayer != player) { + } else if (currentPlayer != player) { return; } ensureCapeNodesCreated(player); - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { CapeNode node = nodes[x + y * HORZ_NODES]; node.lastPosition.x = node.position.x; node.lastPosition.y = node.position.y; @@ -427,11 +414,10 @@ public class NEUCape { private static double interpolateRotation(float a, float b, float amount) { double f; - for(f = b - a; f < -180.0F; f += 360.0F) { - ; + for (f = b - a; f < -180.0F; f += 360.0F) { } - while(f >= 180.0F) { + while (f >= 180.0F) { f -= 360.0F; } @@ -441,24 +427,24 @@ public class NEUCape { private double getPlayerRenderAngle(EntityPlayer player, float partialRenderTick) { double angle = interpolateRotation(player.prevRenderYawOffset, player.renderYawOffset, partialRenderTick); - if(player.isRiding() && player.ridingEntity instanceof EntityLivingBase && player.ridingEntity.shouldRiderSit()) { + if (player.isRiding() && player.ridingEntity instanceof EntityLivingBase && player.ridingEntity.shouldRiderSit()) { EntityLivingBase entitylivingbase = (EntityLivingBase) player.ridingEntity; double head = interpolateRotation(player.prevRotationYawHead, player.rotationYawHead, partialRenderTick); angle = interpolateRotation(entitylivingbase.prevRenderYawOffset, entitylivingbase.renderYawOffset, partialRenderTick); double wrapped = MathHelper.wrapAngleTo180_double(head - angle); - if(wrapped < -85.0F) { + if (wrapped < -85.0F) { wrapped = -85.0F; } - if(wrapped >= 85.0F) { + if (wrapped >= 85.0F) { wrapped = 85.0F; } angle = head - wrapped; - if(wrapped * wrapped > 2500.0F) { + if (wrapped * wrapped > 2500.0F) { angle += wrapped * 0.2F; } } @@ -483,7 +469,7 @@ public class NEUCape { float totalDZ = 0; int totalMovements = 0; - for(int i = 0; i < HORZ_NODES; i++) { + for (int i = 0; i < HORZ_NODES; i++) { float mult = 1 - 2f * i / (HORZ_NODES - 1); //1 -> -1 float widthMult = 1.25f - (1.414f * i / (HORZ_NODES - 1) - 0.707f) * (1.414f * i / (HORZ_NODES - 1) - 0.707f); CapeNode node = nodes[i]; @@ -519,7 +505,7 @@ public class NEUCape { float xOff = (float) (Math.cos(angle) * shoulderLength); float zOff = (float) (Math.sin(angle) * shoulderLength); - for(int i = 0; i < HORZ_NODES; i++) { + for (int i = 0; i < HORZ_NODES; i++) { float mult = 1 - 2f * i / (HORZ_NODES - 1); //1 -> -1 float widthMult = 1.25f - (1.414f * i / (HORZ_NODES - 1) - 0.707f) * (1.414f * i / (HORZ_NODES - 1) - 0.707f); CapeNode node = nodes[i]; @@ -538,16 +524,16 @@ public class NEUCape { private void updateCape(EntityPlayer player) { Vector3f capeTranslation = updateFixedCapeNodes(player); - if(shaderName.equals("space_cape")) { + if (shaderName.equals("space_cape")) { long currentTime = System.currentTimeMillis(); - if(currentTime - startTime > eventMillis - startTime + eventLength) { + if (currentTime - startTime > eventMillis - startTime + eventLength) { eventMillis = currentTime; eventLength = random.nextFloat() * 2000 + 4000; eventRandom = random.nextFloat(); } - } else if(shaderName.equals("biscuit_cape") || shaderName.equals("shiny_cape")) { + } else if (shaderName.equals("biscuit_cape") || shaderName.equals("shiny_cape")) { long currentTime = System.currentTimeMillis(); - if(currentTime - startTime > eventMillis - startTime + eventLength) { + if (currentTime - startTime > eventMillis - startTime + eventLength) { eventMillis = currentTime; eventLength = random.nextFloat() * 3000 + 3000; } @@ -555,10 +541,10 @@ public class NEUCape { double playerAngle = getPlayerRenderAngle(player, 0); double deltaAngle = playerAngle - oldPlayerAngle; - if(deltaAngle > Math.PI) { + if (deltaAngle > Math.PI) { deltaAngle = 2 * Math.PI - deltaAngle; } - if(deltaAngle < -Math.PI) { + if (deltaAngle < -Math.PI) { deltaAngle = 2 * Math.PI + deltaAngle; } deltaAngleAccum *= 0.5f; @@ -572,17 +558,17 @@ public class NEUCape { float capeTransLength = capeTranslation.length(); float capeTranslationFactor = 0f; - if(capeTransLength > 0.5f) { + if (capeTransLength > 0.5f) { capeTranslationFactor = (capeTransLength - 0.5f) / capeTransLength; } Vector3f lookDir = new Vector3f(dX, 0, dZ); Vector3f lookDirNorm = lookDir.normalise(null); float dot = Vector3f.dot(capeTranslation, lookDirNorm); - if(dot < 0) { //Moving backwards - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + if (dot < 0) { //Moving backwards + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { CapeNode node = nodes[x + y * HORZ_NODES]; - if(!node.fixed) { + if (!node.fixed) { node.position.x += lookDirNorm.x * dot; node.position.y += lookDirNorm.y * dot; node.position.z += lookDirNorm.z * dot; @@ -593,23 +579,23 @@ public class NEUCape { factor = 0.05f; } - if(factor > 0) { - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + if (factor > 0) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { nodes[x + y * HORZ_NODES].applyForce(-dX * factor, 0, -dZ * factor); } } } - if(capeTranslationFactor > 0f) { + if (capeTranslationFactor > 0f) { float capeDX = capeTranslation.x * capeTranslationFactor; float capeDY = capeTranslation.y * capeTranslationFactor; float capeDZ = capeTranslation.z * capeTranslationFactor; - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { CapeNode node = nodes[x + y * HORZ_NODES]; - if(!node.fixed) { + if (!node.fixed) { node.position.x += capeDX; node.position.y += capeDY; node.position.z += capeDZ; @@ -625,20 +611,20 @@ public class NEUCape { float windDX = (float) Math.cos(windDir + Math.PI / 2f); float windDZ = (float) Math.sin(windDir + Math.PI / 2f); - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { nodes[x + y * HORZ_NODES].applyForce(-windDX * windRandom * 0.01f, 0, -windDZ * windRandom * 0.01f); } } - if(player.isSneaking()) { + if (player.isSneaking()) { crouchTicks++; float mult = 0.5f; - if(crouchTicks < 5) { + if (crouchTicks < 5) { mult = 2f; } - for(int y = 0; y < 8; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < 8; y++) { + for (int x = 0; x < HORZ_NODES; x++) { nodes[x + y * HORZ_NODES].applyForce(-dX * mult, 0, -dZ * mult); } } @@ -647,13 +633,13 @@ public class NEUCape { } Vector3f avgPosition = avgFixedPosition(); - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { CapeNode node = nodes[x + y * HORZ_NODES]; Vector3f delta = Vector3f.sub(node.position, avgPosition, null); - if(delta.lengthSquared() > 5 * 5) { + if (delta.lengthSquared() > 5 * 5) { Vector3f norm = delta.normalise(null); node.position = Vector3f.add(avgPosition, norm, null); } @@ -662,15 +648,15 @@ public class NEUCape { oldPlayerAngle = playerAngle; - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { nodes[x + y * HORZ_NODES].update(); } } - int updates = player == Minecraft.getMinecraft().thePlayer ? 50 : 50; - for(int i = 0; i < updates; i++) { - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + int updates = 50; + for (int i = 0; i < updates; i++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { nodes[x + y * HORZ_NODES].resolveAll(2 + 1f * y / VERT_NODES, false); } } @@ -686,8 +672,8 @@ public class NEUCape { private void loadSBBO() { FloatBuffer buff = BufferUtils.createFloatBuffer(CapeNode.FLOAT_NUM * HORZ_NODES * VERT_NODES); - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { nodes[x + y * HORZ_NODES].loadIntoBuffer(buff); } } @@ -699,7 +685,7 @@ public class NEUCape { } private void resolveAllCompute() { - if(ssbo == -1) { + if (ssbo == -1) { generateSSBO(); } loadSBBO(); @@ -714,7 +700,7 @@ public class NEUCape { GL20.glUseProgram(program); - for(int i = 0; i < 30; i++) { + for (int i = 0; i < 30; i++) { GL43.glDispatchCompute(VERT_NODES, 1, 1); GL42.glMemoryBarrier(GL43.GL_SHADER_STORAGE_BARRIER_BIT); } @@ -727,8 +713,8 @@ public class NEUCape { GL15.glGetBufferSubData(GL43.GL_SHADER_STORAGE_BUFFER, 0, buff); GL15.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, 0); - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { nodes[x + y * HORZ_NODES].readFromBuffer(buff); } } @@ -737,14 +723,14 @@ public class NEUCape { private Vector3f avgRenderPosition() { Vector3f accum = new Vector3f(); int num = 0; - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { CapeNode node = nodes[x + y * HORZ_NODES]; Vector3f.add(accum, node.renderPosition, accum); num++; } } - if(num != 0) { + if (num != 0) { accum.scale(1f / num); } return accum; @@ -753,14 +739,14 @@ public class NEUCape { private Vector3f avgNormal() { Vector3f accum = new Vector3f(); int num = 0; - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { CapeNode node = nodes[x + y * HORZ_NODES]; Vector3f.add(accum, node.normal(), accum); num++; } } - if(num != 0) { + if (num != 0) { accum.scale(1f / num); } return accum; @@ -769,16 +755,16 @@ public class NEUCape { private Vector3f avgFixedRenderPosition() { Vector3f accum = new Vector3f(); int numFixed = 0; - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { CapeNode node = nodes[x + y * HORZ_NODES]; - if(node.fixed) { + if (node.fixed) { Vector3f.add(accum, node.renderPosition, accum); numFixed++; } } } - if(numFixed != 0) { + if (numFixed != 0) { accum.scale(1f / numFixed); } return accum; @@ -787,29 +773,29 @@ public class NEUCape { private Vector3f avgFixedPosition() { Vector3f accum = new Vector3f(); int numFixed = 0; - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { CapeNode node = nodes[x + y * HORZ_NODES]; - if(node.fixed) { + if (node.fixed) { Vector3f.add(accum, node.position, accum); numFixed++; } } } - if(numFixed != 0) { + if (numFixed != 0) { accum.scale(1f / numFixed); } return accum; } private void renderBackAndDoFrontStencil() { - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { nodes[x + y * HORZ_NODES].renderNode(CapeNode.DRAW_MASK_BACK | CapeNode.DRAW_MASK_SIDES); } } - if(!Minecraft.getMinecraft().getFramebuffer().isStencilEnabled()) + if (!Minecraft.getMinecraft().getFramebuffer().isStencilEnabled()) Minecraft.getMinecraft().getFramebuffer().enableStencil(); GL11.glEnable(GL11.GL_STENCIL_TEST); @@ -820,8 +806,8 @@ public class NEUCape { GlStateManager.enableDepth(); GL11.glColorMask(false, false, false, false); - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { nodes[x + y * HORZ_NODES].renderNode(CapeNode.DRAW_MASK_FRONT); } } @@ -834,25 +820,25 @@ public class NEUCape { private Vector3f getPoint(Vector3f point, Vector3f... vectors) { Vector3f res = new Vector3f(point); - for(Vector3f vec : vectors) Vector3f.add(res, vec, res); + for (Vector3f vec : vectors) Vector3f.add(res, vec, res); return res; } private static void renderVBO(WorldRenderer worldRenderer) { - if(worldRenderer != null && worldRenderer.getVertexCount() > 0) { + if (worldRenderer != null && worldRenderer.getVertexCount() > 0) { VertexFormat vertexformat = worldRenderer.getVertexFormat(); int stride = vertexformat.getNextOffset(); ByteBuffer bytebuffer = worldRenderer.getByteBuffer(); List list = vertexformat.getElements(); - for(int index = 0; index < list.size(); index++) { + for (int index = 0; index < list.size(); index++) { VertexFormatElement vertexformatelement = list.get(index); vertexformatelement.getUsage().preDraw(vertexformat, index, stride, bytebuffer); } GL11.glDrawArrays(worldRenderer.getDrawMode(), 0, worldRenderer.getVertexCount()); - for(int index = 0; index < list.size(); index++) { + for (int index = 0; index < list.size(); index++) { VertexFormatElement vertexformatelement = list.get(index); vertexformatelement.getUsage().postDraw(vertexformat, index, stride, bytebuffer); } @@ -862,7 +848,7 @@ public class NEUCape { private static WorldRenderer sphereVBO = null; private void renderNodes() { - if(capeName.equalsIgnoreCase("planets")) { + if (capeName.equalsIgnoreCase("planets")) { renderBackAndDoFrontStencil(); Vector3f pointNorm = avgNormal(); @@ -872,8 +858,8 @@ public class NEUCape { pointNorm.scale(1 - pointNorm.y / 1.3f); Vector3f point = Vector3f.sub(capeAvgPos, pointNorm, null); - if(sphereVBO == null || Keyboard.isKeyDown(Keyboard.KEY_K)) { - if(sphereVBO != null) sphereVBO.reset(); + if (sphereVBO == null || Keyboard.isKeyDown(Keyboard.KEY_K)) { + if (sphereVBO != null) sphereVBO.reset(); int arcSegments = 24; int rotationSegments = 24; @@ -884,14 +870,14 @@ public class NEUCape { double diameterUnitArcLen = 0; double arcAngle = 0; - for(int i = 0; i < arcSegments; i++) { + for (int i = 0; i < arcSegments; i++) { diameterUnitArcLen += Math.sin(arcAngle); arcAngle += arcAngleDelta; } double arcLength = 2f / diameterUnitArcLen; List> arcs = new ArrayList<>(); - for(int angleI = 0; angleI < rotationSegments; angleI++) { + for (int angleI = 0; angleI < rotationSegments; angleI++) { double angle = Math.PI * 2 * angleI / rotationSegments; List arc = new ArrayList<>(); @@ -901,7 +887,7 @@ public class NEUCape { arc.add(arcPos); arcAngle = 0; - for(int segmentI = 0; segmentI < arcSegments; segmentI++) { + for (int segmentI = 0; segmentI < arcSegments; segmentI++) { double deltaZ = Math.sin(arcAngle) * arcLength; double deltaY = Math.cos(arcAngle) * Math.cos(angle) * arcLength; @@ -924,8 +910,8 @@ public class NEUCape { sphereVBO.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_NORMAL); double maxXYRad = 0; - for(int angleI = 0; angleI < rotationSegments; angleI++) { - for(int segmentI = 0; segmentI <= arcSegments; segmentI++) { + for (int angleI = 0; angleI < rotationSegments; angleI++) { + for (int segmentI = 0; segmentI <= arcSegments; segmentI++) { List thisArc = arcs.get(angleI); Vector3f point1 = thisArc.get(segmentI); double rad = Math.sqrt(point1.x * point1.x + point1.y * point1.y); @@ -933,10 +919,10 @@ public class NEUCape { } } - for(int angleI = 0; angleI < rotationSegments; angleI++) { + for (int angleI = 0; angleI < rotationSegments; angleI++) { int nextAngleI = angleI + 1; - if(angleI == rotationSegments - 1) { + if (angleI == rotationSegments - 1) { nextAngleI = 0; } @@ -947,7 +933,7 @@ public class NEUCape { List thisArc = arcs.get(angleI); List nextArc = arcs.get(nextAngleI); - for(int segmentI = 1; segmentI <= arcSegments; segmentI++) { + for (int segmentI = 1; segmentI <= arcSegments; segmentI++) { Vector3f point1 = thisArc.get(segmentI); Vector3f point2 = thisArc.get(segmentI - 1); Vector3f point3 = nextArc.get(segmentI - 1); @@ -1006,29 +992,29 @@ public class NEUCape { orbitals.put(mercuryDist, 2); double delta = Minecraft.getMinecraft().getRenderViewEntity().getRotationYawHead() % 360; - while(delta < 0) delta += 360; + while (delta < 0) delta += 360; double jupDelta = (delta + Math.toDegrees(jupiterAngle)) % 360; - while(jupDelta < 0) jupDelta += 360; - if(jupDelta > 250 || jupDelta < 110) orbitals.put(jupiterDist, 3); + while (jupDelta < 0) jupDelta += 360; + if (jupDelta > 250 || jupDelta < 110) orbitals.put(jupiterDist, 3); double nepDelta = (delta + Math.toDegrees(-earthAngle)) % 360; - while(nepDelta < 0) nepDelta += 360; - if(nepDelta > 250 || nepDelta < 110) orbitals.put(neptuneDist, 4); + while (nepDelta < 0) nepDelta += 360; + if (nepDelta > 250 || nepDelta < 110) orbitals.put(neptuneDist, 4); GlStateManager.disableDepth(); GlStateManager.enableCull(); - for(int planetId : orbitals.descendingMap().values()) { + for (int planetId : orbitals.descendingMap().values()) { GlStateManager.pushMatrix(); - switch(planetId) { + switch (planetId) { case 0: { GlStateManager.translate(point.x, point.y, point.z); GlStateManager.scale(0.2f, 0.2f, 0.2f); break; } case 1: { - Vector3f sunVec = new Vector3f((float) earthX, (float) earthY, (float) earthZ); + Vector3f sunVec = new Vector3f((float) earthX, (float) earthY, (float) earthZ); ShaderManager.getInstance().loadData(shaderId, "sunVec", sunVec); GlStateManager.translate(point.x + earthX, point.y + earthY, point.z + earthZ); GlStateManager.scale(0.1f, 0.1f, 0.1f); @@ -1061,12 +1047,11 @@ public class NEUCape { GlStateManager.popMatrix(); } - GlStateManager.disableCull(); GlStateManager.enableDepth(); GL11.glDisable(GL11.GL_STENCIL_TEST); - } else if(capeName.equalsIgnoreCase("parallax")) { + } else if (capeName.equalsIgnoreCase("parallax")) { renderBackAndDoFrontStencil(); Vector3f pointNorm = avgNormal(); @@ -1129,12 +1114,11 @@ public class NEUCape { tessellator.draw(); - GlStateManager.disableCull(); GlStateManager.enableDepth(); GL11.glDisable(GL11.GL_STENCIL_TEST); - } else if(capeName.equalsIgnoreCase("tunnel")) { + } else if (capeName.equalsIgnoreCase("tunnel")) { renderBackAndDoFrontStencil(); Vector3f pointNorm = avgNormal(); @@ -1147,7 +1131,7 @@ public class NEUCape { List edgeCoords = new ArrayList<>(); //Left edge - for(int y = 0; y < VERT_NODES; y++) { + for (int y = 0; y < VERT_NODES; y++) { edgeNodes.add(nodes[y * HORZ_NODES]); edgeCoords.add(new Vector2f(0, (float) y / (VERT_NODES - 1))); } @@ -1156,14 +1140,14 @@ public class NEUCape { //Bottom edge int bottomIndex = VERT_NODES - 1; int botSize = HORZ_NODES; - for(int x = 0; x < botSize; x++) { + for (int x = 0; x < botSize; x++) { edgeNodes.add(getNode(x, bottomIndex)); edgeCoords.add(new Vector2f((float) x / (botSize - 1), 1)); } edgeNodes.add(null); edgeCoords.add(null); //Right edge - for(int y = VERT_NODES - 1; y >= 0; y--) { + for (int y = VERT_NODES - 1; y >= 0; y--) { edgeNodes.add(getNode(HORZ_NODES - 1, y)); edgeCoords.add(new Vector2f(1, (float) y / VERT_NODES)); } @@ -1171,7 +1155,7 @@ public class NEUCape { edgeCoords.add(null); //Top edge int topSize = HORZ_NODES; - for(int x = topSize - 1; x >= 0; x--) { + for (int x = topSize - 1; x >= 0; x--) { edgeNodes.add(getNode(x, 0)); edgeCoords.add(new Vector2f((float) x / (topSize - 1), 0)); } @@ -1179,9 +1163,9 @@ public class NEUCape { GlStateManager.disableDepth(); GlStateManager.enableCull(); CapeNode last = null; - for(int i = 0; i < edgeNodes.size(); i++) { + for (int i = 0; i < edgeNodes.size(); i++) { CapeNode node = edgeNodes.get(i); - if(last != null && node != null) { + if (last != null && node != null) { Vector2f lastCoord = edgeCoords.get(i - 1); Vector2f coord = edgeCoords.get(i); @@ -1212,8 +1196,8 @@ public class NEUCape { GL11.glDisable(GL11.GL_STENCIL_TEST); } else { - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { nodes[x + y * HORZ_NODES].renderNode(); } } @@ -1228,13 +1212,13 @@ public class NEUCape { Vector3f avgPositionFixed = avgFixedRenderPosition(); Vector3f delta = Vector3f.sub(avgPositionFixed, avgPositionFixedBefore, null); - if(delta.lengthSquared() > 9) { + if (delta.lengthSquared() > 9) { updateFixedCapeNodes(player); - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { CapeNode node = nodes[x + y * HORZ_NODES]; - if(!node.fixed) { + if (!node.fixed) { Vector3f.add(node.renderPosition, delta, node.renderPosition); node.position.set(node.renderPosition); node.lastPosition.set(node.renderPosition); @@ -1248,13 +1232,13 @@ public class NEUCape { return; } - for(int y = 0; y < VERT_NODES; y++) { - for(int x = 0; x < HORZ_NODES; x++) { + for (int y = 0; y < VERT_NODES; y++) { + for (int x = 0; x < HORZ_NODES; x++) { CapeNode node = nodes[x + y * HORZ_NODES]; node.resetNormal(); - if(node.fixed) continue; + if (node.fixed) continue; Vector3f newPosition = new Vector3f(); newPosition.x = node.lastPosition.x + (node.position.x - node.lastPosition.x) * partialRenderTick; @@ -1264,18 +1248,18 @@ public class NEUCape { int length = node.oldRenderPosition.length; int fps = Minecraft.getDebugFPS(); - if(fps < 50) { + if (fps < 50) { length = 2; - } else if(fps < 100) { + } else if (fps < 100) { length = 2 + (int) ((fps - 50) / 50f * 3); } - if(node.oldRenderPosition[length - 1] == null) { + if (node.oldRenderPosition[length - 1] == null) { Arrays.fill(node.oldRenderPosition, Vector3f.sub(newPosition, avgPositionFixed, null)); node.renderPosition = newPosition; } else { Vector3f accum = new Vector3f(); - for(int i = 0; i < length; i++) { + for (int i = 0; i < length; i++) { Vector3f.add(accum, node.oldRenderPosition[i], accum); Vector3f.add(accum, avgPositionFixed, accum); } @@ -1288,9 +1272,9 @@ public class NEUCape { node.renderPosition = accum; } - if(!Minecraft.getMinecraft().isGamePaused()) { - for(int i = node.oldRenderPosition.length - 1; i >= 0; i--) { - if(i > 0) { + if (!Minecraft.getMinecraft().isGamePaused()) { + for (int i = node.oldRenderPosition.length - 1; i >= 0; i--) { + if (i > 0) { node.oldRenderPosition[i] = node.oldRenderPosition[i - 1]; } else { node.oldRenderPosition[i] = Vector3f.sub(node.renderPosition, avgPositionFixed, null); diff --git a/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/ShaderManager.java b/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/ShaderManager.java index a750f597..6801b4c8 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/ShaderManager.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/cosmetics/ShaderManager.java @@ -16,8 +16,8 @@ import java.util.HashMap; public class ShaderManager { - private ResourceLocation shaderLocation = new ResourceLocation("notenoughupdates:shaders"); - private HashMap shaderMap = new HashMap<>(); + private final ResourceLocation shaderLocation = new ResourceLocation("notenoughupdates:shaders"); + private final HashMap shaderMap = new HashMap<>(); private static final ShaderManager INSTANCE = new ShaderManager(); @@ -25,7 +25,7 @@ public class ShaderManager { return INSTANCE; } - public class Shader { + public static class Shader { public final int program; public Shader(int program) { @@ -34,14 +34,14 @@ public class ShaderManager { } public int getShader(String name) { - if(!shaderMap.containsKey(name)) { + if (!shaderMap.containsKey(name)) { reloadShader(name); } return shaderMap.get(name).program; } public int loadShader(String name) { - if(!shaderMap.containsKey(name)) { + if (!shaderMap.containsKey(name)) { reloadShader(name); } GL20.glUseProgram(shaderMap.get(name).program); @@ -51,17 +51,17 @@ public class ShaderManager { public void loadData(String name, String var, Object value) { int location = GL20.glGetUniformLocation(shaderMap.get(name).program, var); - if(value instanceof Integer) { + if (value instanceof Integer) { GL20.glUniform1i(location, (Integer) value); - } else if(value instanceof Float) { + } else if (value instanceof Float) { GL20.glUniform1f(location, (Float) value); - } else if(value instanceof Vector2f) { + } else if (value instanceof Vector2f) { Vector2f vec = (Vector2f) value; GL20.glUniform2f(location, vec.x, vec.y); - } else if(value instanceof Vector3f) { + } else if (value instanceof Vector3f) { Vector3f vec = (Vector3f) value; GL20.glUniform3f(location, vec.x, vec.y, vec.z); - } else if(value instanceof Vector4f) { + } else if (value instanceof Vector4f) { Vector4f vec = (Vector4f) value; GL20.glUniform4f(location, vec.x, vec.y, vec.z, vec.w); } else { @@ -72,7 +72,7 @@ public class ShaderManager { private void reloadShader(String name) { int vertex = -1; String sourceVert = getShaderSource(name, GL20.GL_VERTEX_SHADER); - if(!sourceVert.isEmpty()) { + if (!sourceVert.isEmpty()) { vertex = GL20.glCreateShader(GL20.GL_VERTEX_SHADER); GL20.glShaderSource(vertex, sourceVert); GL20.glCompileShader(vertex); @@ -84,7 +84,7 @@ public class ShaderManager { int fragment = -1; String sourceFrag = getShaderSource(name, GL20.GL_FRAGMENT_SHADER); - if(!sourceFrag.isEmpty()) { + if (!sourceFrag.isEmpty()) { fragment = GL20.glCreateShader(GL20.GL_FRAGMENT_SHADER); GL20.glShaderSource(fragment, sourceFrag); GL20.glCompileShader(fragment); @@ -96,7 +96,7 @@ public class ShaderManager { int compute = -1; String sourceCompute = getShaderSource(name, GL43.GL_COMPUTE_SHADER); - if(!sourceCompute.isEmpty()) { + if (!sourceCompute.isEmpty()) { compute = GL20.glCreateShader(GL43.GL_COMPUTE_SHADER); GL20.glShaderSource(compute, sourceCompute); GL20.glCompileShader(compute); @@ -107,15 +107,15 @@ public class ShaderManager { } int program = GL20.glCreateProgram(); - if(vertex != -1) GL20.glAttachShader(program, vertex); - if(fragment != -1) GL20.glAttachShader(program, fragment); - if(compute != -1) GL20.glAttachShader(program, compute); + if (vertex != -1) GL20.glAttachShader(program, vertex); + if (fragment != -1) GL20.glAttachShader(program, fragment); + if (compute != -1) GL20.glAttachShader(program, compute); GL20.glLinkProgram(program); - if(vertex != -1) GL20.glDeleteShader(vertex); - if(fragment != -1) GL20.glDeleteShader(fragment); - if(compute != -1) GL20.glDeleteShader(compute); + if (vertex != -1) GL20.glDeleteShader(vertex); + if (fragment != -1) GL20.glDeleteShader(fragment); + if (compute != -1) GL20.glDeleteShader(compute); if (GL20.glGetProgrami(program, 35714) == 0) { System.err.println(GL20.glGetProgramInfoLog(program, 100)); @@ -130,28 +130,27 @@ public class ShaderManager { public String getShaderSource(String name, int type) { String ext = ""; - if(type == GL20.GL_VERTEX_SHADER) { + if (type == GL20.GL_VERTEX_SHADER) { ext = ".vert"; - } else if(type == GL20.GL_FRAGMENT_SHADER) { + } else if (type == GL20.GL_FRAGMENT_SHADER) { ext = ".frag"; - } else if(type == GL43.GL_COMPUTE_SHADER) { + } else if (type == GL43.GL_COMPUTE_SHADER) { ext = ".compute"; } else { return ""; } ResourceLocation location = new ResourceLocation(shaderLocation.getResourceDomain(), - shaderLocation.getResourcePath()+"/"+name+ext); - try(InputStream is = Minecraft.getMinecraft().getResourceManager().getResource(location).getInputStream()) { + shaderLocation.getResourcePath() + "/" + name + ext); + try (InputStream is = Minecraft.getMinecraft().getResourceManager().getResource(location).getInputStream()) { StringBuilder source = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; - while((line = br.readLine()) != null) { + while ((line = br.readLine()) != null) { source.append(line).append("\n"); } return source.toString(); - } catch(IOException e) { - } + } catch (IOException ignored) {} return ""; } } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/dungeons/DungeonBlocks.java b/src/main/java/io/github/moulberry/notenoughupdates/dungeons/DungeonBlocks.java index 890155e8..e29ccca4 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/dungeons/DungeonBlocks.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/dungeons/DungeonBlocks.java @@ -7,12 +7,17 @@ import io.github.moulberry.notenoughupdates.util.Utils; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.ScaledResolution; -import net.minecraft.client.renderer.*; -import net.minecraft.client.renderer.texture.*; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.OpenGlHelper; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.shader.Framebuffer; import net.minecraft.util.ResourceLocation; import org.lwjgl.BufferUtils; -import org.lwjgl.opengl.*; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; +import org.lwjgl.opengl.GL14; +import org.lwjgl.opengl.GL30; import java.nio.FloatBuffer; import java.util.HashMap; @@ -24,19 +29,19 @@ public class DungeonBlocks { private static Framebuffer framebufferBlocksTo = null; private static Framebuffer framebufferBlocksFrom = null; - private static HashMap framebuffersDynamicTo = new HashMap<>(); + private static final HashMap framebuffersDynamicTo = new HashMap<>(); public static HashMap framebuffersDynamicFrom = new HashMap<>(); - private static HashSet dynamicUpdated = new HashSet<>(); + private static final HashSet dynamicUpdated = new HashSet<>(); - private static FloatBuffer projectionMatrixOld = BufferUtils.createFloatBuffer(16); - private static FloatBuffer modelviewMatrixOld = BufferUtils.createFloatBuffer(16); + private static final FloatBuffer projectionMatrixOld = BufferUtils.createFloatBuffer(16); + private static final FloatBuffer modelviewMatrixOld = BufferUtils.createFloatBuffer(16); public static boolean textureExists() { return framebufferBlocksFrom != null && isOverriding(); } public static void bindTextureIfExists() { - if(textureExists()) { + if (textureExists()) { framebufferBlocksFrom.bindFramebufferTexture(); } } @@ -44,24 +49,24 @@ public class DungeonBlocks { public static boolean isOverriding() { return OpenGlHelper.isFramebufferEnabled() && NotEnoughUpdates.INSTANCE.config.dungeons.enableDungBlockOverlay && (NotEnoughUpdates.INSTANCE.config.dungeons.dungeonBlocksEverywhere || - (SBInfo.getInstance().getLocation() != null && SBInfo.getInstance().getLocation().equals("dungeon"))); + (SBInfo.getInstance().getLocation() != null && SBInfo.getInstance().getLocation().equals("dungeon"))); } public static boolean bindModifiedTexture(ResourceLocation location, int colour) { - if(!isOverriding()) { + if (!isOverriding()) { return false; } - if(Utils.disableCustomDungColours) { + if (Utils.disableCustomDungColours) { return false; } - if(((colour >> 24) & 0xFF) < 10) { + if (((colour >> 24) & 0xFF) < 10) { return false; } - String id = location.getResourceDomain()+":"+location.getResourcePath(); - if(dynamicUpdated.contains(id) && framebuffersDynamicFrom.containsKey(id)) { + String id = location.getResourceDomain() + ":" + location.getResourcePath(); + if (dynamicUpdated.contains(id) && framebuffersDynamicFrom.containsKey(id)) { framebuffersDynamicFrom.get(id).bindFramebufferTexture(); return true; } @@ -108,7 +113,7 @@ public class DungeonBlocks { if (Minecraft.getMinecraft().gameSettings.mipmapLevels >= 0) { GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL, Minecraft.getMinecraft().gameSettings.mipmapLevels); GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MIN_LOD, 0.0F); - GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LOD, (float)Minecraft.getMinecraft().gameSettings.mipmapLevels); + GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LOD, (float) Minecraft.getMinecraft().gameSettings.mipmapLevels); GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, 0.0F); GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D); } @@ -128,7 +133,7 @@ public class DungeonBlocks { GlStateManager.disableBlend(); GlStateManager.enableLighting(); return true; - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); } Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); @@ -137,7 +142,7 @@ public class DungeonBlocks { return false; } - private static HashMap dynamicPreloadMap = new HashMap<>(); + private static final HashMap dynamicPreloadMap = new HashMap<>(); static { dynamicPreloadMap.put(new ResourceLocation("textures/entity/bat.png"), @@ -153,13 +158,13 @@ public class DungeonBlocks { } public static void tick() { - if(!isOverriding() || Minecraft.getMinecraft().theWorld == null) { + if (!isOverriding() || Minecraft.getMinecraft().theWorld == null) { return; } dynamicUpdated.clear(); - for(Map.Entry entry : dynamicPreloadMap.entrySet()) { + for (Map.Entry entry : dynamicPreloadMap.entrySet()) { bindModifiedTexture(entry.getKey(), SpecialColour.specialToChromaRGB(entry.getValue())); } @@ -200,12 +205,12 @@ public class DungeonBlocks { spriteMap.put(Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite("minecraft:blocks/trip_wire"), SpecialColour.specialToChromaRGB(NotEnoughUpdates.INSTANCE.config.dungeons.dungTripWireColour)); - for(Map.Entry entry : spriteMap.entrySet()) { - if(((entry.getValue() >> 24) & 0xFF) < 10) continue; + for (Map.Entry entry : spriteMap.entrySet()) { + if (((entry.getValue() >> 24) & 0xFF) < 10) continue; TextureAtlasSprite tas = entry.getKey(); - Gui.drawRect((int)(w*tas.getMinU()), h-(int)(h*tas.getMaxV())-1, - (int)(w*tas.getMaxU())+1, h-(int)(h*tas.getMinV()), entry.getValue()); + Gui.drawRect((int) (w * tas.getMinU()), h - (int) (h * tas.getMaxV()) - 1, + (int) (w * tas.getMaxU()) + 1, h - (int) (h * tas.getMinV()), entry.getValue()); } ScaledResolution scaledResolution = new ScaledResolution(Minecraft.getMinecraft()); @@ -223,7 +228,7 @@ public class DungeonBlocks { if (Minecraft.getMinecraft().gameSettings.mipmapLevels >= 0) { GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL, Minecraft.getMinecraft().gameSettings.mipmapLevels); GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MIN_LOD, 0.0F); - GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LOD, (float)Minecraft.getMinecraft().gameSettings.mipmapLevels); + GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LOD, (float) Minecraft.getMinecraft().gameSettings.mipmapLevels); GL11.glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, 0.0F); GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D); } @@ -231,7 +236,7 @@ public class DungeonBlocks { Framebuffer from = checkFramebufferSizes(framebufferBlocksFrom, w, h); framebufferBlocksFrom = to; framebufferBlocksTo = from; - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); } Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); @@ -239,8 +244,8 @@ public class DungeonBlocks { } private static Framebuffer checkFramebufferSizes(Framebuffer framebuffer, int width, int height) { - if(framebuffer == null || framebuffer.framebufferWidth != width || framebuffer.framebufferHeight != height) { - if(framebuffer == null) { + if (framebuffer == null || framebuffer.framebufferWidth != width || framebuffer.framebufferHeight != height) { + if (framebuffer == null) { framebuffer = new Framebuffer(width, height, false); framebuffer.framebufferColor[0] = 1f; framebuffer.framebufferColor[1] = 0f; diff --git a/src/main/java/io/github/moulberry/notenoughupdates/dungeons/DungeonMap.java b/src/main/java/io/github/moulberry/notenoughupdates/dungeons/DungeonMap.java index 658f72df..6f42ab10 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/dungeons/DungeonMap.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/dungeons/DungeonMap.java @@ -2,10 +2,10 @@ package io.github.moulberry.notenoughupdates.dungeons; import com.google.common.collect.Iterables; import com.google.gson.JsonObject; +import io.github.moulberry.notenoughupdates.NotEnoughUpdates; import io.github.moulberry.notenoughupdates.core.BackgroundBlur; import io.github.moulberry.notenoughupdates.core.config.Position; import io.github.moulberry.notenoughupdates.util.NEUResourceManager; -import io.github.moulberry.notenoughupdates.NotEnoughUpdates; import io.github.moulberry.notenoughupdates.util.SpecialColour; import io.github.moulberry.notenoughupdates.util.Utils; import net.minecraft.block.material.MapColor; @@ -13,7 +13,10 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.entity.AbstractClientPlayer; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.ScaledResolution; -import net.minecraft.client.renderer.*; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.OpenGlHelper; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.resources.DefaultPlayerSkin; @@ -29,11 +32,12 @@ import net.minecraft.scoreboard.Score; import net.minecraft.scoreboard.ScoreObjective; import net.minecraft.scoreboard.ScorePlayerTeam; import net.minecraft.scoreboard.Scoreboard; -import net.minecraft.util.*; +import net.minecraft.util.Matrix4f; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.Vec4b; import net.minecraft.world.storage.MapData; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.event.world.WorldEvent; -import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL14; @@ -42,8 +46,8 @@ import java.awt.*; import java.io.BufferedReader; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; -import java.util.*; import java.util.List; +import java.util.*; public class DungeonMap { @@ -86,15 +90,15 @@ public class DungeonMap { private long lastDecorationsMillis = -1; private long lastLastDecorationsMillis = -1; - private Map playerEntityMapPositions = new HashMap<>(); - private Map playerMarkerMapPositions = new HashMap<>(); - private Set rawPlayerMarkerMapPositions = new HashSet<>(); - private Map playerMarkerMapPositionsLast = new HashMap<>(); - private HashMap playerIdMap = new HashMap<>(); + private final Map playerEntityMapPositions = new HashMap<>(); + private final Map playerMarkerMapPositions = new HashMap<>(); + private final Set rawPlayerMarkerMapPositions = new HashSet<>(); + private final Map playerMarkerMapPositionsLast = new HashMap<>(); + private final HashMap playerIdMap = new HashMap<>(); + + private final Map playerSkinMap = new HashMap<>(); - private Map playerSkinMap = new HashMap<>(); - - private class RoomOffset { + private static class RoomOffset { int x; int y; @@ -104,19 +108,19 @@ public class DungeonMap { } public RoomOffset left() { - return new RoomOffset(x-1, y); + return new RoomOffset(x - 1, y); } public RoomOffset right() { - return new RoomOffset(x+1, y); + return new RoomOffset(x + 1, y); } public RoomOffset up() { - return new RoomOffset(x, y-1); + return new RoomOffset(x, y - 1); } public RoomOffset down() { - return new RoomOffset(x, y+1); + return new RoomOffset(x, y + 1); } public RoomOffset[] getNeighbors() { @@ -141,7 +145,7 @@ public class DungeonMap { NONE, WALL, CORRIDOR, ROOM_DIVIDER } - private class RoomConnection { + private static class RoomConnection { RoomConnectionType type; Color colour; @@ -176,39 +180,39 @@ public class DungeonMap { RoomConnection down = new RoomConnection(RoomConnectionType.NONE, new Color(0, true)); public void renderNoRotate(int roomSize, int connectorSize, int rotation) { - if(tickColour != 0) { + if (tickColour != 0) { Color tick = new Color(tickColour, true); ResourceLocation indicatorTex = null; - if(tick.getRed() == 255 && tick.getGreen() == 255 && tick.getBlue() == 255) { + if (tick.getRed() == 255 && tick.getGreen() == 255 && tick.getBlue() == 255) { indicatorTex = WHITE_CHECK; - } else if(tick.getRed() == 0 && tick.getGreen() == 124 && tick.getBlue() == 0) { + } else if (tick.getRed() == 0 && tick.getGreen() == 124 && tick.getBlue() == 0) { indicatorTex = GREEN_CHECK; - } else if(tick.getRed() == 13 && tick.getGreen() == 13 && tick.getBlue() == 13) { + } else if (tick.getRed() == 13 && tick.getGreen() == 13 && tick.getBlue() == 13) { indicatorTex = QUESTION; - } else if(tick.getRed() == 255 && tick.getGreen() == 0 && tick.getBlue() == 0) { + } else if (tick.getRed() == 255 && tick.getGreen() == 0 && tick.getBlue() == 0) { indicatorTex = CROSS; } - if(indicatorTex != null) { + if (indicatorTex != null) { Minecraft.getMinecraft().getTextureManager().bindTexture(indicatorTex); float x = 0; float y = 0; - if(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmCenterCheck) { - if(fillCorner) { - x += -(roomSize+connectorSize)/2f*Math.cos(Math.toRadians(rotation-45))*1.414f; - y += (roomSize+connectorSize)/2f*Math.sin(Math.toRadians(rotation-45))*1.414; + if (NotEnoughUpdates.INSTANCE.config.dungeonMap.dmCenterCheck) { + if (fillCorner) { + x += -(roomSize + connectorSize) / 2f * Math.cos(Math.toRadians(rotation - 45)) * 1.414f; + y += (roomSize + connectorSize) / 2f * Math.sin(Math.toRadians(rotation - 45)) * 1.414; } - if(down.type == RoomConnectionType.ROOM_DIVIDER && right.type != RoomConnectionType.ROOM_DIVIDER) { - x += -(roomSize+connectorSize)/2f*Math.sin(Math.toRadians(rotation)); - y += -(roomSize+connectorSize)/2f*Math.cos(Math.toRadians(rotation)); - } else if(down.type != RoomConnectionType.ROOM_DIVIDER && right.type == RoomConnectionType.ROOM_DIVIDER) { - x += -(roomSize+connectorSize)/2f*Math.cos(Math.toRadians(rotation)); - y += (roomSize+connectorSize)/2f*Math.sin(Math.toRadians(rotation)); + if (down.type == RoomConnectionType.ROOM_DIVIDER && right.type != RoomConnectionType.ROOM_DIVIDER) { + x += -(roomSize + connectorSize) / 2f * Math.sin(Math.toRadians(rotation)); + y += -(roomSize + connectorSize) / 2f * Math.cos(Math.toRadians(rotation)); + } else if (down.type != RoomConnectionType.ROOM_DIVIDER && right.type == RoomConnectionType.ROOM_DIVIDER) { + x += -(roomSize + connectorSize) / 2f * Math.cos(Math.toRadians(rotation)); + y += (roomSize + connectorSize) / 2f * Math.sin(Math.toRadians(rotation)); } } GlStateManager.translate(x, y, 0); - if(!NotEnoughUpdates.INSTANCE.config.dungeonMap.dmOrientCheck) { - GlStateManager.rotate(-rotation+180, 0, 0, 1); + if (!NotEnoughUpdates.INSTANCE.config.dungeonMap.dmOrientCheck) { + GlStateManager.rotate(-rotation + 180, 0, 0, 1); } GlStateManager.pushMatrix(); @@ -217,8 +221,8 @@ public class DungeonMap { Utils.drawTexturedRect(-5, -5, 10, 10, GL11.GL_NEAREST); GlStateManager.popMatrix(); - if(!NotEnoughUpdates.INSTANCE.config.dungeonMap.dmOrientCheck) { - GlStateManager.rotate(rotation-180, 0, 0, 1); + if (!NotEnoughUpdates.INSTANCE.config.dungeonMap.dmOrientCheck) { + GlStateManager.rotate(rotation - 180, 0, 0, 1); } GlStateManager.translate(-x, -y, 0); } @@ -227,25 +231,25 @@ public class DungeonMap { public void render(int roomSize, int connectorSize) { ResourceLocation roomTex = null; - if(colour.getRed() == 114 && colour.getGreen() == 67 && colour.getBlue() == 27) { + if (colour.getRed() == 114 && colour.getGreen() == 67 && colour.getBlue() == 27) { roomTex = ROOM_BROWN; - } else if(colour.getRed() == 65 && colour.getGreen() == 65 && colour.getBlue() == 65) { + } else if (colour.getRed() == 65 && colour.getGreen() == 65 && colour.getBlue() == 65) { roomTex = ROOM_GRAY; - } else if(colour.getRed() == 0 && colour.getGreen() == 124 && colour.getBlue() == 0) { + } else if (colour.getRed() == 0 && colour.getGreen() == 124 && colour.getBlue() == 0) { roomTex = ROOM_GREEN; - } else if(colour.getRed() == 242 && colour.getGreen() == 127 && colour.getBlue() == 165) { + } else if (colour.getRed() == 242 && colour.getGreen() == 127 && colour.getBlue() == 165) { roomTex = ROOM_PINK; - } else if(colour.getRed() == 178 && colour.getGreen() == 76 && colour.getBlue() == 216) { + } else if (colour.getRed() == 178 && colour.getGreen() == 76 && colour.getBlue() == 216) { roomTex = ROOM_PURPLE; - } else if(colour.getRed() == 255 && colour.getGreen() == 0 && colour.getBlue() == 0) { + } else if (colour.getRed() == 255 && colour.getGreen() == 0 && colour.getBlue() == 0) { roomTex = ROOM_RED; - } else if(colour.getRed() == 229 && colour.getGreen() == 229 && colour.getBlue() == 51) { + } else if (colour.getRed() == 229 && colour.getGreen() == 229 && colour.getBlue() == 51) { roomTex = ROOM_YELLOW; - } else if(colour.getRed() == 216 && colour.getGreen() == 127 && colour.getBlue() == 51) { + } else if (colour.getRed() == 216 && colour.getGreen() == 127 && colour.getBlue() == 51) { roomTex = ROOM_ORANGE; } - if(roomTex != null) { + if (roomTex != null) { Minecraft.getMinecraft().getTextureManager().bindTexture(roomTex); GlStateManager.color(1, 1, 1, 1); Utils.drawTexturedRect(0, 0, roomSize, roomSize, GL11.GL_LINEAR); @@ -253,72 +257,72 @@ public class DungeonMap { Gui.drawRect(0, 0, roomSize, roomSize, colour.getRGB()); } - if(fillCorner) { + if (fillCorner) { GlStateManager.color(1, 1, 1, 1); Minecraft.getMinecraft().getTextureManager().bindTexture(CORNER_BROWN); Utils.drawTexturedRect(roomSize, roomSize, connectorSize, connectorSize, GL11.GL_NEAREST); } - for(int k=0; k<2; k++) { + for (int k = 0; k < 2; k++) { RoomConnection connection = down; - if(k == 1) connection = right; + if (k == 1) connection = right; + + if (connection.type == RoomConnectionType.NONE || connection.type == RoomConnectionType.WALL) continue; - if(connection.type == RoomConnectionType.NONE || connection.type == RoomConnectionType.WALL) continue; - ResourceLocation corridorTex = null; - if(connection.colour.getRed() == 114 && connection.colour.getGreen() == 67 && connection.colour.getBlue() == 27) { + if (connection.colour.getRed() == 114 && connection.colour.getGreen() == 67 && connection.colour.getBlue() == 27) { corridorTex = connection.type == RoomConnectionType.CORRIDOR ? CORRIDOR_BROWN : DIVIDER_BROWN; - } else if(connection.colour.getRed() == 65 && connection.colour.getGreen() == 65 && connection.colour.getBlue() == 65) { + } else if (connection.colour.getRed() == 65 && connection.colour.getGreen() == 65 && connection.colour.getBlue() == 65) { corridorTex = CORRIDOR_GRAY; - } else if(connection.colour.getRed() == 0 && connection.colour.getGreen() == 124 && connection.colour.getBlue() == 0) { + } else if (connection.colour.getRed() == 0 && connection.colour.getGreen() == 124 && connection.colour.getBlue() == 0) { corridorTex = CORRIDOR_GREEN; - } else if(connection.colour.getRed() == 242 && connection.colour.getGreen() == 127 && connection.colour.getBlue() == 165) { + } else if (connection.colour.getRed() == 242 && connection.colour.getGreen() == 127 && connection.colour.getBlue() == 165) { corridorTex = CORRIDOR_PINK; - } else if(connection.colour.getRed() == 178 && connection.colour.getGreen() == 76 && connection.colour.getBlue() == 216) { + } else if (connection.colour.getRed() == 178 && connection.colour.getGreen() == 76 && connection.colour.getBlue() == 216) { corridorTex = CORRIDOR_PURPLE; - } else if(connection.colour.getRed() == 255 && connection.colour.getGreen() == 0 && connection.colour.getBlue() == 0) { + } else if (connection.colour.getRed() == 255 && connection.colour.getGreen() == 0 && connection.colour.getBlue() == 0) { corridorTex = CORRIDOR_RED; - } else if(connection.colour.getRed() == 229 && connection.colour.getGreen() == 229 && connection.colour.getBlue() == 51) { + } else if (connection.colour.getRed() == 229 && connection.colour.getGreen() == 229 && connection.colour.getBlue() == 51) { corridorTex = CORRIDOR_YELLOW; - } else if(connection.colour.getRed() == 216 && connection.colour.getGreen() == 127 && connection.colour.getBlue() == 51) { + } else if (connection.colour.getRed() == 216 && connection.colour.getGreen() == 127 && connection.colour.getBlue() == 51) { corridorTex = CORRIDOR_ORANGE; } - if(corridorTex == null) { + if (corridorTex == null) { int xOffset = 0; int yOffset = 0; int width = 0; int height = 0; - if(connection == right) { + if (connection == right) { xOffset = roomSize; width = connectorSize; height = roomSize; - if(connection.type == RoomConnectionType.CORRIDOR) { + if (connection.type == RoomConnectionType.CORRIDOR) { height = 8; yOffset += 4; } - } else if(connection == down) { + } else if (connection == down) { yOffset = roomSize; width = roomSize; height = connectorSize; - if(connection.type == RoomConnectionType.CORRIDOR) { + if (connection.type == RoomConnectionType.CORRIDOR) { width = 8; xOffset += 4; } } - Gui.drawRect(xOffset, yOffset, xOffset+width, yOffset+height, connection.colour.getRGB()); + Gui.drawRect(xOffset, yOffset, xOffset + width, yOffset + height, connection.colour.getRGB()); } else { GlStateManager.color(1, 1, 1, 1); Minecraft.getMinecraft().getTextureManager().bindTexture(corridorTex); GlStateManager.pushMatrix(); - if(connection==right) { - GlStateManager.translate(roomSize/2f, roomSize/2f, 0); + if (connection == right) { + GlStateManager.translate(roomSize / 2f, roomSize / 2f, 0); GlStateManager.rotate(-90, 0, 0, 1); - GlStateManager.translate(-roomSize/2f, -roomSize/2f, 0); + GlStateManager.translate(-roomSize / 2f, -roomSize / 2f, 0); } Utils.drawTexturedRect(0, roomSize, roomSize, connectorSize, GL11.GL_NEAREST); GlStateManager.popMatrix(); @@ -335,8 +339,8 @@ public class DungeonMap { public static Shader mapShader = null; private static Framebuffer checkFramebufferSizes(Framebuffer framebuffer, int width, int height) { - if(framebuffer == null || framebuffer.framebufferWidth != width || framebuffer.framebufferHeight != height) { - if(framebuffer == null) { + if (framebuffer == null || framebuffer.framebufferWidth != width || framebuffer.framebufferHeight != height) { + if (framebuffer == null) { framebuffer = new Framebuffer(width, height, true); } else { framebuffer.createBindFramebuffer(width, height); @@ -347,44 +351,45 @@ public class DungeonMap { } private static void upload(Shader shader, int width, int height, int scale, float radiusSq) { - if(shader == null) return; + if (shader == null) return; shader.getShaderManager().getShaderUniformOrDefault("ProjMat").set(projectionMatrix); - shader.getShaderManager().getShaderUniformOrDefault("InSize").set(width*scale, height*scale); + shader.getShaderManager().getShaderUniformOrDefault("InSize").set(width * scale, height * scale); shader.getShaderManager().getShaderUniformOrDefault("OutSize").set(width, height); - shader.getShaderManager().getShaderUniformOrDefault("ScreenSize").set((float)width, (float)height); + shader.getShaderManager().getShaderUniformOrDefault("ScreenSize").set((float) width, (float) height); shader.getShaderManager().getShaderUniformOrDefault("radiusSq").set(radiusSq); } public int getRenderRoomSize() { double roomSizeOption = NotEnoughUpdates.INSTANCE.config.dungeonMap.dmRoomSize; - if(roomSizeOption <= 0) return 12; - return 12 + (int)Math.round(roomSizeOption*4); + if (roomSizeOption <= 0) return 12; + return 12 + (int) Math.round(roomSizeOption * 4); } public int getRenderConnSize() { - int roomSizeOption = (int)Math.round(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmRoomSize); - if(roomSizeOption <= 0) return 3; + int roomSizeOption = Math.round(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmRoomSize); + if (roomSizeOption <= 0) return 3; return 3 + roomSizeOption; } - private HashMap borderRadiusCache = new HashMap<>(); + private final HashMap borderRadiusCache = new HashMap<>(); + public float getBorderRadius() { int borderSizeOption = Math.round(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderSize); String sizeId = borderSizeOption == 0 ? "small" : borderSizeOption == 2 ? "large" : "medium"; int style = NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderStyle; - if(borderRadiusCache.containsKey(style)) { + if (borderRadiusCache.containsKey(style)) { return borderRadiusCache.get(style); } - try(BufferedReader reader = new BufferedReader(new InputStreamReader(Minecraft.getMinecraft().getResourceManager().getResource( - new ResourceLocation("notenoughupdates:dungeon_map/borders/"+sizeId+"/"+style+".json")).getInputStream(), StandardCharsets.UTF_8))) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(Minecraft.getMinecraft().getResourceManager().getResource( + new ResourceLocation("notenoughupdates:dungeon_map/borders/" + sizeId + "/" + style + ".json")).getInputStream(), StandardCharsets.UTF_8))) { JsonObject json = NotEnoughUpdates.INSTANCE.manager.gson.fromJson(reader, JsonObject.class); float radiusSq = json.get("radiusSq").getAsFloat(); borderRadiusCache.put(style, radiusSq); return radiusSq; - } catch(Exception ignored) { } + } catch (Exception ignored) {} borderRadiusCache.put(style, 1f); return 1f; @@ -410,7 +415,7 @@ public class DungeonMap { int minRoomY = 999; int maxRoomX = -999; int maxRoomY = -999; - for(RoomOffset offset : roomMap.keySet()) { + for (RoomOffset offset : roomMap.keySet()) { minRoomX = Math.min(offset.x, minRoomX); minRoomY = Math.min(offset.y, minRoomY); maxRoomX = Math.max(offset.x, maxRoomX); @@ -423,43 +428,43 @@ public class DungeonMap { int renderConnSize = getRenderConnSize(); MapPosition playerPos = null; - if(playerEntityMapPositions.containsKey(Minecraft.getMinecraft().thePlayer.getName())) { + if (playerEntityMapPositions.containsKey(Minecraft.getMinecraft().thePlayer.getName())) { playerPos = playerEntityMapPositions.get(Minecraft.getMinecraft().thePlayer.getName()); - } else if(playerMarkerMapPositions.containsKey(Minecraft.getMinecraft().thePlayer.getName())) { + } else if (playerMarkerMapPositions.containsKey(Minecraft.getMinecraft().thePlayer.getName())) { playerPos = playerMarkerMapPositions.get(Minecraft.getMinecraft().thePlayer.getName()); } int rotation = 180; - if(playerPos != null && NotEnoughUpdates.INSTANCE.config.dungeonMap.dmRotatePlayer) { - rotation = (int)playerPos.rotation; + if (playerPos != null && NotEnoughUpdates.INSTANCE.config.dungeonMap.dmRotatePlayer) { + rotation = (int) playerPos.rotation; } int mapSizeX; int mapSizeY; - if(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderStyle <= 1) { - mapSizeX = 80 + Math.round(40*NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderSize); + if (NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderStyle <= 1) { + mapSizeX = 80 + Math.round(40 * NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderSize); } else { mapSizeX = borderSizeOption == 0 ? 90 : borderSizeOption == 1 ? 120 : borderSizeOption == 2 ? 160 : 240; } mapSizeY = mapSizeX; - int roomsSizeX = (maxRoomX-minRoomX)*(renderRoomSize+renderConnSize)+renderRoomSize; - int roomsSizeY = (maxRoomY-minRoomY)*(renderRoomSize+renderConnSize)+renderRoomSize; - int mapCenterX = mapSizeX/2; - int mapCenterY = mapSizeY/2; + int roomsSizeX = (maxRoomX - minRoomX) * (renderRoomSize + renderConnSize) + renderRoomSize; + int roomsSizeY = (maxRoomY - minRoomY) * (renderRoomSize + renderConnSize) + renderRoomSize; + int mapCenterX = mapSizeX / 2; + int mapCenterY = mapSizeY / 2; int scaleFactor = 8; - projectionMatrix = Utils.createProjectionMatrix(mapSizeX*scaleFactor, mapSizeY*scaleFactor); - mapFramebuffer1 = checkFramebufferSizes(mapFramebuffer1, mapSizeX*scaleFactor, mapSizeY*scaleFactor); - mapFramebuffer2 = checkFramebufferSizes(mapFramebuffer2, mapSizeX*scaleFactor, mapSizeY*scaleFactor); + projectionMatrix = Utils.createProjectionMatrix(mapSizeX * scaleFactor, mapSizeY * scaleFactor); + mapFramebuffer1 = checkFramebufferSizes(mapFramebuffer1, mapSizeX * scaleFactor, mapSizeY * scaleFactor); + mapFramebuffer2 = checkFramebufferSizes(mapFramebuffer2, mapSizeX * scaleFactor, mapSizeY * scaleFactor); mapFramebuffer1.framebufferColor[1] = 0; mapFramebuffer1.framebufferColor[2] = 0; try { - if(mapShader == null) { + if (mapShader == null) { mapShader = new Shader(new NEUResourceManager(Minecraft.getMinecraft().getResourceManager()), "dungeonmap", mapFramebuffer1, mapFramebuffer2); } - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); Utils.pushGuiScale(-1); return; @@ -467,24 +472,25 @@ public class DungeonMap { int backgroundColour = SpecialColour.specialToChromaRGB(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBackgroundColour); - mapFramebuffer1.framebufferColor[0] = ((backgroundColour >> 16) & 0xFF)/255f; - mapFramebuffer1.framebufferColor[1] = ((backgroundColour >> 8) & 0xFF)/255f; - mapFramebuffer1.framebufferColor[2] = (backgroundColour & 0xFF)/255f; - mapFramebuffer2.framebufferColor[0] = ((backgroundColour >> 16) & 0xFF)/255f; - mapFramebuffer2.framebufferColor[1] = ((backgroundColour >> 8) & 0xFF)/255f; - mapFramebuffer2.framebufferColor[2] = (backgroundColour & 0xFF)/255f; + mapFramebuffer1.framebufferColor[0] = ((backgroundColour >> 16) & 0xFF) / 255f; + mapFramebuffer1.framebufferColor[1] = ((backgroundColour >> 8) & 0xFF) / 255f; + mapFramebuffer1.framebufferColor[2] = (backgroundColour & 0xFF) / 255f; + mapFramebuffer2.framebufferColor[0] = ((backgroundColour >> 16) & 0xFF) / 255f; + mapFramebuffer2.framebufferColor[1] = ((backgroundColour >> 8) & 0xFF) / 255f; + mapFramebuffer2.framebufferColor[2] = (backgroundColour & 0xFF) / 255f; try { - if(useFb) { + if (useFb) { mapFramebuffer1.framebufferClear(); mapFramebuffer2.framebufferClear(); } - GlStateManager.pushMatrix(); { - if(useFb) { + GlStateManager.pushMatrix(); + { + if (useFb) { GlStateManager.matrixMode(5889); GlStateManager.loadIdentity(); - GlStateManager.ortho(0.0D, mapSizeX*scaleFactor, mapSizeY*scaleFactor, 0.0D, 1000.0D, 3000.0D); + GlStateManager.ortho(0.0D, mapSizeX * scaleFactor, mapSizeY * scaleFactor, 0.0D, 1000.0D, 3000.0D); GlStateManager.matrixMode(5888); GlStateManager.loadIdentity(); GlStateManager.translate(0.0F, 0.0F, -2000.0F); @@ -496,47 +502,47 @@ public class DungeonMap { GlStateManager.disableBlend(); } else { GL11.glEnable(GL11.GL_SCISSOR_TEST); - GL11.glScissor((centerX-mapSizeX/2)*2, Minecraft.getMinecraft().displayHeight-(centerY+mapSizeY/2)*2, mapSizeX*2, mapSizeY*2); + GL11.glScissor((centerX - mapSizeX / 2) * 2, Minecraft.getMinecraft().displayHeight - (centerY + mapSizeY / 2) * 2, mapSizeX * 2, mapSizeY * 2); - GlStateManager.translate(centerX-mapSizeX/2, centerY-mapSizeY/2, 100); + GlStateManager.translate(centerX - mapSizeX / 2, centerY - mapSizeY / 2, 100); } - if(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBackgroundBlur > 0.1) { - GlStateManager.translate(-centerX+mapSizeX/2, -centerY+mapSizeY/2, 0); + if (NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBackgroundBlur > 0.1) { + GlStateManager.translate(-centerX + mapSizeX / 2, -centerY + mapSizeY / 2, 0); BackgroundBlur.renderBlurredBackground(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBackgroundBlur, scaledResolution.getScaledWidth(), scaledResolution.getScaledHeight(), - centerX-mapSizeX/2, centerY-mapSizeY/2, mapSizeX, mapSizeY); + centerX - mapSizeX / 2, centerY - mapSizeY / 2, mapSizeX, mapSizeY); BackgroundBlur.markDirty(); - GlStateManager.translate(centerX-mapSizeX/2, centerY-mapSizeY/2, 0); + GlStateManager.translate(centerX - mapSizeX / 2, centerY - mapSizeY / 2, 0); } GlStateManager.translate(mapCenterX, mapCenterY, 10); - if(!useFb || NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBackgroundBlur > 0.1) { + if (!useFb || NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBackgroundBlur > 0.1) { GlStateManager.enableBlend(); GL14.glBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA); } Utils.drawRectNoBlend(-mapCenterX, -mapCenterY, mapCenterX, mapCenterY, backgroundColour); - GlStateManager.rotate(-rotation+180, 0, 0, 1); + GlStateManager.rotate(-rotation + 180, 0, 0, 1); - if(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmCenterPlayer && playerPos != null) { + if (NotEnoughUpdates.INSTANCE.config.dungeonMap.dmCenterPlayer && playerPos != null) { float x = playerPos.getRenderX(); float y = playerPos.getRenderY(); - x -= minRoomX*(renderRoomSize+renderConnSize); - y -= minRoomY*(renderRoomSize+renderConnSize); + x -= minRoomX * (renderRoomSize + renderConnSize); + y -= minRoomY * (renderRoomSize + renderConnSize); GlStateManager.translate(-x, -y, 0); } else { - GlStateManager.translate(-roomsSizeX/2, -roomsSizeY/2, 0); + GlStateManager.translate(-roomsSizeX / 2, -roomsSizeY / 2, 0); } - for(Map.Entry entry : roomMap.entrySet()) { + for (Map.Entry entry : roomMap.entrySet()) { RoomOffset roomOffset = entry.getKey(); Room room = entry.getValue(); - int x = (roomOffset.x-minRoomX)*(renderRoomSize+renderConnSize); - int y = (roomOffset.y-minRoomY)*(renderRoomSize+renderConnSize); + int x = (roomOffset.x - minRoomX) * (renderRoomSize + renderConnSize); + int y = (roomOffset.y - minRoomY) * (renderRoomSize + renderConnSize); GlStateManager.pushMatrix(); GlStateManager.translate(x, y, 0); @@ -547,22 +553,22 @@ public class DungeonMap { GlStateManager.popMatrix(); } - GlStateManager.translate(-mapCenterX+roomsSizeX/2f, -mapCenterY+roomsSizeY/2f, 0); + GlStateManager.translate(-mapCenterX + roomsSizeX / 2f, -mapCenterY + roomsSizeY / 2f, 0); GlStateManager.translate(mapCenterX, mapCenterY, 0); - GlStateManager.rotate(rotation-180, 0, 0, 1); + GlStateManager.rotate(rotation - 180, 0, 0, 1); GlStateManager.translate(-mapCenterX, -mapCenterY, 0); GlStateManager.translate(mapCenterX, mapCenterY, 0); - for(Map.Entry entry : roomMap.entrySet()) { + for (Map.Entry entry : roomMap.entrySet()) { RoomOffset roomOffset = entry.getKey(); Room room = entry.getValue(); - float x = (roomOffset.x-minRoomX)*(renderRoomSize+renderConnSize)-roomsSizeX/2f+renderRoomSize/2f; - float y = (roomOffset.y-minRoomY)*(renderRoomSize+renderConnSize)-roomsSizeY/2f+renderRoomSize/2f; - float x2 = (float)(-x*Math.cos(Math.toRadians(-rotation)) + y*Math.sin(Math.toRadians(-rotation))); - float y2 = (float)(-x*Math.sin(Math.toRadians(-rotation)) - y*Math.cos(Math.toRadians(-rotation))); + float x = (roomOffset.x - minRoomX) * (renderRoomSize + renderConnSize) - roomsSizeX / 2f + renderRoomSize / 2f; + float y = (roomOffset.y - minRoomY) * (renderRoomSize + renderConnSize) - roomsSizeY / 2f + renderRoomSize / 2f; + float x2 = (float) (-x * Math.cos(Math.toRadians(-rotation)) + y * Math.sin(Math.toRadians(-rotation))); + float y2 = (float) (-x * Math.sin(Math.toRadians(-rotation)) - y * Math.cos(Math.toRadians(-rotation))); GlStateManager.pushMatrix(); GlStateManager.translate(x2, y2, 0); @@ -574,20 +580,19 @@ public class DungeonMap { GlStateManager.popMatrix(); } - GlStateManager.translate(-mapCenterX, -mapCenterY, 0); GlStateManager.translate(mapCenterX, mapCenterY, 0); - GlStateManager.rotate(-rotation+180, 0, 0, 1); + GlStateManager.rotate(-rotation + 180, 0, 0, 1); GlStateManager.translate(-mapCenterX, -mapCenterY, 0); - GlStateManager.translate(mapCenterX-roomsSizeX/2f, mapCenterY-roomsSizeY/2f, 0); + GlStateManager.translate(mapCenterX - roomsSizeX / 2f, mapCenterY - roomsSizeY / 2f, 0); Tessellator tessellator = Tessellator.getInstance(); WorldRenderer worldrenderer = tessellator.getWorldRenderer(); int k = 0; - for(Map.Entry entry : playerMarkerMapPositions.entrySet()) { + for (Map.Entry entry : playerMarkerMapPositions.entrySet()) { String name = entry.getKey(); MapPosition pos = entry.getValue(); float x = pos.getRenderX(); @@ -595,7 +600,7 @@ public class DungeonMap { float angle = pos.rotation; boolean doInterp = NotEnoughUpdates.INSTANCE.config.dungeonMap.dmPlayerInterp; - if(!isFloorOne && playerEntityMapPositions.containsKey(name)) { + if (!isFloorOne && playerEntityMapPositions.containsKey(name)) { MapPosition entityPos = playerEntityMapPositions.get(name); angle = entityPos.rotation; @@ -619,23 +624,23 @@ public class DungeonMap { doInterp = false; } - float minU = 3/4f; + float minU = 3 / 4f; float minV = 0; - if(name.equals(Minecraft.getMinecraft().thePlayer.getName())) { - minU = 1/4f; + if (name.equals(Minecraft.getMinecraft().thePlayer.getName())) { + minU = 1 / 4f; } - float maxU = minU + 1/4f; - float maxV = minV + 1/4f; + float maxU = minU + 1 / 4f; + float maxV = minV + 1 / 4f; - if(doInterp && playerMarkerMapPositionsLast.containsKey(name)) { + if (doInterp && playerMarkerMapPositionsLast.containsKey(name)) { MapPosition last = playerMarkerMapPositionsLast.get(name); float xLast = last.getRenderX(); float yLast = last.getRenderY(); - float distSq = (x-xLast) * (x-xLast) + (y-yLast) * (y-yLast); - if (distSq < renderRoomSize*renderRoomSize/4f) { + float distSq = (x - xLast) * (x - xLast) + (y - yLast) * (y - yLast); + if (distSq < renderRoomSize * renderRoomSize / 4f) { float angleLast = last.rotation; if (angle > 180 && angleLast < 180) angleLast += 360; if (angleLast > 180 && angle < 180) angle += 360; @@ -654,31 +659,31 @@ public class DungeonMap { boolean headLayer = false; int pixelWidth = 8; int pixelHeight = 8; - if(renderRoomSize >= 24) { + if (renderRoomSize >= 24) { pixelWidth = pixelHeight = 12; } GlStateManager.color(1, 1, 1, 1); - if((!NotEnoughUpdates.INSTANCE.config.dungeons.showOwnHeadAsMarker || - playerMarkerMapPositions.size() <= 1 || minU != 1/4f) && + if ((!NotEnoughUpdates.INSTANCE.config.dungeons.showOwnHeadAsMarker || + playerMarkerMapPositions.size() <= 1 || minU != 1 / 4f) && NotEnoughUpdates.INSTANCE.config.dungeonMap.dmPlayerHeads >= 1 && playerSkinMap.containsKey(entry.getKey())) { Minecraft.getMinecraft().getTextureManager().bindTexture(playerSkinMap.get(entry.getKey())); - minU = 8/64f; - minV = 8/64f; - maxU = 16/64f; - maxV = 16/64f; + minU = 8 / 64f; + minV = 8 / 64f; + maxU = 16 / 64f; + maxV = 16 / 64f; headLayer = true; - if(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmPlayerHeads >= 2) { + if (NotEnoughUpdates.INSTANCE.config.dungeonMap.dmPlayerHeads >= 2) { blackBorder = true; } } else { Minecraft.getMinecraft().getTextureManager().bindTexture(mapIcons); } - x -= minRoomX*(renderRoomSize+renderConnSize); - y -= minRoomY*(renderRoomSize+renderConnSize); + x -= minRoomX * (renderRoomSize + renderConnSize); + y -= minRoomY * (renderRoomSize + renderConnSize); GlStateManager.pushMatrix(); @@ -692,50 +697,52 @@ public class DungeonMap { GlStateManager.rotate(angle, 0.0F, 0.0F, 1.0F); GlStateManager.translate(-0.5F, 0.5F, 0.0F); - if(blackBorder) { - Gui.drawRect(-pixelWidth/2-1,-pixelHeight/2-1, pixelWidth/2+1, pixelHeight/2+1, 0xff111111); + if (blackBorder) { + Gui.drawRect(-pixelWidth / 2 - 1, -pixelHeight / 2 - 1, pixelWidth / 2 + 1, pixelHeight / 2 + 1, 0xff111111); GlStateManager.color(1, 1, 1, 1); } worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos(-pixelWidth/2f, pixelHeight/2f, 30+((float)k * -0.005F)).tex(minU, minV).endVertex(); - worldrenderer.pos(pixelWidth/2f, pixelHeight/2f, 30+((float)k * -0.005F)).tex(maxU, minV).endVertex(); - worldrenderer.pos(pixelWidth/2f, -pixelHeight/2f, 30+((float)k * -0.005F)).tex(maxU, maxV).endVertex(); - worldrenderer.pos(-pixelWidth/2f, -pixelHeight/2f, 30+((float)k * -0.005F)).tex(minU, maxV).endVertex(); + worldrenderer.pos(-pixelWidth / 2f, pixelHeight / 2f, 30 + ((float) k * -0.005F)).tex(minU, minV).endVertex(); + worldrenderer.pos(pixelWidth / 2f, pixelHeight / 2f, 30 + ((float) k * -0.005F)).tex(maxU, minV).endVertex(); + worldrenderer.pos(pixelWidth / 2f, -pixelHeight / 2f, 30 + ((float) k * -0.005F)).tex(maxU, maxV).endVertex(); + worldrenderer.pos(-pixelWidth / 2f, -pixelHeight / 2f, 30 + ((float) k * -0.005F)).tex(minU, maxV).endVertex(); tessellator.draw(); - if(headLayer) { + if (headLayer) { worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos(-pixelWidth/2f, pixelHeight/2f, 30+((float)k * -0.005F)+0.001f).tex(minU+0.5f, minV).endVertex(); - worldrenderer.pos(pixelWidth/2f, pixelHeight/2f, 30+((float)k * -0.005F)+0.001f).tex(maxU+0.5f, minV).endVertex(); - worldrenderer.pos(pixelWidth/2f, -pixelHeight/2f, 30+((float)k * -0.005F)+0.001f).tex(maxU+0.5f, maxV).endVertex(); - worldrenderer.pos(-pixelWidth/2f, -pixelHeight/2f, 30+((float)k * -0.005F)+0.001f).tex(minU+0.5f, maxV).endVertex(); + worldrenderer.pos(-pixelWidth / 2f, pixelHeight / 2f, 30 + ((float) k * -0.005F) + 0.001f).tex(minU + 0.5f, minV).endVertex(); + worldrenderer.pos(pixelWidth / 2f, pixelHeight / 2f, 30 + ((float) k * -0.005F) + 0.001f).tex(maxU + 0.5f, minV).endVertex(); + worldrenderer.pos(pixelWidth / 2f, -pixelHeight / 2f, 30 + ((float) k * -0.005F) + 0.001f).tex(maxU + 0.5f, maxV).endVertex(); + worldrenderer.pos(-pixelWidth / 2f, -pixelHeight / 2f, 30 + ((float) k * -0.005F) + 0.001f).tex(minU + 0.5f, maxV).endVertex(); tessellator.draw(); } GlStateManager.popMatrix(); k--; } - if(useFb) { + if (useFb) { GlStateManager.enableBlend(); GL14.glBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA); } else { GL11.glDisable(GL11.GL_SCISSOR_TEST); } - } GlStateManager.popMatrix(); + } + GlStateManager.popMatrix(); - if(useFb) { + if (useFb) { Framebuffer renderFromBuffer = mapFramebuffer1; - if(useShd) { - GlStateManager.pushMatrix(); { + if (useShd) { + GlStateManager.pushMatrix(); + { try { upload(mapShader, mapSizeX, mapSizeY, scaleFactor, getBorderRadius()); mapShader.setProjectionMatrix(projectionMatrix); mapShader.loadShader(0); renderFromBuffer = mapFramebuffer2; - } catch(Exception e) { - } - } GlStateManager.popMatrix(); + } catch (Exception ignored) {} + } + GlStateManager.popMatrix(); } Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); @@ -745,7 +752,7 @@ public class DungeonMap { GlStateManager.translate(centerX, centerY, 100); renderFromBuffer.bindFramebufferTexture(); - Utils.drawTexturedRect(-mapSizeX/2, -mapSizeY/2, mapSizeX, mapSizeY, + Utils.drawTexturedRect(-mapSizeX / 2, -mapSizeY / 2, mapSizeX, mapSizeY, 0, 1, 1, 0, GL11.GL_NEAREST); GlStateManager.bindTexture(0); @@ -756,61 +763,61 @@ public class DungeonMap { GlStateManager.translate(centerX, centerY, 100); - if(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmChromaBorder) { + if (NotEnoughUpdates.INSTANCE.config.dungeonMap.dmChromaBorder) { int colour = SpecialColour.specialToChromaRGB(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderColour); - Gui.drawRect(-mapCenterX-2, -mapCenterY-2, -mapCenterX, -mapCenterY, + Gui.drawRect(-mapCenterX - 2, -mapCenterY - 2, -mapCenterX, -mapCenterY, colour); //topleft - Gui.drawRect(-mapCenterX-2, mapCenterY+2, -mapCenterX, mapCenterY, + Gui.drawRect(-mapCenterX - 2, mapCenterY + 2, -mapCenterX, mapCenterY, SpecialColour.rotateHue(colour, -180)); //bottomleft - Gui.drawRect(mapCenterX, -mapCenterY-2, mapCenterX+2, mapCenterY, + Gui.drawRect(mapCenterX, -mapCenterY - 2, mapCenterX + 2, mapCenterY, SpecialColour.rotateHue(colour, -180)); //topright - Gui.drawRect(mapCenterX, mapCenterY, mapCenterX+2, mapCenterY+2, + Gui.drawRect(mapCenterX, mapCenterY, mapCenterX + 2, mapCenterY + 2, colour); //bottomright - for(int i=0; i<20; i++) { - int start1 = SpecialColour.rotateHue(colour, -9*i); - int start2 = SpecialColour.rotateHue(colour, -9*i-9); - int end1 = SpecialColour.rotateHue(colour, -180-9*i); - int end2 = SpecialColour.rotateHue(colour, -180-9*i-9); + for (int i = 0; i < 20; i++) { + int start1 = SpecialColour.rotateHue(colour, -9 * i); + int start2 = SpecialColour.rotateHue(colour, -9 * i - 9); + int end1 = SpecialColour.rotateHue(colour, -180 - 9 * i); + int end2 = SpecialColour.rotateHue(colour, -180 - 9 * i - 9); - Utils.drawGradientRect(-mapCenterX-2, -mapCenterY+(int)(mapSizeY*(i/20f)), -mapCenterX, - -mapCenterY+(int)(mapSizeY*((i+1)/20f)), start1, start2); //left - Utils.drawGradientRect(mapCenterX, -mapCenterY+(int)(mapSizeX*(i/20f)), mapCenterX+2, - -mapCenterY+(int)(mapSizeX*((i+1)/20f)), + Utils.drawGradientRect(-mapCenterX - 2, -mapCenterY + (int) (mapSizeY * (i / 20f)), -mapCenterX, + -mapCenterY + (int) (mapSizeY * ((i + 1) / 20f)), start1, start2); //left + Utils.drawGradientRect(mapCenterX, -mapCenterY + (int) (mapSizeX * (i / 20f)), mapCenterX + 2, + -mapCenterY + (int) (mapSizeX * ((i + 1) / 20f)), end1, end2); //right - Utils.drawGradientRectHorz(-mapCenterX+(int)(mapSizeX*(i/20f)), -mapCenterY-2, - -mapCenterX+(int)(mapSizeX*((i+1)/20f)), -mapCenterY, start1, start2); //top - Utils.drawGradientRectHorz(-mapCenterX+(int)(mapSizeX*(i/20f)), - mapCenterY, -mapCenterX+(int)(mapSizeX*((i+1)/20f)), mapCenterY+2, + Utils.drawGradientRectHorz(-mapCenterX + (int) (mapSizeX * (i / 20f)), -mapCenterY - 2, + -mapCenterX + (int) (mapSizeX * ((i + 1) / 20f)), -mapCenterY, start1, start2); //top + Utils.drawGradientRectHorz(-mapCenterX + (int) (mapSizeX * (i / 20f)), + mapCenterY, -mapCenterX + (int) (mapSizeX * ((i + 1) / 20f)), mapCenterY + 2, end1, end2); //bottom } } else { - Gui.drawRect(-mapCenterX-2, -mapCenterY, -mapCenterX, mapCenterY, + Gui.drawRect(-mapCenterX - 2, -mapCenterY, -mapCenterX, mapCenterY, SpecialColour.specialToChromaRGB(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderColour)); //left - Gui.drawRect(mapCenterX, -mapCenterY, mapCenterX+2, mapCenterY, + Gui.drawRect(mapCenterX, -mapCenterY, mapCenterX + 2, mapCenterY, SpecialColour.specialToChromaRGB(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderColour)); //right - Gui.drawRect(-mapCenterX-2, -mapCenterY-2, mapCenterX+2, -mapCenterY, + Gui.drawRect(-mapCenterX - 2, -mapCenterY - 2, mapCenterX + 2, -mapCenterY, SpecialColour.specialToChromaRGB(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderColour)); //top - Gui.drawRect(-mapCenterX-2, mapCenterY, mapCenterX+2, mapCenterY+2, + Gui.drawRect(-mapCenterX - 2, mapCenterY, mapCenterX + 2, mapCenterY + 2, SpecialColour.specialToChromaRGB(NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderColour)); //bottom } String sizeId = borderSizeOption == 0 ? "small" : borderSizeOption == 2 ? "large" : "medium"; - ResourceLocation rl = new ResourceLocation("notenoughupdates:dungeon_map/borders/"+sizeId+"/"+ - NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderStyle+".png"); - if(Minecraft.getMinecraft().getTextureManager().getTexture(rl) != TextureUtil.missingTexture) { + ResourceLocation rl = new ResourceLocation("notenoughupdates:dungeon_map/borders/" + sizeId + "/" + + NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderStyle + ".png"); + if (Minecraft.getMinecraft().getTextureManager().getTexture(rl) != TextureUtil.missingTexture) { Minecraft.getMinecraft().getTextureManager().bindTexture(rl); GlStateManager.color(1, 1, 1, 1); int size = borderSizeOption == 0 ? 165 : borderSizeOption == 1 ? 220 : borderSizeOption == 2 ? 300 : 440; - Utils.drawTexturedRect(-size/2, -size/2, size, size, GL11.GL_NEAREST); + Utils.drawTexturedRect(-size / 2, -size / 2, size, size, GL11.GL_NEAREST); } GlStateManager.translate(-centerX, -centerY, -100); - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); Minecraft.getMinecraft().entityRenderer.setupOverlayRendering(); @@ -824,26 +831,25 @@ public class DungeonMap { GlStateManager.disableLighting(); } - public void updateRoomConnections(RoomOffset roomOffset) { - if(roomMap.containsKey(roomOffset)) { + if (roomMap.containsKey(roomOffset)) { Room room = roomMap.get(roomOffset); int otherPixelFilled = 0; int otherPixelColour = 0; - for(int xOff=0; xOff 0 && y > 0 && x < colourMap.length && y < colourMap[x].length) { + if (x > 0 && y > 0 && x < colourMap.length && y < colourMap[x].length) { Color c = colourMap[x][y]; - if(!c.equals(room.colour)) { - if(otherPixelColour == c.getRGB()) { + if (!c.equals(room.colour)) { + if (otherPixelColour == c.getRGB()) { otherPixelFilled++; } else { otherPixelFilled--; - if(otherPixelFilled <= 0) { + if (otherPixelFilled <= 0) { otherPixelFilled = 1; otherPixelColour = c.getRGB(); } @@ -854,45 +860,45 @@ public class DungeonMap { } room.tickColour = 0; - if((float)otherPixelFilled/roomSize/connectorSize > 0.05) { + if ((float) otherPixelFilled / roomSize / connectorSize > 0.05) { room.tickColour = otherPixelColour; } - for(int k=0; k<4; k++) { + for (int k = 0; k < 4; k++) { Color colour = null; int totalFilled = 0; - for(int i=0; i 0 && y > 0 && x < colourMap.length && y < colourMap[x].length) { + if (x > 0 && y > 0 && x < colourMap.length && y < colourMap[x].length) { Color pixel = colourMap[x][y]; - if(pixel.getAlpha() > 40) { - if(colour == null) { + if (pixel.getAlpha() > 40) { + if (colour == null) { colour = pixel; totalFilled = 1; } else { - if(colour.equals(pixel)) { + if (colour.equals(pixel)) { totalFilled++; } else { totalFilled--; - if(totalFilled <= 0) { + if (totalFilled <= 0) { colour = pixel; totalFilled = 1; } @@ -902,32 +908,32 @@ public class DungeonMap { } } } - float proportionFilled = (float)totalFilled/roomSize/connectorSize; + float proportionFilled = (float) totalFilled / roomSize / connectorSize; RoomConnectionType type = RoomConnectionType.WALL; - if(proportionFilled > 0.8) { + if (proportionFilled > 0.8) { type = RoomConnectionType.ROOM_DIVIDER; - } else if(proportionFilled > 0.1) { + } else if (proportionFilled > 0.1) { type = RoomConnectionType.CORRIDOR; } - if(k == 0) { + if (k == 0) { room.up = new RoomConnection(type, colour); - } else if(k == 1) { + } else if (k == 1) { room.right = new RoomConnection(type, colour); - } else if(k == 2) { + } else if (k == 2) { room.down = new RoomConnection(type, colour); } else { room.left = new RoomConnection(type, colour); } } - int x = startRoomX + roomOffset.x*(roomSize+connectorSize) + roomSize + connectorSize/2; - int y = startRoomY + roomOffset.y*(roomSize+connectorSize) + roomSize + connectorSize/2; + int x = startRoomX + roomOffset.x * (roomSize + connectorSize) + roomSize + connectorSize / 2; + int y = startRoomY + roomOffset.y * (roomSize + connectorSize) + roomSize + connectorSize / 2; room.fillCorner = false; - if(x > 0 && y > 0 && x < colourMap.length && y < colourMap[x].length) { + if (x > 0 && y > 0 && x < colourMap.length && y < colourMap[x].length) { Color pixel = colourMap[x][y]; - if(pixel.equals(room.colour)) { + if (pixel.equals(room.colour)) { room.fillCorner = true; } } @@ -935,16 +941,16 @@ public class DungeonMap { } public void loadNeighbors(RoomOffset room) { - if(!roomMap.containsKey(room)) { + if (!roomMap.containsKey(room)) { roomMap.put(room, new Room()); } - for(RoomOffset neighbor : room.getNeighbors()) { - if(!roomMap.containsKey(neighbor)) { - int x = startRoomX + neighbor.x*(roomSize+connectorSize); - int y = startRoomY + neighbor.y*(roomSize+connectorSize); + for (RoomOffset neighbor : room.getNeighbors()) { + if (!roomMap.containsKey(neighbor)) { + int x = startRoomX + neighbor.x * (roomSize + connectorSize); + int y = startRoomY + neighbor.y * (roomSize + connectorSize); - if(x >= 0 && y >= 0 && x+roomSize < colourMap.length && y+roomSize < colourMap[x].length) { - if(colourMap[x][y].getAlpha() > 100) { + if (x >= 0 && y >= 0 && x + roomSize < colourMap.length && y + roomSize < colourMap[x].length) { + if (colourMap[x][y].getAlpha() > 100) { roomMap.put(neighbor, new Room()); loadNeighbors(neighbor); } @@ -954,13 +960,13 @@ public class DungeonMap { } public void updateRoomColours() { - for(Map.Entry entry : roomMap.entrySet()) { - int x = startRoomX + entry.getKey().x*(roomSize+connectorSize); - int y = startRoomY + entry.getKey().y*(roomSize+connectorSize); + for (Map.Entry entry : roomMap.entrySet()) { + int x = startRoomX + entry.getKey().x * (roomSize + connectorSize); + int y = startRoomY + entry.getKey().y * (roomSize + connectorSize); try { entry.getValue().colour = colourMap[x][y]; - } catch(Exception e) {} + } catch (Exception ignored) {} } } @@ -981,11 +987,11 @@ public class DungeonMap { } public float getRenderX() { - return roomOffsetX*getRenderRoomSize() + connOffsetX*getRenderConnSize(); + return roomOffsetX * getRenderRoomSize() + connOffsetX * getRenderConnSize(); } public float getRenderY() { - return roomOffsetY*getRenderRoomSize() + connOffsetY*getRenderConnSize(); + return roomOffsetY * getRenderRoomSize() + connOffsetY * getRenderConnSize(); } @Override @@ -1009,16 +1015,17 @@ public class DungeonMap { private boolean isFloorOne = false; private boolean failMap = false; private long lastClearCache = 0; + public void renderMap(int centerX, int centerY, Color[][] colourMap, Map mapDecorations, int roomSizeBlocks, Set actualPlayers, boolean usePlayerPositions, float partialTicks) { - if(!NotEnoughUpdates.INSTANCE.config.dungeonMap.dmEnable) return; - if(colourMap == null) return; - if(colourMap.length != 128) return; - if(colourMap[0].length != 128) return; + if (!NotEnoughUpdates.INSTANCE.config.dungeonMap.dmEnable) return; + if (colourMap == null) return; + if (colourMap.length != 128) return; + if (colourMap[0].length != 128) return; this.colourMap = colourMap; boolean searchForPlayers = false; - if(System.currentTimeMillis() - lastClearCache > 1000) { + if (System.currentTimeMillis() - lastClearCache > 1000) { roomMap.clear(); searchForPlayers = true; startRoomX = -1; @@ -1037,61 +1044,61 @@ public class DungeonMap { List scores = new ArrayList<>(scoreboard.getSortedScores(sidebarObjective)); - for(int i=scores.size()-1; i>=0; i--) { + for (int i = scores.size() - 1; i >= 0; i--) { Score score = scores.get(i); ScorePlayerTeam scoreplayerteam1 = scoreboard.getPlayersTeam(score.getPlayerName()); String line = ScorePlayerTeam.formatPlayerName(scoreplayerteam1, score.getPlayerName()); line = Utils.cleanColour(line); - if(line.contains("(F1)") || line.contains("(E)") || line.contains("(M1)")) { + if (line.contains("(F1)") || line.contains("(E)") || line.contains("(M1)")) { isFloorOne = true; break; } } } - if(failMap) { + if (failMap) { return; } int alphaPixels = 0; - for(int x=0; x<128; x++) { - for(int y=0; y<128; y++) { + for (int x = 0; x < 128; x++) { + for (int y = 0; y < 128; y++) { Color c = colourMap[x][y]; - if(c == null) { + if (c == null) { return; - } else if(c.getAlpha() < 50) { + } else if (c.getAlpha() < 50) { alphaPixels++; } } } - if(alphaPixels < 128*128/10) { + if (alphaPixels < 128 * 128 / 10) { failMap = true; return; } - if(startRoomX < 0 || startRoomY < 0 || roomSize <= 0) { - for(int x=0; x 80) { - if(startRoomX < 0 && startRoomY < 0 && c.getRed() == 0 && c.getGreen() == 124 && c.getBlue() == 0) { + if (c.getAlpha() > 80) { + if (startRoomX < 0 && startRoomY < 0 && c.getRed() == 0 && c.getGreen() == 124 && c.getBlue() == 0) { roomSize = 0; out: - for(int xd=0; xd<=20; xd++) { - for(int yd=0; yd<=20; yd++) { - if(x+xd >= colourMap.length || y+yd >= colourMap[x+xd].length) continue; - Color c2 = colourMap[x+xd][y+yd]; + for (int xd = 0; xd <= 20; xd++) { + for (int yd = 0; yd <= 20; yd++) { + if (x + xd >= colourMap.length || y + yd >= colourMap[x + xd].length) continue; + Color c2 = colourMap[x + xd][y + yd]; - if(c2.getGreen() != 124 || c2.getAlpha() <= 80) { - if(xd < 10 && yd < 10) { + if (c2.getGreen() != 124 || c2.getAlpha() <= 80) { + if (xd < 10 && yd < 10) { break out; } } else { - roomSize = Math.max(roomSize, Math.min(xd+1, yd+1)); + roomSize = Math.max(roomSize, Math.min(xd + 1, yd + 1)); } - if(xd == 20 && yd == 20) { - if(roomSize == 0) roomSize = 20; + if (xd == 20 && yd == 20) { + if (roomSize == 0) roomSize = 20; startRoomX = x; startRoomY = y; } @@ -1103,56 +1110,56 @@ public class DungeonMap { } } - if(startRoomX < 0 || startRoomY < 0) { + if (startRoomX < 0 || startRoomY < 0) { failMap = true; return; } - if(connectorSize <= 0) { - for(int i=0; i 0 && y > 0 && x < colourMap.length && y < colourMap[x].length) { - if(colourMap[x][y].getAlpha() > 80) { - if(j == 1) { + if (x > 0 && y > 0 && x < colourMap.length && y < colourMap[x].length) { + if (colourMap[x][y].getAlpha() > 80) { + if (j == 1) { break; } - connectorSize = Math.min(connectorSize, j-1); + connectorSize = Math.min(connectorSize, j - 1); } } } } } - if(connectorSize <= 0) { + if (connectorSize <= 0) { connectorSize = 4; } } actualPlayers.add(Minecraft.getMinecraft().thePlayer.getName()); - if(searchForPlayers) { - for(EntityPlayer player : Minecraft.getMinecraft().theWorld.playerEntities) { - if(player instanceof AbstractClientPlayer && actualPlayers.contains(player.getName())) { + if (searchForPlayers) { + for (EntityPlayer player : Minecraft.getMinecraft().theWorld.playerEntities) { + if (player instanceof AbstractClientPlayer && actualPlayers.contains(player.getName())) { AbstractClientPlayer aplayer = (AbstractClientPlayer) player; ResourceLocation skin = aplayer.getLocationSkin(); - if(skin != DefaultPlayerSkin.getDefaultSkin(aplayer.getUniqueID())) { + if (skin != DefaultPlayerSkin.getDefaultSkin(aplayer.getUniqueID())) { playerSkinMap.put(player.getName(), skin); playerIdMap.put(player.getName(), player.getEntityId()); } @@ -1161,49 +1168,49 @@ public class DungeonMap { } playerEntityMapPositions.clear(); - if(usePlayerPositions) { - for(String playerName : actualPlayers) { - if(playerIdMap.containsKey(playerName)) { + if (usePlayerPositions) { + for (String playerName : actualPlayers) { + if (playerIdMap.containsKey(playerName)) { Entity entity = Minecraft.getMinecraft().theWorld.getEntityByID(playerIdMap.get(playerName)); - if(entity instanceof EntityPlayer) { + if (entity instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) entity; - float roomX = (float)player.posX / (roomSizeBlocks+1); - float roomY = (float)player.posZ / (roomSizeBlocks+1); + float roomX = (float) player.posX / (roomSizeBlocks + 1); + float roomY = (float) player.posZ / (roomSizeBlocks + 1); float playerRoomOffsetX = (float) Math.floor(roomX); float playerConnOffsetX = (float) Math.floor(roomX); float playerRoomOffsetY = (float) Math.floor(roomY); float playerConnOffsetY = (float) Math.floor(roomY); - float roomXInBlocks = (float)player.posX % (roomSizeBlocks+1); - if(roomXInBlocks < 2) { //0,1 - playerConnOffsetX -= 2/5f-roomXInBlocks/5f; - } else if(roomXInBlocks > roomSizeBlocks-2) { //31,30,29 + float roomXInBlocks = (float) player.posX % (roomSizeBlocks + 1); + if (roomXInBlocks < 2) { //0,1 + playerConnOffsetX -= 2 / 5f - roomXInBlocks / 5f; + } else if (roomXInBlocks > roomSizeBlocks - 2) { //31,30,29 playerRoomOffsetX++; - playerConnOffsetX += (roomXInBlocks - (roomSizeBlocks-2))/5f; + playerConnOffsetX += (roomXInBlocks - (roomSizeBlocks - 2)) / 5f; } else { - playerRoomOffsetX += (roomXInBlocks-2) / (roomSizeBlocks-4); + playerRoomOffsetX += (roomXInBlocks - 2) / (roomSizeBlocks - 4); } - float roomYInBlocks = (float)player.posZ % (roomSizeBlocks+1); - if(roomYInBlocks < 2) { //0,1 - playerConnOffsetY -= 2/5f-roomYInBlocks/5f; - } else if(roomYInBlocks > roomSizeBlocks-2) { //31,30,29 + float roomYInBlocks = (float) player.posZ % (roomSizeBlocks + 1); + if (roomYInBlocks < 2) { //0,1 + playerConnOffsetY -= 2 / 5f - roomYInBlocks / 5f; + } else if (roomYInBlocks > roomSizeBlocks - 2) { //31,30,29 playerRoomOffsetY++; - playerConnOffsetY += (roomYInBlocks - (roomSizeBlocks-2))/5f; + playerConnOffsetY += (roomYInBlocks - (roomSizeBlocks - 2)) / 5f; } else { - playerRoomOffsetY += (roomYInBlocks-2) / (roomSizeBlocks-4); + playerRoomOffsetY += (roomYInBlocks - 2) / (roomSizeBlocks - 4); } - playerRoomOffsetX -= startRoomX/(roomSize+connectorSize); - playerRoomOffsetY -= startRoomY/(roomSize+connectorSize); - playerConnOffsetX -= startRoomX/(roomSize+connectorSize); - playerConnOffsetY -= startRoomY/(roomSize+connectorSize); + playerRoomOffsetX -= startRoomX / (roomSize + connectorSize); + playerRoomOffsetY -= startRoomY / (roomSize + connectorSize); + playerConnOffsetX -= startRoomX / (roomSize + connectorSize); + playerConnOffsetY -= startRoomY / (roomSize + connectorSize); MapPosition pos = new MapPosition(playerRoomOffsetX, playerConnOffsetX, playerRoomOffsetY, playerConnOffsetY); - pos.rotation = (player.prevRotationYawHead + (player.rotationYawHead-player.prevRotationYawHead)*partialTicks) % 360; - if(pos.rotation < 0) pos.rotation += 360; + pos.rotation = (player.prevRotationYawHead + (player.rotationYawHead - player.prevRotationYawHead) * partialTicks) % 360; + if (pos.rotation < 0) pos.rotation += 360; playerEntityMapPositions.put(player.getName(), pos); } } @@ -1212,26 +1219,26 @@ public class DungeonMap { loadNeighbors(new RoomOffset(0, 0)); updateRoomColours(); - for(RoomOffset offset : roomMap.keySet()) { + for (RoomOffset offset : roomMap.keySet()) { updateRoomConnections(offset); } - if(roomMap.isEmpty()) { + if (roomMap.isEmpty()) { failMap = true; return; } - if(mapDecorations != null && mapDecorations.size() > 0) { + if (mapDecorations != null && mapDecorations.size() > 0) { List positions = new ArrayList<>(); int decorations = 0; for (Vec4b vec4b : mapDecorations.values()) { byte id = vec4b.func_176110_a(); - if(id != 1 && id != 3) continue; + if (id != 1 && id != 3) continue; float x = (float) vec4b.func_176112_b() / 2.0F + 64.0F; float y = (float) vec4b.func_176113_c() / 2.0F + 64.0F; - if(x < 0 || y < 0 || x > 128 || y > 128) { + if (x < 0 || y < 0 || x > 128 || y > 128) { continue; } @@ -1269,9 +1276,9 @@ public class DungeonMap { MapPosition pos = new MapPosition(roomsOffsetX, connOffsetX, roomsOffsetY, connOffsetY); pos.rotation = angle % 360; - if(pos.rotation < 0) pos.rotation += 360; + if (pos.rotation < 0) pos.rotation += 360; - if(decorations++ <= 6) { + if (decorations++ <= 6) { positions.add(pos); } rawPlayerMarkerMapPositions.add(pos); @@ -1288,7 +1295,7 @@ public class DungeonMap { } } - if(different && positions.size() > 0) { + if (different && positions.size() > 0) { lastLastDecorationsMillis = lastDecorationsMillis; lastDecorationsMillis = System.currentTimeMillis(); @@ -1360,21 +1367,21 @@ public class DungeonMap { } List nonUsedIndexes = new ArrayList<>(); - for(int i=0; i= 0 && startRoomY >= 0) { + if (!roomMap.isEmpty() && startRoomX >= 0 && startRoomY >= 0) { render(centerX, centerY); } @@ -1397,27 +1404,27 @@ public class DungeonMap { @SubscribeEvent public void onRenderOverlay(RenderGameOverlayEvent.Post event) { - if(!NotEnoughUpdates.INSTANCE.hasSkyblockScoreboard()) return; - if(event.type == RenderGameOverlayEvent.ElementType.ALL) { - if(!NotEnoughUpdates.INSTANCE.config.dungeonMap.dmEnable) return; + if (!NotEnoughUpdates.INSTANCE.hasSkyblockScoreboard()) return; + if (event.type == RenderGameOverlayEvent.ElementType.ALL) { + if (!NotEnoughUpdates.INSTANCE.config.dungeonMap.dmEnable) return; - if(Minecraft.getMinecraft().gameSettings.showDebugInfo || + if (Minecraft.getMinecraft().gameSettings.showDebugInfo || (Minecraft.getMinecraft().gameSettings.keyBindPlayerList.isKeyDown() && (!Minecraft.getMinecraft().isIntegratedServerRunning() || Minecraft.getMinecraft().thePlayer.sendQueue.getPlayerInfoMap().size() > 1))) { return; } - + ItemStack stack = Minecraft.getMinecraft().thePlayer.inventory.mainInventory[8]; boolean holdingBow = stack != null && stack.getItem() == Items.arrow && colourMap != null; - if(holdingBow || (stack != null && stack.getItem() instanceof ItemMap)) { + if (holdingBow || (stack != null && stack.getItem() instanceof ItemMap)) { Map decorations = null; Color[][] colourMap = new Color[128][128]; - if(holdingBow) { - for(int x=0; x<128; x++) { - for(int y=0; y<128; y++) { - if(this.colourMap[x][y] != null) { + if (holdingBow) { + for (int x = 0; x < 128; x++) { + for (int y = 0; y < 128; y++) { + if (this.colourMap[x][y] != null) { colourMap[x][y] = this.colourMap[x][y]; } else { colourMap[x][y] = new Color(0, true); @@ -1428,7 +1435,7 @@ public class DungeonMap { ItemMap map = (ItemMap) stack.getItem(); MapData mapData = map.getMapData(stack, Minecraft.getMinecraft().theWorld); - if(mapData == null) return; + if (mapData == null) return; decorations = mapData.mapDecorations; @@ -1494,30 +1501,30 @@ public class DungeonMap { } }*/ int players = 0; - for(ScorePlayerTeam team : Minecraft.getMinecraft().thePlayer.getWorldScoreboard().getTeams()) { - if(team.getTeamName().startsWith("a") && team.getMembershipCollection().size() == 1) { + for (ScorePlayerTeam team : Minecraft.getMinecraft().thePlayer.getWorldScoreboard().getTeams()) { + if (team.getTeamName().startsWith("a") && team.getMembershipCollection().size() == 1) { String playerName = Iterables.get(team.getMembershipCollection(), 0); boolean foundPlayer = false; - for(EntityPlayer player : Minecraft.getMinecraft().theWorld.playerEntities) { - if(player.getName().equals(playerName) && (player == Minecraft.getMinecraft().thePlayer || !player.isPlayerSleeping())) { + for (EntityPlayer player : Minecraft.getMinecraft().theWorld.playerEntities) { + if (player.getName().equals(playerName) && (player == Minecraft.getMinecraft().thePlayer || !player.isPlayerSleeping())) { actualPlayers.add(playerName); foundPlayer = true; break; } } - if(!foundPlayer) actualPlayers.add(playerName); - if(++players >= 6) break; + if (!foundPlayer) actualPlayers.add(playerName); + if (++players >= 6) break; } } Position pos = NotEnoughUpdates.INSTANCE.config.dungeonMap.dmPosition; - int size = 80 + Math.round(40*NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderSize); + int size = 80 + Math.round(40 * NotEnoughUpdates.INSTANCE.config.dungeonMap.dmBorderSize); ScaledResolution scaledResolution = Utils.pushGuiScale(2); - renderMap(pos.getAbsX(scaledResolution, size/2)+size/2, pos.getAbsY(scaledResolution, size/2)+size/2, + renderMap(pos.getAbsX(scaledResolution, size / 2) + size / 2, pos.getAbsY(scaledResolution, size / 2) + size / 2, colourMap, decorations, roomSizeBlocks, actualPlayers, true, event.partialTicks); Utils.pushGuiScale(-1); - } else if(stack != null && Item.getIdFromItem(stack.getItem()) == 399){ + } else if (stack != null && Item.getIdFromItem(stack.getItem()) == 399) { //This should clear the map if you're in the dungeon boss room //so when you're holding a bow it doesnt show the map anymore this.colourMap = null; @@ -1528,20 +1535,20 @@ public class DungeonMap { public List> permutations(List values) { List> permutations = new ArrayList<>(); - if(values.size() == 1) { + if (values.size() == 1) { permutations.add(values); return permutations; } - for(String first : values) { + for (String first : values) { List newList = new ArrayList<>(); - for(String val : values) { - if(!val.equals(first)) { + for (String val : values) { + if (!val.equals(first)) { newList.add(val); } } - for(List list2 : permutations(newList)) { + for (List list2 : permutations(newList)) { List perm = new ArrayList<>(); perm.add(first); perm.addAll(list2); @@ -1560,15 +1567,15 @@ public class DungeonMap { /** * Creates a projection matrix that projects from our coordinate space [0->width; 0->height] to OpenGL coordinate * space [-1 -> 1; 1 -> -1] (Note: flipped y-axis). - * + *

* This is so that we can render to and from the framebuffer in a way that is familiar to us, instead of needing to * apply scales and translations manually. */ private Matrix4f createProjectionMatrix(int width, int height) { - Matrix4f projMatrix = new Matrix4f(); + Matrix4f projMatrix = new Matrix4f(); projMatrix.setIdentity(); - projMatrix.m00 = 2.0F / (float)width; - projMatrix.m11 = 2.0F / (float)(-height); + projMatrix.m00 = 2.0F / (float) width; + projMatrix.m11 = 2.0F / (float) (-height); projMatrix.m22 = -0.0020001999F; projMatrix.m33 = 1.0F; projMatrix.m03 = -1.0F; diff --git a/src/main/java/io/github/moulberry/notenoughupdates/dungeons/DungeonWin.java b/src/main/java/io/github/moulberry/notenoughupdates/dungeons/DungeonWin.java index 95ca32c9..d79e9840 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/dungeons/DungeonWin.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/dungeons/DungeonWin.java @@ -14,9 +14,7 @@ import net.minecraftforge.client.event.ClientChatReceivedEvent; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL14; -import java.awt.*; import java.util.*; -import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -33,7 +31,7 @@ public class DungeonWin { private int life = 0; private float xVel; private float yVel; - private int id; + private final int id; public Confetti(float x, float y, float xVel, float yVel) { this.x = x; @@ -43,9 +41,10 @@ public class DungeonWin { this.xVel = xVel; this.yVel = yVel; this.id = rand.nextInt(16); - this.life = 20+rand.nextInt(10); + this.life = 20 + rand.nextInt(10); } } + public static ResourceLocation CONFETTI = new ResourceLocation("notenoughupdates:dungeon_win/confetti.png"); public static ResourceLocation SPLUS = new ResourceLocation("notenoughupdates:dungeon_win/splus.png"); public static ResourceLocation S = new ResourceLocation("notenoughupdates:dungeon_win/s.png"); @@ -56,8 +55,8 @@ public class DungeonWin { public static ResourceLocation TEAM_SCORE = SPLUS; private static final int SCALE_FACTOR = 3; - private static final int WIDTH = 32*SCALE_FACTOR; - private static final int HEIGHT = 16*SCALE_FACTOR; + private static final int WIDTH = 32 * SCALE_FACTOR; + private static final int HEIGHT = 16 * SCALE_FACTOR; private static boolean hideChat = false; private static long lastDungeonFinish = 0; @@ -71,63 +70,68 @@ public class DungeonWin { public static long startTime = 0; static { - for(int i=0; i<10; i++) { - text.add("{PLACEHOLDER DUNGEON STAT #"+i+"}"); + for (int i = 0; i < 10; i++) { + text.add("{PLACEHOLDER DUNGEON STAT #" + i + "}"); } } public static void displayWin() { - if(NotEnoughUpdates.INSTANCE.config.dungeons.dungeonWinMillis < 100 || !NotEnoughUpdates.INSTANCE.config.dungeons.enableDungeonWin) return; + if (NotEnoughUpdates.INSTANCE.config.dungeons.dungeonWinMillis < 100 || !NotEnoughUpdates.INSTANCE.config.dungeons.enableDungeonWin) + return; startTime = System.currentTimeMillis(); confetti.clear(); } public static void tick() { - if(NotEnoughUpdates.INSTANCE.config.dungeons.dungeonWinMillis < 100 || !NotEnoughUpdates.INSTANCE.config.dungeons.enableDungeonWin) return; - if(System.currentTimeMillis() - startTime > 5000) return; - int deltaTime = (int)(System.currentTimeMillis() - startTime); + if (NotEnoughUpdates.INSTANCE.config.dungeons.dungeonWinMillis < 100 || !NotEnoughUpdates.INSTANCE.config.dungeons.enableDungeonWin) + return; + if (System.currentTimeMillis() - startTime > 5000) return; + int deltaTime = (int) (System.currentTimeMillis() - startTime); - if(deltaTime < 1000) { + if (deltaTime < 1000) { ScaledResolution sr = Utils.pushGuiScale(2); int cap = 0; - switch(TEAM_SCORE.getResourcePath()) { + switch (TEAM_SCORE.getResourcePath()) { case "dungeon_win/splus.png": - cap = 200; break; + cap = 200; + break; case "dungeon_win/s.png": - cap = 100; break; + cap = 100; + break; case "dungeon_win/a.png": - cap = 50; break; + cap = 50; + break; } - int maxConfetti = Math.min(cap, deltaTime/5); - while(confetti.size() < maxConfetti) { + int maxConfetti = Math.min(cap, deltaTime / 5); + while (confetti.size() < maxConfetti) { int y; - if(deltaTime < 500) { - y = sr.getScaledHeight()/2-(int)(Math.sin(deltaTime/1000f*Math.PI)*sr.getScaledHeight()/9); + if (deltaTime < 500) { + y = sr.getScaledHeight() / 2 - (int) (Math.sin(deltaTime / 1000f * Math.PI) * sr.getScaledHeight() / 9); } else { - y = sr.getScaledHeight()/6+(int)(Math.sin(deltaTime/1000f*Math.PI)*sr.getScaledHeight()*4/18); + y = sr.getScaledHeight() / 6 + (int) (Math.sin(deltaTime / 1000f * Math.PI) * sr.getScaledHeight() * 4 / 18); } - int xOffset = -WIDTH/2+rand.nextInt(WIDTH); - int x = sr.getScaledWidth()/2+xOffset; + int xOffset = -WIDTH / 2 + rand.nextInt(WIDTH); + int x = sr.getScaledWidth() / 2 + xOffset; - int xVel = xOffset/2; - int yVel = -25-rand.nextInt(10)+Math.abs(xVel)/2; + int xVel = xOffset / 2; + int yVel = -25 - rand.nextInt(10) + Math.abs(xVel) / 2; confetti.add(new Confetti(x, y, xVel, yVel)); } } else { Set toRemove = new HashSet<>(); - for(Confetti c : confetti) { - if(c.life <= 0) { + for (Confetti c : confetti) { + if (c.life <= 0) { toRemove.add(c); } } try { confetti.removeAll(toRemove); - } catch(ConcurrentModificationException ignored) {} + } catch (ConcurrentModificationException ignored) {} } Utils.pushGuiScale(-1); - for(Confetti c : confetti) { + for (Confetti c : confetti) { c.yVel += 1; c.xVel /= 1.1f; c.yVel /= 1.1f; @@ -139,11 +143,11 @@ public class DungeonWin { } } - public static void onChatMessage(ClientChatReceivedEvent e) { - if(e.type == 2) return; + if (e.type == 2) return; - if(NotEnoughUpdates.INSTANCE.config.dungeons.dungeonWinMillis < 100 || !NotEnoughUpdates.INSTANCE.config.dungeons.enableDungeonWin) return; + if (NotEnoughUpdates.INSTANCE.config.dungeons.dungeonWinMillis < 100 || !NotEnoughUpdates.INSTANCE.config.dungeons.enableDungeonWin) + return; long currentTime = System.currentTimeMillis(); String unformatted = Utils.cleanColour(e.message.getUnformattedText()); @@ -151,48 +155,52 @@ public class DungeonWin { //Added two more Resets, cant do Reset+Reset+Reset cause idk? //hypixel please dont randomly add more - if(e.message.getFormattedText().startsWith(EnumChatFormatting.RESET+""+EnumChatFormatting.RESET+""+EnumChatFormatting.RESET+" ")){ - if(currentTime - lastDungeonFinish > 30000) { + if (e.message.getFormattedText().startsWith(EnumChatFormatting.RESET + "" + EnumChatFormatting.RESET + "" + EnumChatFormatting.RESET + " ")) { + if (currentTime - lastDungeonFinish > 30000) { Matcher matcher = TEAM_SCORE_REGEX.matcher(unformatted); - if(matcher.find()) { + if (matcher.find()) { lastDungeonFinish = currentTime; String score = matcher.group(1); switch (score.toUpperCase()) { case "S+": - TEAM_SCORE = SPLUS; break; + TEAM_SCORE = SPLUS; + break; case "S": - TEAM_SCORE = S; break; + TEAM_SCORE = S; + break; case "A": - TEAM_SCORE = A; break; + TEAM_SCORE = A; + break; case "B": - TEAM_SCORE = B; break; + TEAM_SCORE = B; + break; case "C": - TEAM_SCORE = C; break; + TEAM_SCORE = C; + break; default: - TEAM_SCORE = D; break; + TEAM_SCORE = D; + break; } - SES.schedule(()-> { - NotEnoughUpdates.INSTANCE.sendChatMessage("/showextrastats"); - }, 100L, TimeUnit.MILLISECONDS); + SES.schedule(() -> NotEnoughUpdates.INSTANCE.sendChatMessage("/showextrastats"), 100L, TimeUnit.MILLISECONDS); } } } - if(currentTime - lastDungeonFinish > 100 && currentTime - lastDungeonFinish < 10000) { - if(hideChat) { - if(text.size() > 50) text.clear(); + if (currentTime - lastDungeonFinish > 100 && currentTime - lastDungeonFinish < 10000) { + if (hideChat) { + if (text.size() > 50) text.clear(); e.setCanceled(true); - if(unformatted.contains("\u25AC")) { + if (unformatted.contains("\u25AC")) { hideChat = false; displayWin(); } else { - if(unformatted.trim().length() > 0) { + if (unformatted.trim().length() > 0) { text.add(e.message.getFormattedText().substring(6).trim()); } } } else { - if(unformatted.contains("\u25AC")) { + if (unformatted.contains("\u25AC")) { hideChat = true; text.clear(); e.setCanceled(true); @@ -203,54 +211,55 @@ public class DungeonWin { } public static void render(float partialTicks) { - if(NotEnoughUpdates.INSTANCE.config.dungeons.dungeonWinMillis < 100 || !NotEnoughUpdates.INSTANCE.config.dungeons.enableDungeonWin) return; + if (NotEnoughUpdates.INSTANCE.config.dungeons.dungeonWinMillis < 100 || !NotEnoughUpdates.INSTANCE.config.dungeons.enableDungeonWin) + return; int maxTime = Math.min(30000, NotEnoughUpdates.INSTANCE.config.dungeons.dungeonWinMillis); - if(System.currentTimeMillis() - startTime > maxTime) return; - int deltaTime = (int)(System.currentTimeMillis() - startTime); + if (System.currentTimeMillis() - startTime > maxTime) return; + int deltaTime = (int) (System.currentTimeMillis() - startTime); - float alpha = Math.max(0, Math.min(1, 1-(deltaTime-maxTime+150)/150f)); + float alpha = Math.max(0, Math.min(1, 1 - (deltaTime - maxTime + 150) / 150f)); ScaledResolution sr = Utils.pushGuiScale(2); - if(deltaTime > 600) { + if (deltaTime > 600) { float bottom; - if(deltaTime < 1000) { - bottom = sr.getScaledHeight()/6f+(float)Math.sin(deltaTime/1000f*Math.PI)*sr.getScaledHeight()*4/18+HEIGHT/2; + if (deltaTime < 1000) { + bottom = sr.getScaledHeight() / 6f + (float) Math.sin(deltaTime / 1000f * Math.PI) * sr.getScaledHeight() * 4 / 18 + HEIGHT / 2; } else { - bottom = sr.getScaledHeight()/6f+HEIGHT/2; + bottom = sr.getScaledHeight() / 6f + HEIGHT / 2; } - for(int i=0; i bottom) { - int textAlpha = (int)(alpha * (deltaTime > 1000 ? 255 : Math.min(255, (textCenterY-bottom)/30f*255))); + float textCenterY = sr.getScaledHeight() / 6f + HEIGHT / 2 + 7 + i * 10; + if (textCenterY > bottom) { + int textAlpha = (int) (alpha * (deltaTime > 1000 ? 255 : Math.min(255, (textCenterY - bottom) / 30f * 255))); GlStateManager.enableBlend(); - if(textAlpha > 150) { - for(int xOff=-2; xOff<=2; xOff++) { - for(int yOff=-2; yOff<=2; yOff++) { - if(Math.abs(xOff) != Math.abs(yOff)) { + if (textAlpha > 150) { + for (int xOff = -2; xOff <= 2; xOff++) { + for (int yOff = -2; yOff <= 2; yOff++) { + if (Math.abs(xOff) != Math.abs(yOff)) { Utils.drawStringCentered(Utils.cleanColourNotModifiers(line), Minecraft.getMinecraft().fontRendererObj, - sr.getScaledWidth()/2+xOff/2f, textCenterY+yOff/2f, false, - ((textAlpha/Math.max(Math.abs(xOff), Math.abs(yOff))) << 24)); + sr.getScaledWidth() / 2 + xOff / 2f, textCenterY + yOff / 2f, false, + ((textAlpha / Math.max(Math.abs(xOff), Math.abs(yOff))) << 24)); } } } } Utils.drawStringCentered(line, Minecraft.getMinecraft().fontRendererObj, - sr.getScaledWidth()/2, textCenterY, false, (textAlpha << 24) | 0x00FFFFFF); + sr.getScaledWidth() / 2, textCenterY, false, (textAlpha << 24) | 0x00FFFFFF); } } } - for(Confetti c : confetti) { + for (Confetti c : confetti) { Minecraft.getMinecraft().getTextureManager().bindTexture(CONFETTI); GlStateManager.color(1, 1, 1, 1); - if(c.life >= 15) { - GlStateManager.color(1, 1, 1, Math.min(1, c.life/4f)); - Utils.drawTexturedRect(c.xLast+(c.x-c.xLast)*partialTicks-4, c.yLast+(c.y-c.yLast)*partialTicks-4, - 8, 8, (c.id%4)/4f, (c.id%4+1)/4f, (c.id/4)/4f, (c.id/4+1)/4f, GL11.GL_NEAREST); + if (c.life >= 15) { + GlStateManager.color(1, 1, 1, Math.min(1, c.life / 4f)); + Utils.drawTexturedRect(c.xLast + (c.x - c.xLast) * partialTicks - 4, c.yLast + (c.y - c.yLast) * partialTicks - 4, + 8, 8, (c.id % 4) / 4f, (c.id % 4 + 1) / 4f, (c.id / 4) / 4f, (c.id / 4 + 1) / 4f, GL11.GL_NEAREST); } } @@ -258,62 +267,62 @@ public class DungeonWin { GlStateManager.color(1, 1, 1, alpha); GlStateManager.pushMatrix(); - if(deltaTime < 1600) { - GlStateManager.translate(sr.getScaledWidth()/2, 0, 0); - if(deltaTime < 500) { - GlStateManager.translate(0, sr.getScaledHeight()/2f-Math.sin(deltaTime/1000f*Math.PI)*sr.getScaledHeight()/9, 0); - } else if(deltaTime < 1000) { - GlStateManager.translate(0, sr.getScaledHeight()/6f+Math.sin(deltaTime/1000f*Math.PI)*sr.getScaledHeight()*4/18, 0); + if (deltaTime < 1600) { + GlStateManager.translate(sr.getScaledWidth() / 2, 0, 0); + if (deltaTime < 500) { + GlStateManager.translate(0, sr.getScaledHeight() / 2f - Math.sin(deltaTime / 1000f * Math.PI) * sr.getScaledHeight() / 9, 0); + } else if (deltaTime < 1000) { + GlStateManager.translate(0, sr.getScaledHeight() / 6f + Math.sin(deltaTime / 1000f * Math.PI) * sr.getScaledHeight() * 4 / 18, 0); } else { - GlStateManager.translate(0, sr.getScaledHeight()/6f, 0); + GlStateManager.translate(0, sr.getScaledHeight() / 6f, 0); } - if(deltaTime < 200) { - float scale = deltaTime/200f; + if (deltaTime < 200) { + float scale = deltaTime / 200f; GlStateManager.scale(scale, scale, 1); - } else if(deltaTime < 1000) { - float scale = 1+(float)Math.sin((deltaTime-200)/800f*Math.PI)*0.8f; + } else if (deltaTime < 1000) { + float scale = 1 + (float) Math.sin((deltaTime - 200) / 800f * Math.PI) * 0.8f; GlStateManager.scale(scale, scale, 1); - } else if(deltaTime < 1100) { - float scale = 1+(float)Math.sin((deltaTime-1000)/100f*Math.PI)*0.15f; + } else if (deltaTime < 1100) { + float scale = 1 + (float) Math.sin((deltaTime - 1000) / 100f * Math.PI) * 0.15f; GlStateManager.scale(scale, scale, 1); } - if(deltaTime < 600) { - GlStateManager.rotate(180+deltaTime/600f*180, 0, 1, 0); - GlStateManager.rotate(180-deltaTime/600f*180, 1, 0, 0); - GlStateManager.rotate(-180-deltaTime/600f*165, 0, 0, 1); - } else if(deltaTime < 1000) { - GlStateManager.rotate(15-(deltaTime-600)/400f*11, 0, 0, 1); + if (deltaTime < 600) { + GlStateManager.rotate(180 + deltaTime / 600f * 180, 0, 1, 0); + GlStateManager.rotate(180 - deltaTime / 600f * 180, 1, 0, 0); + GlStateManager.rotate(-180 - deltaTime / 600f * 165, 0, 0, 1); + } else if (deltaTime < 1000) { + GlStateManager.rotate(15 - (deltaTime - 600) / 400f * 11, 0, 0, 1); } else { - float logFac = 1-(float)Math.log((deltaTime-1000)/600f*1.7f+1); - logFac = logFac*logFac; + float logFac = 1 - (float) Math.log((deltaTime - 1000) / 600f * 1.7f + 1); + logFac = logFac * logFac; - GlStateManager.rotate(4f*logFac, 0, 0, 1); - float x = (deltaTime-1000)/300f; - GlStateManager.rotate((float)(40*(1-Math.log(x*0.85f+1))*Math.sin(10*x*x)), 0, 1, 0); + GlStateManager.rotate(4f * logFac, 0, 0, 1); + float x = (deltaTime - 1000) / 300f; + GlStateManager.rotate((float) (40 * (1 - Math.log(x * 0.85f + 1)) * Math.sin(10 * x * x)), 0, 1, 0); } } else { - GlStateManager.translate(sr.getScaledWidth()/2, sr.getScaledHeight()/6f, 0); + GlStateManager.translate(sr.getScaledWidth() / 2, sr.getScaledHeight() / 6f, 0); } GlStateManager.disableCull(); - Utils.drawTexturedRect(-WIDTH/2, -HEIGHT/2, WIDTH, HEIGHT, GL11.GL_NEAREST); - GlStateManager.translate(0, 0, -SCALE_FACTOR*2); - Utils.drawTexturedRect(-WIDTH/2, -HEIGHT/2, WIDTH, HEIGHT, GL11.GL_NEAREST); - GlStateManager.translate(0, 0, SCALE_FACTOR*2); + Utils.drawTexturedRect(-WIDTH / 2, -HEIGHT / 2, WIDTH, HEIGHT, GL11.GL_NEAREST); + GlStateManager.translate(0, 0, -SCALE_FACTOR * 2); + Utils.drawTexturedRect(-WIDTH / 2, -HEIGHT / 2, WIDTH, HEIGHT, GL11.GL_NEAREST); + GlStateManager.translate(0, 0, SCALE_FACTOR * 2); - if(deltaTime < 1600) { + if (deltaTime < 1600) { float epsilon = 0.01f; - for(int xIndex=0; xIndex<32; xIndex++) { - for(int yIndex=0; yIndex<16; yIndex++) { - float uMin = xIndex/32f; - float uMax = (xIndex+1)/32f; - float vMin = yIndex/16f; - float vMax = (yIndex+1)/16f; + for (int xIndex = 0; xIndex < 32; xIndex++) { + for (int yIndex = 0; yIndex < 16; yIndex++) { + float uMin = xIndex / 32f; + float uMax = (xIndex + 1) / 32f; + float vMin = yIndex / 16f; + float vMax = (yIndex + 1) / 16f; - int x = -WIDTH/2+xIndex*SCALE_FACTOR; - int y = -HEIGHT/2+yIndex*SCALE_FACTOR; + int x = -WIDTH / 2 + xIndex * SCALE_FACTOR; + int y = -HEIGHT / 2 + yIndex * SCALE_FACTOR; GlStateManager.enableTexture2D(); GlStateManager.enableBlend(); @@ -327,61 +336,61 @@ public class DungeonWin { //Left worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); worldrenderer - .pos(x+epsilon, y+SCALE_FACTOR, 0.0D+epsilon) + .pos(x + epsilon, y + SCALE_FACTOR, 0.0D + epsilon) .tex(uMin, vMax).endVertex(); worldrenderer - .pos(x+epsilon, y, 0.0D+epsilon) + .pos(x + epsilon, y, 0.0D + epsilon) .tex(uMax, vMax).endVertex(); worldrenderer - .pos(x+epsilon, y, -SCALE_FACTOR*2-epsilon) + .pos(x + epsilon, y, -SCALE_FACTOR * 2 - epsilon) .tex(uMax, vMin).endVertex(); worldrenderer - .pos(x+epsilon, y+SCALE_FACTOR, -SCALE_FACTOR*2-epsilon) + .pos(x + epsilon, y + SCALE_FACTOR, -SCALE_FACTOR * 2 - epsilon) .tex(uMin, vMin).endVertex(); tessellator.draw(); //Right worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); worldrenderer - .pos(x+SCALE_FACTOR-epsilon, y+SCALE_FACTOR, 0.0D+epsilon) + .pos(x + SCALE_FACTOR - epsilon, y + SCALE_FACTOR, 0.0D + epsilon) .tex(uMin, vMax).endVertex(); worldrenderer - .pos(x+SCALE_FACTOR-epsilon, y, 0.0D+epsilon) + .pos(x + SCALE_FACTOR - epsilon, y, 0.0D + epsilon) .tex(uMax, vMax).endVertex(); worldrenderer - .pos(x+SCALE_FACTOR-epsilon, y, -SCALE_FACTOR*2-epsilon) + .pos(x + SCALE_FACTOR - epsilon, y, -SCALE_FACTOR * 2 - epsilon) .tex(uMax, vMin).endVertex(); worldrenderer - .pos(x+SCALE_FACTOR-epsilon, y+SCALE_FACTOR, -SCALE_FACTOR*2-epsilon) + .pos(x + SCALE_FACTOR - epsilon, y + SCALE_FACTOR, -SCALE_FACTOR * 2 - epsilon) .tex(uMin, vMin).endVertex(); tessellator.draw(); //Top worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); worldrenderer - .pos(x+SCALE_FACTOR, y+epsilon, 0.0D+epsilon) + .pos(x + SCALE_FACTOR, y + epsilon, 0.0D + epsilon) .tex(uMin, vMax).endVertex(); worldrenderer - .pos(x, y+epsilon, 0.0D+epsilon) + .pos(x, y + epsilon, 0.0D + epsilon) .tex(uMax, vMax).endVertex(); worldrenderer - .pos(x, y+epsilon, -SCALE_FACTOR*2-epsilon) + .pos(x, y + epsilon, -SCALE_FACTOR * 2 - epsilon) .tex(uMax, vMin).endVertex(); worldrenderer - .pos(x+SCALE_FACTOR, y+epsilon, -SCALE_FACTOR*2-epsilon) + .pos(x + SCALE_FACTOR, y + epsilon, -SCALE_FACTOR * 2 - epsilon) .tex(uMin, vMin).endVertex(); tessellator.draw(); //Top worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); worldrenderer - .pos(x+SCALE_FACTOR, y+SCALE_FACTOR-epsilon, 0.0D+epsilon) + .pos(x + SCALE_FACTOR, y + SCALE_FACTOR - epsilon, 0.0D + epsilon) .tex(uMin, vMax).endVertex(); worldrenderer - .pos(x, y+SCALE_FACTOR-epsilon, 0.0D+epsilon) + .pos(x, y + SCALE_FACTOR - epsilon, 0.0D + epsilon) .tex(uMax, vMax).endVertex(); worldrenderer - .pos(x, y+SCALE_FACTOR-epsilon, -SCALE_FACTOR*2-epsilon) + .pos(x, y + SCALE_FACTOR - epsilon, -SCALE_FACTOR * 2 - epsilon) .tex(uMax, vMin).endVertex(); worldrenderer - .pos(x+SCALE_FACTOR, y+SCALE_FACTOR-epsilon, -SCALE_FACTOR*2-epsilon) + .pos(x + SCALE_FACTOR, y + SCALE_FACTOR - epsilon, -SCALE_FACTOR * 2 - epsilon) .tex(uMin, vMin).endVertex(); tessellator.draw(); @@ -395,13 +404,13 @@ public class DungeonWin { GlStateManager.popMatrix(); - for(Confetti c : confetti) { + for (Confetti c : confetti) { Minecraft.getMinecraft().getTextureManager().bindTexture(CONFETTI); GlStateManager.color(1, 1, 1, 1); - if(c.life > 0 && c.life < 15) { - GlStateManager.color(1, 1, 1, Math.min(1, c.life/4f)); - Utils.drawTexturedRect(c.xLast+(c.x-c.xLast)*partialTicks-4, c.yLast+(c.y-c.yLast)*partialTicks-4, - 8, 8, (c.id%4)/4f, (c.id%4+1)/4f, (c.id/4)/4f, (c.id/4+1)/4f, GL11.GL_NEAREST); + if (c.life > 0 && c.life < 15) { + GlStateManager.color(1, 1, 1, Math.min(1, c.life / 4f)); + Utils.drawTexturedRect(c.xLast + (c.x - c.xLast) * partialTicks - 4, c.yLast + (c.y - c.yLast) * partialTicks - 4, + 8, 8, (c.id % 4) / 4f, (c.id % 4 + 1) / 4f, (c.id / 4) / 4f, (c.id / 4 + 1) / 4f, GL11.GL_NEAREST); } } diff --git a/src/main/java/io/github/moulberry/notenoughupdates/dungeons/GuiDungeonMapEditor.java b/src/main/java/io/github/moulberry/notenoughupdates/dungeons/GuiDungeonMapEditor.java index 1a420c67..475e89e9 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/dungeons/GuiDungeonMapEditor.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/dungeons/GuiDungeonMapEditor.java @@ -1,13 +1,12 @@ package io.github.moulberry.notenoughupdates.dungeons; -import io.github.moulberry.notenoughupdates.core.config.gui.GuiPositionEditor; -import io.github.moulberry.notenoughupdates.core.util.render.RenderUtils; -import io.github.moulberry.notenoughupdates.core.util.render.TextRenderUtils; -import io.github.moulberry.notenoughupdates.options.NEUConfig; import io.github.moulberry.notenoughupdates.NotEnoughUpdates; import io.github.moulberry.notenoughupdates.core.GuiElementColour; import io.github.moulberry.notenoughupdates.core.config.annotations.ConfigEditorSlider; import io.github.moulberry.notenoughupdates.core.config.annotations.ConfigOption; +import io.github.moulberry.notenoughupdates.core.config.gui.GuiPositionEditor; +import io.github.moulberry.notenoughupdates.core.util.render.RenderUtils; +import io.github.moulberry.notenoughupdates.core.util.render.TextRenderUtils; import io.github.moulberry.notenoughupdates.itemeditor.GuiElementTextField; import io.github.moulberry.notenoughupdates.options.seperateSections.DungeonMapConfig; import io.github.moulberry.notenoughupdates.util.SpecialColour; @@ -30,8 +29,9 @@ import org.lwjgl.opengl.GL11; import java.awt.*; import java.io.IOException; import java.lang.reflect.Field; -import java.util.*; import java.util.List; +import java.util.*; + import static io.github.moulberry.notenoughupdates.util.GuiTextures.*; public class GuiDungeonMapEditor extends GuiScreen { @@ -45,20 +45,20 @@ public class GuiDungeonMapEditor extends GuiScreen { private int guiLeft; private int guiTop; - private List