From fb340fa755f3839d06f15a65d6d9e95ecb97507a Mon Sep 17 00:00:00 2001 From: Lyft <127234178+Lyfts@users.noreply.github.com> Date: Wed, 16 Oct 2024 18:48:56 +0200 Subject: [PATCH] Reduce memory allocations (#24) * update bs+dep * reduce allocations by a ton * stop sending rain packet every tick * small cleanup * these will never be null at this point * chill with the enum[] allocations --- dependencies.gradle | 4 +- gradle.properties | 4 +- settings.gradle | 2 +- .../lunatrius/ingameinfo/Alignment.java | 34 ++- .../lunatrius/ingameinfo/InGameInfoCore.java | 202 ++++++------------ .../ingameinfo/client/gui/GuiTagList.java | 6 +- .../lunatrius/ingameinfo/client/gui/Info.java | 15 ++ .../ingameinfo/client/gui/InfoIcon.java | 14 +- .../ingameinfo/client/gui/InfoItem.java | 35 ++- .../ingameinfo/client/gui/InfoText.java | 125 +++++++++-- .../ingameinfo/command/InGameInfoCommand.java | 2 +- .../handler/ConfigurationHandler.java | 1 - .../ingameinfo/handler/KeyInputHandler.java | 25 +-- .../ingameinfo/handler/WorldHandler.java | 11 +- .../ingameinfo/proxy/ClientProxy.java | 12 +- .../github/lunatrius/ingameinfo/tag/Tag.java | 25 +-- .../lunatrius/ingameinfo/tag/TagMisc.java | 55 +++-- .../ingameinfo/tag/TagMouseOver.java | 3 +- .../ingameinfo/tag/TagNearbyPlayer.java | 9 +- .../ingameinfo/tag/TagPlayerEquipment.java | 27 ++- .../ingameinfo/tag/TagPlayerPotion.java | 14 +- .../ingameinfo/tag/registry/TagRegistry.java | 16 +- .../lunatrius/ingameinfo/value/Operation.java | 4 +- .../lunatrius/ingameinfo/value/Value.java | 49 +++-- .../ingameinfo/value/ValueComplex.java | 44 ++-- .../ingameinfo/value/ValueSimple.java | 2 +- .../value/registry/ValueRegistry.java | 2 +- 27 files changed, 410 insertions(+), 332 deletions(-) diff --git a/dependencies.gradle b/dependencies.gradle index 9547da4..c16b59c 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -3,10 +3,10 @@ dependencies { api('com.github.GTNewHorizons:LunatriusCore:1.2.0-GTNH:dev') - compileOnly('com.github.GTNewHorizons:BloodMagic:1.6.2:dev') + compileOnly('com.github.GTNewHorizons:BloodMagic:1.6.6:dev') compileOnly('thaumcraft:Thaumcraft:1.7.10-4.2.3.5:dev') compileOnly('curse.maven:cofh-lib-220333:2388748') compileOnly('curse.maven:simply-jetpacks-79325:2267185') compileOnly('curse.maven:tfcraft-302973:2627990') - compileOnly('com.github.GTNewHorizons:GT5-Unofficial:5.09.49.56:dev') + compileOnly('com.github.GTNewHorizons:GT5-Unofficial:5.09.50.42:dev') } diff --git a/gradle.properties b/gradle.properties index a221b59..ac5408b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -41,11 +41,11 @@ developmentEnvironmentUserName = Developer # Enables using modern Java syntax (up to version 17) via Jabel, while still targeting JVM 8. # See https://github.com/bsideup/jabel for details on how this works. -enableModernJavaSyntax = false +enableModernJavaSyntax = true # Enables injecting missing generics into the decompiled source code for a better coding experience. # Turns most publicly visible List, Map, etc. into proper List, Map types. -enableGenericInjection = false +enableGenericInjection = true # Generate a class with a String field for the mod version named as defined below. # If generateGradleTokenClass is empty or not missing, no such class will be generated. diff --git a/settings.gradle b/settings.gradle index 242692e..3d3ba12 100644 --- a/settings.gradle +++ b/settings.gradle @@ -17,7 +17,7 @@ pluginManagement { } plugins { - id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.26' + id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.27' } diff --git a/src/main/java/com/github/lunatrius/ingameinfo/Alignment.java b/src/main/java/com/github/lunatrius/ingameinfo/Alignment.java index 2c9e240..c15f346 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/Alignment.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/Alignment.java @@ -66,33 +66,23 @@ public static Alignment parse(String str) { } public int getX(int screenwidth, int textwidth) { - switch (this.alignment & MASK_X) { - case LEFT: - return this.x; + return switch (this.alignment & MASK_X) { + case LEFT -> this.x; + case CENTER -> this.x + (screenwidth - textwidth) / 2; + case RIGHT -> this.x + screenwidth - textwidth; + default -> 0; + }; - case CENTER: - return this.x + (screenwidth - textwidth) / 2; - - case RIGHT: - return this.x + screenwidth - textwidth; - } - - return 0; } public int getY(int screenheight, int textheight) { - switch (this.alignment & MASK_Y) { - case TOP: - return this.y; - - case MIDDLE: - return this.y + (screenheight - textheight) / 2; - - case BOTTOM: - return this.y + screenheight - textheight; - } + return switch (this.alignment & MASK_Y) { + case TOP -> this.y; + case MIDDLE -> this.y + (screenheight - textheight) / 2; + case BOTTOM -> this.y + screenheight - textheight; + default -> 0; + }; - return 0; } public String getDefaultXY() { diff --git a/src/main/java/com/github/lunatrius/ingameinfo/InGameInfoCore.java b/src/main/java/com/github/lunatrius/ingameinfo/InGameInfoCore.java index 0337b8b..f8eb07c 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/InGameInfoCore.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/InGameInfoCore.java @@ -7,25 +7,20 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; -import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import java.util.Set; import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityClientPlayerMP; -import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.resources.IResource; import net.minecraft.profiler.Profiler; import net.minecraft.util.ResourceLocation; -import net.minecraft.world.World; import org.lwjgl.opengl.GL11; -import com.github.lunatrius.ingameinfo.client.gui.Info; import com.github.lunatrius.ingameinfo.client.gui.InfoText; import com.github.lunatrius.ingameinfo.handler.ClientConfigurationHandler; import com.github.lunatrius.ingameinfo.parser.IParser; @@ -44,14 +39,12 @@ public class InGameInfoCore { - private static final Pattern PATTERN = Pattern.compile("\\{ICON\\|( *)\\}", Pattern.CASE_INSENSITIVE); - private static final Matcher MATCHER = PATTERN.matcher(""); public static final InGameInfoCore INSTANCE = new InGameInfoCore(); private IParser parser; private final Minecraft minecraft = Minecraft.getMinecraft(); - private final Profiler profiler = this.minecraft.mcProfiler; + private final Profiler profiler = minecraft.mcProfiler; private File configDirectory = null; private File configFile = null; /** @@ -59,25 +52,22 @@ public class InGameInfoCore { */ private String baseConfigFileName; private final Map>> format = new HashMap<>(); - private final List info = new ArrayList<>(); - private final List infoItemQueue = new ArrayList<>(); - private ScaledResolution scaledResolution = new ScaledResolution( - this.minecraft, - this.minecraft.displayWidth, - this.minecraft.displayHeight); - - private InGameInfoCore() { - Tag.setInfo(this.infoItemQueue); - Value.setInfo(this.infoItemQueue); - } - - public boolean setConfigDirectory(File directory) { - this.configDirectory = directory; - return true; + public ScaledResolution scaledResolution = new ScaledResolution( + minecraft, + minecraft.displayWidth, + minecraft.displayHeight); + private final Set infoTexts = new HashSet<>(); + public int scaledWidth; + public int scaledHeight; + + private InGameInfoCore() {} + + public void setConfigDirectory(File directory) { + configDirectory = directory; } public File getConfigDirectory() { - return this.configDirectory; + return configDirectory; } public void setConfigFileWithLocale() { @@ -91,7 +81,7 @@ public void setConfigFileWithLocale(String filename) { String baseName = filename.split("\\.")[0]; String extension = filename.split("\\.").length > 1 ? filename.split("\\.")[1] : ""; String localeAwareFileName = baseName + "_" + userLang + "." + extension; - if (new File(this.configDirectory, localeAwareFileName).isFile()) { + if (new File(configDirectory, localeAwareFileName).isFile()) { setConfigFile(localeAwareFileName, filename); } else { setConfigFile(filename); @@ -102,121 +92,51 @@ public boolean setConfigFile(String filename) { return setConfigFile(filename, filename); } - public boolean setConfigFile(String filename, String baseConfigFileName) { - File file = new File(this.configDirectory, filename); + public boolean setConfigFile(String filename, String baseName) { + File file = new File(configDirectory, filename); if (file.exists()) { + configFile = file; + baseConfigFileName = baseName; if (filename.endsWith(Names.Files.EXT_XML)) { - this.configFile = file; - this.parser = new XmlParser(); - this.baseConfigFileName = baseConfigFileName; - return true; + parser = new XmlParser(); } else if (filename.endsWith(Names.Files.EXT_JSON)) { - this.configFile = file; - this.parser = new JsonParser(); - this.baseConfigFileName = baseConfigFileName; - return true; + parser = new JsonParser(); } else if (filename.endsWith(Names.Files.EXT_TXT)) { - this.configFile = file; - this.parser = new TextParser(); - this.baseConfigFileName = baseConfigFileName; - return true; + parser = new TextParser(); } + return true; } - this.configFile = null; - this.parser = new XmlParser(); - this.baseConfigFileName = null; + configFile = null; + parser = new XmlParser(); + baseConfigFileName = null; return false; } public void onTickClient() { float scale = ClientConfigurationHandler.Scale / 10; - int scaledWidth = (int) (scaledResolution.getScaledWidth() / scale); - int scaledHeight = (int) (scaledResolution.getScaledHeight() / scale); - - World world = this.minecraft.theWorld; - if (world == null) { - return; - } - Tag.setWorld(world); + scaledWidth = (int) (scaledResolution.getScaledWidth() / scale); + scaledHeight = (int) (scaledResolution.getScaledHeight() / scale); + Tag.update(); - EntityClientPlayerMP player = this.minecraft.thePlayer; - if (player == null) { - return; + if (infoTexts.isEmpty()) { + refreshInfoTexts(); } - Tag.setPlayer(player); - - this.info.clear(); - int x, y; - - this.profiler.startSection("alignment"); - this.profiler.startSection("none"); - for (Alignment alignment : Alignment.values()) { - this.profiler.endStartSection(alignment.toString().toLowerCase()); - List> lines = this.format.get(alignment); - - if (lines == null) { - continue; - } - - FontRenderer fontRenderer = this.minecraft.fontRenderer; - List queue = new ArrayList<>(); - - for (List line : lines) { - StringBuilder str = new StringBuilder(); - - this.infoItemQueue.clear(); - this.profiler.startSection("taggathering"); - for (Value value : line) { - str.append(getValue(value)); - } - this.profiler.endSection(); - - if (str.length() > 0) { - String processed = str.toString().replaceAll("\\{ICON\\|( *)\\}", "$1"); - - x = alignment.getX(scaledWidth, fontRenderer.getStringWidth(processed)); - InfoText text = new InfoText(fontRenderer, processed, x, 0); - - if (this.infoItemQueue.size() > 0) { - MATCHER.reset(str.toString()); - - for (int i = 0; i < this.infoItemQueue.size() && MATCHER.find(); i++) { - Info item = this.infoItemQueue.get(i); - item.x = fontRenderer.getStringWidth(str.substring(0, MATCHER.start())); - text.children.add(item); - - str = new StringBuilder( - str.toString().replaceFirst(Pattern.quote(MATCHER.group(0)), MATCHER.group(1))); - MATCHER.reset(str.toString()); - } - } - queue.add(text); - } - } - - y = alignment.getY(scaledHeight, queue.size() * (fontRenderer.FONT_HEIGHT + 1)); - for (Info item : queue) { - item.y = y; - this.info.add(item); - y += fontRenderer.FONT_HEIGHT + 1; - } - this.info.addAll(queue); + for (InfoText infoText : infoTexts) { + infoText.update(); } - this.profiler.endSection(); - this.profiler.endSection(); Tag.releaseResources(); ValueComplex.ValueFile.tick(); } public void onTickRender(ScaledResolution resolution) { - this.scaledResolution = resolution; + scaledResolution = resolution; GL11.glPushMatrix(); float scale = ClientConfigurationHandler.Scale / 10; GL11.glScalef(scale, scale, scale); - for (Info info : this.info) { + for (InfoText info : infoTexts) { info.draw(); } GL11.glPopMatrix(); @@ -227,11 +147,10 @@ public boolean loadConfig(String filename) { } public boolean reloadConfig() { - this.info.clear(); - this.infoItemQueue.clear(); - this.format.clear(); + infoTexts.clear(); + format.clear(); - if (this.parser == null) { + if (parser == null) { return false; } @@ -240,11 +159,11 @@ public boolean reloadConfig() { return false; } - if (this.parser.load(inputStream) && this.parser.parse(this.format)) { + if (parser.load(inputStream) && parser.parse(format)) { return true; } - this.format.clear(); + format.clear(); return false; } @@ -252,13 +171,13 @@ private InputStream getInputStream() { InputStream inputStream = null; try { - if (this.configFile != null && this.configFile.exists()) { + if (configFile != null && configFile.exists()) { Reference.logger.debug("Loading file config..."); - inputStream = new FileInputStream(this.configFile); + inputStream = new FileInputStream(configFile); } else { Reference.logger.debug("Loading default config..."); ResourceLocation resourceLocation = new ResourceLocation("ingameinfo", Names.Files.FILE_XML); - IResource resource = this.minecraft.getResourceManager().getResource(resourceLocation); + IResource resource = minecraft.getResourceManager().getResource(resourceLocation); inputStream = resource.getInputStream(); } } catch (Exception e) { @@ -268,9 +187,23 @@ private InputStream getInputStream() { return inputStream; } + public void refreshInfoTexts() { + for (Alignment alignment : Alignment.values()) { + List> lines = format.get(alignment); + + if (lines == null) { + continue; + } + + for (int i = 0; i < lines.size(); i++) { + infoTexts.add(new InfoText(i, alignment, lines.get(i))); + } + } + } + public boolean saveConfig(String filename) { IPrinter printer = null; - File file = new File(this.configDirectory, filename); + File file = new File(configDirectory, filename); if (filename.endsWith(Names.Files.EXT_XML)) { printer = new XmlPrinter(); } else if (filename.endsWith(Names.Files.EXT_JSON)) { @@ -279,7 +212,7 @@ public boolean saveConfig(String filename) { printer = new TextPrinter(); } - return printer != null && printer.print(file, this.format); + return printer != null && printer.print(file, format); } public void moveConfig(File directory, String fileName) { @@ -303,17 +236,4 @@ public void moveConfig(File directory, String fileName) { throw new RuntimeException(e); } } - - private String getValue(Value value) { - try { - if (value.isValidSize()) { - return value.getReplacedValue(); - } - } catch (Exception e) { - Reference.logger.debug("Failed to get value!", e); - return "null"; - } - - return ""; - } } diff --git a/src/main/java/com/github/lunatrius/ingameinfo/client/gui/GuiTagList.java b/src/main/java/com/github/lunatrius/ingameinfo/client/gui/GuiTagList.java index eb3a2b4..2e2d728 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/client/gui/GuiTagList.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/client/gui/GuiTagList.java @@ -21,13 +21,11 @@ public class GuiTagList extends GuiListExtended { public static final int OFFSET_X = 150; public static final int SCROLLBAR_WIDTH = 6; - private final Minecraft minecraft; private final Map> map; private IGuiListEntry[] entries; public GuiTagList(GuiTags guiTags, Minecraft minecraft) { super(minecraft, guiTags.width, guiTags.height, 18, guiTags.height - 30, 24); - this.minecraft = minecraft; this.map = new TreeMap<>(); @@ -39,13 +37,13 @@ public GuiTagList(GuiTags guiTags, Minecraft minecraft) { CategoryEntry categoryEntry = stringCategoryEntryMap.get(category); if (categoryEntry == null) { - categoryEntry = new CategoryEntry(this.minecraft.fontRenderer, category); + categoryEntry = new CategoryEntry(minecraft.fontRenderer, category); stringCategoryEntryMap.put(category, categoryEntry); this.map.put(categoryEntry, new TreeSet<>()); } Set tagEntries = this.map.get(categoryEntry); if (tagEntries != null) { - tagEntries.add(new TagEntry(this.minecraft.fontRenderer, name, description)); + tagEntries.add(new TagEntry(minecraft.fontRenderer, name, description)); } } diff --git a/src/main/java/com/github/lunatrius/ingameinfo/client/gui/Info.java b/src/main/java/com/github/lunatrius/ingameinfo/client/gui/Info.java index 488043d..9cc80a7 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/client/gui/Info.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/client/gui/Info.java @@ -3,13 +3,20 @@ import java.util.ArrayList; import java.util.List; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; + +import org.jetbrains.annotations.NotNull; + public abstract class Info { + protected static final FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer; public final List children = new ArrayList<>(); public int x; public int y; public int offsetX; public int offsetY; + private String identifier = ""; protected Info(int x, int y) { this.x = x; @@ -47,6 +54,14 @@ public int getHeight() { return 0; } + public void setIdentifier(@NotNull String identifier) { + this.identifier = identifier; + } + + public String getIdentifier() { + return this.identifier; + } + @Override public String toString() { return "Info"; diff --git a/src/main/java/com/github/lunatrius/ingameinfo/client/gui/InfoIcon.java b/src/main/java/com/github/lunatrius/ingameinfo/client/gui/InfoIcon.java index ef04ef4..9d34cf1 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/client/gui/InfoIcon.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/client/gui/InfoIcon.java @@ -2,7 +2,6 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; @@ -12,13 +11,11 @@ public class InfoIcon extends Info { - private static final TextureManager textureManager = Minecraft.getMinecraft().getTextureManager(); private final ResourceLocation resourceLocation; private final Vector2f xy0 = new Vector2f(); private final Vector2f xy1 = new Vector2f(); private final Vector2f uv0 = new Vector2f(); private final Vector2f uv1 = new Vector2f(); - private final double zLevel = 300; private int displayWidth; private int displayHeight; @@ -51,16 +48,17 @@ public void setTextureData(int iconX, int iconY, int iconWidth, int iconHeight, @Override public void drawInfo() { try { - textureManager.bindTexture(this.resourceLocation); + Minecraft.getMinecraft().getTextureManager().bindTexture(resourceLocation); GL11.glTranslatef(getX(), getY(), 0); Tessellator tess = Tessellator.instance; tess.startDrawingQuads(); - tess.addVertexWithUV(this.xy0.x, this.xy1.y, this.zLevel, this.uv0.x, this.uv1.y); - tess.addVertexWithUV(this.xy1.x, this.xy1.y, this.zLevel, this.uv1.x, this.uv1.y); - tess.addVertexWithUV(this.xy1.x, this.xy0.y, this.zLevel, this.uv1.x, this.uv0.y); - tess.addVertexWithUV(this.xy0.x, this.xy0.y, this.zLevel, this.uv0.x, this.uv0.y); + double zLevel = 300; + tess.addVertexWithUV(xy0.x, xy1.y, zLevel, uv0.x, uv1.y); + tess.addVertexWithUV(xy1.x, xy1.y, zLevel, uv1.x, uv1.y); + tess.addVertexWithUV(xy1.x, xy0.y, zLevel, uv1.x, uv0.y); + tess.addVertexWithUV(xy0.x, xy0.y, zLevel, uv0.x, uv0.y); tess.draw(); GL11.glTranslatef(-getX(), -getY(), 0); diff --git a/src/main/java/com/github/lunatrius/ingameinfo/client/gui/InfoItem.java b/src/main/java/com/github/lunatrius/ingameinfo/client/gui/InfoItem.java index f69a5bf..ca94bcd 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/client/gui/InfoItem.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/client/gui/InfoItem.java @@ -1,7 +1,6 @@ package com.github.lunatrius.ingameinfo.client.gui; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.client.renderer.texture.TextureManager; @@ -12,24 +11,25 @@ public class InfoItem extends Info { - private static final TextureManager textureManager = Minecraft.getMinecraft().getTextureManager(); private static final RenderItem renderItem = new RenderItem(); private final ItemStack itemStack; - private final FontRenderer fontRenderer; private final boolean large; private final int size; - public InfoItem(FontRenderer fontRenderer, ItemStack itemStack) { - this(fontRenderer, itemStack, false); + static { + renderItem.zLevel = 300; + } + + public InfoItem(ItemStack itemStack) { + this(itemStack, false); } - public InfoItem(FontRenderer fontRenderer, ItemStack itemStack, boolean large) { - this(fontRenderer, itemStack, large, 0, 0); + public InfoItem(ItemStack itemStack, boolean large) { + this(itemStack, large, 0, 0); } - public InfoItem(FontRenderer fontRenderer, ItemStack itemStack, boolean large, int x, int y) { + public InfoItem(ItemStack itemStack, boolean large, int x, int y) { super(x, y); - this.fontRenderer = fontRenderer; this.itemStack = itemStack; this.large = large; this.size = large ? 16 : 8; @@ -40,19 +40,20 @@ public InfoItem(FontRenderer fontRenderer, ItemStack itemStack, boolean large, i @Override public void drawInfo() { - if (this.itemStack != null && this.itemStack.getItem() != null) { + if (itemStack != null && itemStack.getItem() != null) { GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); GL11.glEnable(GL12.GL_RESCALE_NORMAL); RenderHelper.enableGUIStandardItemLighting(); GL11.glTranslatef(getX(), getY(), 0); - if (!this.large) { + if (!large) { GL11.glScalef(0.5f, 0.5f, 0.5f); } - renderItem.renderItemAndEffectIntoGUI(this.fontRenderer, textureManager, this.itemStack, 0, 0); + TextureManager textureManager = Minecraft.getMinecraft().getTextureManager(); + renderItem.renderItemAndEffectIntoGUI(fontRenderer, textureManager, itemStack, 0, 0); - if (!this.large) { + if (!large) { GL11.glScalef(2.0f, 2.0f, 2.0f); } GL11.glTranslatef(-getX(), -getY(), 0); @@ -65,12 +66,12 @@ public void drawInfo() { @Override public int getWidth() { - return this.itemStack != null && this.itemStack.getItem() != null ? this.size : 0; + return itemStack != null && itemStack.getItem() != null ? size : 0; } @Override public int getHeight() { - return this.itemStack != null && this.itemStack.getItem() != null ? this.size : 0; + return itemStack != null && itemStack.getItem() != null ? size : 0; } @Override @@ -84,8 +85,4 @@ public String toString() { this.offsetY, this.children); } - - static { - renderItem.zLevel = 300; - } } diff --git a/src/main/java/com/github/lunatrius/ingameinfo/client/gui/InfoText.java b/src/main/java/com/github/lunatrius/ingameinfo/client/gui/InfoText.java index 3c47a1a..10eab6c 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/client/gui/InfoText.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/client/gui/InfoText.java @@ -1,37 +1,138 @@ package com.github.lunatrius.ingameinfo.client.gui; -import net.minecraft.client.gui.FontRenderer; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.annotation.Nullable; + +import org.jetbrains.annotations.NotNull; import com.github.lunatrius.core.client.gui.FontRendererHelper; +import com.github.lunatrius.ingameinfo.Alignment; +import com.github.lunatrius.ingameinfo.InGameInfoCore; +import com.github.lunatrius.ingameinfo.reference.Reference; +import com.github.lunatrius.ingameinfo.value.Value; public class InfoText extends Info { - private final FontRenderer fontRenderer; - private final String text; + private static final Pattern ICON_PATTERN = Pattern.compile("\\{ICON\\|( *)\\}", Pattern.CASE_INSENSITIVE); + private static final Matcher ICON_MATCHER = ICON_PATTERN.matcher(""); + private final Map attachedValues = new HashMap<>(); + private String text; + private final List values; + private final Alignment alignment; + private final int index; + private boolean needsUpdate = true; - public InfoText(FontRenderer fontRenderer, String text) { - this(fontRenderer, text, 0, 0); + public InfoText(int index, Alignment alignment, List values) { + super(0, 0); + this.values = values; + this.alignment = alignment; + this.index = index; + for (Value value : values) { + value.setParent(this); + } } - public InfoText(FontRenderer fontRenderer, String text, int x, int y) { - super(x, y); - this.fontRenderer = fontRenderer; - this.text = text; + public void update() { + StringBuilder builder = new StringBuilder(); + for (Value value : this.values) { + builder.append(getValue(value)); + } + text = builder.toString(); + updatePosition(); } @Override public void drawInfo() { - FontRendererHelper.drawLeftAlignedString(this.fontRenderer, this.text, getX(), getY(), 0x00FFFFFF); + if (needsUpdate) { + updateChildren(); + needsUpdate = false; + } + + FontRendererHelper.drawLeftAlignedString(fontRenderer, text, getX(), getY(), 0x00FFFFFF); + + for (Info child : attachedValues.values()) { + child.offsetX = x; + child.offsetY = y; + child.draw(); + } + } + + private void updateChildren() { + if (attachedValues.isEmpty()) { + return; + } + + ICON_MATCHER.reset(text); + for (Info child : attachedValues.values()) { + if (!ICON_MATCHER.find()) break; + int newX = fontRenderer.getStringWidth(text.substring(0, ICON_MATCHER.start())); + if (newX == 0) { + offsetX = child.getWidth(); + } + + child.x = newX; + text = text.replaceFirst(Pattern.quote(ICON_MATCHER.group(0)), ICON_MATCHER.group(1)); + ICON_MATCHER.reset(text); + } + updatePosition(); + } + + private void updatePosition() { + int scaledWidth = InGameInfoCore.INSTANCE.scaledWidth; + int scaledHeight = InGameInfoCore.INSTANCE.scaledHeight; + x = alignment.getX(scaledWidth, getWidth()); + y = alignment.getY(scaledHeight, getHeight()) + getHeight(); + } + + public @Nullable Info getAttachedValue(String tag) { + return attachedValues.get(tag); + } + + public void removeAttachedValue(String tag) { + attachedValues.remove(tag); + } + + public void attachValue(@NotNull String tag, @NotNull Info value) { + Info old = attachedValues.get(tag); + if (old != null) { + value.y = old.y; + value.x = old.x; + } else { + needsUpdate = true; + } + + if (value.x == 0) { + offsetX = value.getWidth(); + } + attachedValues.put(tag, value); } @Override public int getWidth() { - return this.fontRenderer.getStringWidth(this.text); + return fontRenderer.getStringWidth(text); } @Override public int getHeight() { - return this.fontRenderer.FONT_HEIGHT; + return index * (fontRenderer.FONT_HEIGHT + 1); + } + + private String getValue(Value value) { + try { + if (value.isValidSize()) { + return value.getReplacedValue(); + } + } catch (Exception e) { + Reference.logger.debug("Failed to get value!", e); + return "null"; + } + + return ""; } @Override diff --git a/src/main/java/com/github/lunatrius/ingameinfo/command/InGameInfoCommand.java b/src/main/java/com/github/lunatrius/ingameinfo/command/InGameInfoCommand.java index 7186cf5..5b5bc20 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/command/InGameInfoCommand.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/command/InGameInfoCommand.java @@ -40,7 +40,7 @@ public boolean canCommandSenderUseCommand(ICommandSender par1ICommandSender) { } @Override - public List addTabCompletionOptions(ICommandSender commandSender, String[] args) { + public List addTabCompletionOptions(ICommandSender commandSender, String[] args) { if (args.length == 1) { return getListOfStringsMatchingLastWord( args, diff --git a/src/main/java/com/github/lunatrius/ingameinfo/handler/ConfigurationHandler.java b/src/main/java/com/github/lunatrius/ingameinfo/handler/ConfigurationHandler.java index 2336689..25c9361 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/handler/ConfigurationHandler.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/handler/ConfigurationHandler.java @@ -23,7 +23,6 @@ public class ConfigurationHandler { public static final String CONFIG_NAME_DEFAULT = Names.Files.FILE_XML; public static final boolean SHOW_HUD_DEFAULT = true; - // TODO: 1.8 - flip the default to true public static final boolean REPLACE_DEBUG_DEFAULT = false; public static final boolean SHOW_IN_CHAT_DEFAULT = true; public static final boolean SHOW_ON_PLAYER_LIST_DEFAULT = true; diff --git a/src/main/java/com/github/lunatrius/ingameinfo/handler/KeyInputHandler.java b/src/main/java/com/github/lunatrius/ingameinfo/handler/KeyInputHandler.java index 5d24b06..bf985a2 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/handler/KeyInputHandler.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/handler/KeyInputHandler.java @@ -1,13 +1,9 @@ package com.github.lunatrius.ingameinfo.handler; +import static com.github.lunatrius.ingameinfo.proxy.ClientProxy.KEY_BINDING_TOGGLE; import static cpw.mods.fml.common.gameevent.InputEvent.KeyInputEvent; import net.minecraft.client.Minecraft; -import net.minecraft.client.settings.KeyBinding; - -import org.lwjgl.input.Keyboard; - -import com.github.lunatrius.ingameinfo.reference.Names; import cpw.mods.fml.common.eventhandler.SubscribeEvent; @@ -15,25 +11,14 @@ public class KeyInputHandler { public static final KeyInputHandler INSTANCE = new KeyInputHandler(); - private static final KeyBinding KEY_BINDING_TOGGLE = new KeyBinding( - Names.Keys.TOGGLE, - Keyboard.KEY_NONE, - Names.Keys.CATEGORY); - - public static final KeyBinding[] KEY_BINDINGS = new KeyBinding[] { KEY_BINDING_TOGGLE }; - - private final Minecraft minecraft = Minecraft.getMinecraft(); - private KeyInputHandler() {} @SubscribeEvent public void onKeyInput(KeyInputEvent event) { - for (KeyBinding keyBinding : KEY_BINDINGS) { - if (keyBinding.isPressed()) { - if (this.minecraft.currentScreen == null) { - ConfigurationHandler.showHUD = !ConfigurationHandler.showHUD; - ConfigurationHandler.saveHUDsettingToFile(); - } + if (KEY_BINDING_TOGGLE.isPressed()) { + if (Minecraft.getMinecraft().currentScreen == null) { + ConfigurationHandler.showHUD = !ConfigurationHandler.showHUD; + ConfigurationHandler.saveHUDsettingToFile(); } } } diff --git a/src/main/java/com/github/lunatrius/ingameinfo/handler/WorldHandler.java b/src/main/java/com/github/lunatrius/ingameinfo/handler/WorldHandler.java index 6cee3a6..8c8f944 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/handler/WorldHandler.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/handler/WorldHandler.java @@ -1,5 +1,7 @@ package com.github.lunatrius.ingameinfo.handler; +import net.minecraft.world.World; + import com.github.lunatrius.ingameinfo.network.PacketHandler; import com.github.lunatrius.ingameinfo.network.message.MessageNextRain; import com.github.lunatrius.ingameinfo.reference.Reference; @@ -12,11 +14,16 @@ public class WorldHandler { @SubscribeEvent public void onWorldTick(TickEvent.WorldTickEvent event) { + World world = event.world; + if (world.playerEntities.isEmpty() || world.getTotalWorldTime() % 20 != 0) { + return; + } + if (event.side == Side.SERVER && event.phase == TickEvent.Phase.END) { try { PacketHandler.INSTANCE.sendToDimension( - new MessageNextRain(event.world.getWorldInfo().getRainTime()), - event.world.provider.dimensionId); + new MessageNextRain(world.getWorldInfo().getRainTime()), + world.provider.dimensionId); } catch (Exception ex) { Reference.logger.error("Failed to get rain!", ex); } diff --git a/src/main/java/com/github/lunatrius/ingameinfo/proxy/ClientProxy.java b/src/main/java/com/github/lunatrius/ingameinfo/proxy/ClientProxy.java index 98eea79..9eb6398 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/proxy/ClientProxy.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/proxy/ClientProxy.java @@ -6,6 +6,8 @@ import net.minecraftforge.client.ClientCommandHandler; import net.minecraftforge.common.MinecraftForge; +import org.lwjgl.input.Keyboard; + import com.github.lunatrius.ingameinfo.InGameInfoCore; import com.github.lunatrius.ingameinfo.command.InGameInfoCommand; import com.github.lunatrius.ingameinfo.handler.ClientConfigurationHandler; @@ -28,6 +30,11 @@ public class ClientProxy extends CommonProxy { + public static final KeyBinding KEY_BINDING_TOGGLE = new KeyBinding( + Names.Keys.TOGGLE, + Keyboard.KEY_NONE, + Names.Keys.CATEGORY); + private final InGameInfoCore core = InGameInfoCore.INSTANCE; @Override @@ -47,10 +54,7 @@ public void preInit(FMLPreInitializationEvent event) { ClientConfigurationHandler.propFileInterval.setConfigEntryClass(GuiConfigEntries.NumberSliderEntry.class); ClientConfigurationHandler.propscale.setConfigEntryClass(GuiConfigEntries.NumberSliderEntry.class); - - for (KeyBinding keyBinding : KeyInputHandler.KEY_BINDINGS) { - ClientRegistry.registerKeyBinding(keyBinding); - } + ClientRegistry.registerKeyBinding(KEY_BINDING_TOGGLE); } @Override diff --git a/src/main/java/com/github/lunatrius/ingameinfo/tag/Tag.java b/src/main/java/com/github/lunatrius/ingameinfo/tag/Tag.java index 3cb7e40..92fc577 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/tag/Tag.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/tag/Tag.java @@ -1,16 +1,17 @@ package com.github.lunatrius.ingameinfo.tag; -import java.util.List; - import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.client.resources.I18n; import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; +import org.jetbrains.annotations.NotNull; + import com.github.lunatrius.core.util.vector.Vector3f; import com.github.lunatrius.core.util.vector.Vector3i; import com.github.lunatrius.ingameinfo.client.gui.Info; +import com.github.lunatrius.ingameinfo.client.gui.InfoText; import com.github.lunatrius.ingameinfo.reference.Reference; public abstract class Tag { @@ -21,7 +22,6 @@ public abstract class Tag { protected static MinecraftServer server; protected static World world; protected static EntityClientPlayerMP player; - protected static List info; protected static boolean hasSeed = false; protected static long seed = 0; protected static boolean hasNextRainTime = false; @@ -76,6 +76,10 @@ public String getLocalizedDescription() { public abstract String getValue(); + public @NotNull String getValue(@NotNull InfoText caller) { + return ""; + } + public static void setServer(MinecraftServer server) { Tag.server = server; @@ -106,12 +110,9 @@ public static void unsetNextRain() { Tag.nextRainTime = 0; } - public static void setWorld(World world) { - Tag.world = world; - } - - public static void setPlayer(EntityClientPlayerMP player) { - Tag.player = player; + public static void update() { + world = minecraft.theWorld; + player = minecraft.thePlayer; if (player != null) { playerPosition @@ -123,13 +124,7 @@ public static void setPlayer(EntityClientPlayerMP player) { } } - public static void setInfo(List info) { - Tag.info = info; - } - public static void releaseResources() { - setWorld(null); - setPlayer(null); TagNearbyPlayer.releaseResources(); TagPlayerPotion.releaseResources(); } diff --git a/src/main/java/com/github/lunatrius/ingameinfo/tag/TagMisc.java b/src/main/java/com/github/lunatrius/ingameinfo/tag/TagMisc.java index 2975669..77cd3f5 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/tag/TagMisc.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/tag/TagMisc.java @@ -6,7 +6,11 @@ import net.minecraft.client.resources.ResourcePackRepository; import net.minecraft.util.EnumChatFormatting; +import org.jetbrains.annotations.NotNull; + +import com.github.lunatrius.ingameinfo.client.gui.Info; import com.github.lunatrius.ingameinfo.client.gui.InfoIcon; +import com.github.lunatrius.ingameinfo.client.gui.InfoText; import com.github.lunatrius.ingameinfo.tag.registry.TagRegistry; public abstract class TagMisc extends Tag { @@ -63,7 +67,7 @@ public static class ResourcePack extends TagMisc { @Override public String getValue() { List repositoryEntries = resourcePackRepository.getRepositoryEntries(); - if (repositoryEntries.size() > 0) { + if (!repositoryEntries.isEmpty()) { return repositoryEntries.get(0).getResourcePackName(); } return resourcePackRepository.rprDefaultResourcePack.getPackName(); @@ -170,34 +174,47 @@ public String getValue() { public static class PingIcon extends TagMisc { + private boolean needsUpdate(InfoText caller, int ping) { + Info value = caller.getAttachedValue(getName()); + if (value == null) return true; + return Integer.parseInt(value.getIdentifier()) != ping; + } + @Override - public String getValue() { + public @NotNull String getValue(@NotNull InfoText caller) { List list = player.sendQueue.playerInfoList; for (GuiPlayerInfo playerInfo : list) { if (player.getGameProfile().getName() .equals(EnumChatFormatting.getTextWithoutFormattingCodes(playerInfo.name))) { - int pingIndex = 4; - if (playerInfo.responseTime < 0) { - pingIndex = 5; - } else if (playerInfo.responseTime < 150) { - pingIndex = 0; - } else if (playerInfo.responseTime < 300) { - pingIndex = 1; - } else if (playerInfo.responseTime < 600) { - pingIndex = 2; - } else if (playerInfo.responseTime < 1000) { - pingIndex = 3; + int pingIndex = getPingIndex(playerInfo); + if (needsUpdate(caller, playerInfo.responseTime)) { + InfoIcon icon = new InfoIcon("textures/gui/icons.png"); + icon.setIdentifier(String.valueOf(playerInfo.responseTime)); + icon.setDisplayDimensions(0, 0, 10, 8); + icon.setTextureData(0, 176 + pingIndex * 8, 10, 8, 256, 256); + caller.attachValue(getName(), icon); + return getIconTag(icon); } - - InfoIcon icon = new InfoIcon("textures/gui/icons.png"); - icon.setDisplayDimensions(0, 0, 10, 8); - icon.setTextureData(0, 176 + pingIndex * 8, 10, 8, 256, 256); - info.add(icon); - return getIconTag(icon); + return ""; } } return "-1"; } + + private static int getPingIndex(GuiPlayerInfo playerInfo) { + int responseTime = playerInfo.responseTime; + if (responseTime < 0) return 5; + if (responseTime < 150) return 0; + if (responseTime < 300) return 1; + if (responseTime < 600) return 2; + if (responseTime < 1000) return 3; + return 4; + } + + @Override + public String getValue() { + return ""; + } } public static void register() { diff --git a/src/main/java/com/github/lunatrius/ingameinfo/tag/TagMouseOver.java b/src/main/java/com/github/lunatrius/ingameinfo/tag/TagMouseOver.java index eb980bd..b32b787 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/tag/TagMouseOver.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/tag/TagMouseOver.java @@ -34,7 +34,8 @@ public String getValue() { world, objectMouseOver.blockX, objectMouseOver.blockY, - objectMouseOver.blockZ); + objectMouseOver.blockZ, + player); if (pickBlock != null) { return pickBlock.getDisplayName(); } diff --git a/src/main/java/com/github/lunatrius/ingameinfo/tag/TagNearbyPlayer.java b/src/main/java/com/github/lunatrius/ingameinfo/tag/TagNearbyPlayer.java index 54081e6..d2e969c 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/tag/TagNearbyPlayer.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/tag/TagNearbyPlayer.java @@ -67,12 +67,9 @@ public String getCategory() { protected static void updateNearbyPlayers() { if (nearbyPlayers == null) { List playerList = new ArrayList<>(); - for (Object o : world.playerEntities) { - if (o instanceof EntityPlayer) { - EntityPlayer entityPlayer = (EntityPlayer) o; - if (entityPlayer != Tag.player && !entityPlayer.isSneaking()) { - playerList.add(entityPlayer); - } + for (EntityPlayer player : world.playerEntities) { + if (player != Tag.player && !player.isSneaking()) { + playerList.add(player); } } playerList.sort(PLAYER_DISTANCE_COMPARATOR); diff --git a/src/main/java/com/github/lunatrius/ingameinfo/tag/TagPlayerEquipment.java b/src/main/java/com/github/lunatrius/ingameinfo/tag/TagPlayerEquipment.java index 25d6b84..c65df5a 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/tag/TagPlayerEquipment.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/tag/TagPlayerEquipment.java @@ -4,8 +4,12 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import org.jetbrains.annotations.NotNull; + import com.github.lunatrius.core.entity.EntityHelper; +import com.github.lunatrius.ingameinfo.client.gui.Info; import com.github.lunatrius.ingameinfo.client.gui.InfoItem; +import com.github.lunatrius.ingameinfo.client.gui.InfoText; import com.github.lunatrius.ingameinfo.tag.registry.TagRegistry; import cpw.mods.fml.common.registry.GameData; @@ -131,12 +135,27 @@ public Icon(int slot, boolean large) { this.large = large; } + @Override + public @NotNull String getValue(@NotNull InfoText caller) { + ItemStack itemStack = getItemStack(slot); + if (itemStack == null) { + caller.removeAttachedValue(getName()); + return ""; + } + + Info value = caller.getAttachedValue(getName()); + if (value == null || !value.getIdentifier().equals(itemStack.getDisplayName())) { + InfoItem item = new InfoItem(itemStack, this.large); + item.setIdentifier(itemStack.getDisplayName()); + caller.attachValue(getName(), item); + return getIconTag(item); + } + return ""; + } + @Override public String getValue() { - ItemStack itemStack = getItemStack(this.slot); - InfoItem item = new InfoItem(minecraft.fontRenderer, itemStack, this.large); - info.add(item); - return getIconTag(item); + return ""; } } diff --git a/src/main/java/com/github/lunatrius/ingameinfo/tag/TagPlayerPotion.java b/src/main/java/com/github/lunatrius/ingameinfo/tag/TagPlayerPotion.java index 3f1f926..c43916e 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/tag/TagPlayerPotion.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/tag/TagPlayerPotion.java @@ -6,7 +6,10 @@ import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; +import org.jetbrains.annotations.NotNull; + import com.github.lunatrius.ingameinfo.client.gui.InfoIcon; +import com.github.lunatrius.ingameinfo.client.gui.InfoText; import com.github.lunatrius.ingameinfo.tag.registry.TagRegistry; public abstract class TagPlayerPotion extends Tag { @@ -54,7 +57,7 @@ protected void updatePotionEffects() { if (potionEffects == null) { Collection potionEffectCollection = player.getActivePotionEffects(); potionEffects = new PotionEffect[potionEffectCollection.size()]; - if (potionEffectCollection.size() > 0) { + if (!potionEffectCollection.isEmpty()) { int index = 0; for (PotionEffect potionEffect : potionEffectCollection) { @@ -151,7 +154,7 @@ public Icon(int index, boolean large) { } @Override - public String getValue() { + public @NotNull String getValue(@NotNull InfoText parent) { updatePotionEffects(); if (potionEffects.length > this.index) { Potion potion = Potion.potionTypes[potionEffects[this.index].getPotionID()]; @@ -164,12 +167,17 @@ public String getValue() { icon.setDisplayDimensions(1, -1, 18 / 2, 18 / 2); } icon.setTextureData((i % 8) * 18, 198 + (i / 8) * 18, 18, 18, 256, 256); - info.add(icon); + parent.attachValue(getName(), icon); return getIconTag(icon); } } return ""; } + + @Override + public String getValue() { + return ""; + } } public static void register() { diff --git a/src/main/java/com/github/lunatrius/ingameinfo/tag/registry/TagRegistry.java b/src/main/java/com/github/lunatrius/ingameinfo/tag/registry/TagRegistry.java index 87331a7..f2e0dda 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/tag/registry/TagRegistry.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/tag/registry/TagRegistry.java @@ -27,7 +27,7 @@ public class TagRegistry { private void register(String name, Tag tag) { if (this.stringTagMap.containsKey(name)) { - Reference.logger.error("Duplicate tag key '" + name + "'!"); + Reference.logger.error("Duplicate tag key '{}'!", name); return; } @@ -48,16 +48,16 @@ public void register(Tag tag) { } public String getValue(String name) { - Tag tag = this.stringTagMap.get(name.toLowerCase()); + Tag tag = stringTagMap.get(name.toLowerCase()); return tag != null ? tag.getValue() : null; } + public Tag getTag(String name) { + return stringTagMap.get(name.toLowerCase()); + } + public List getRegisteredTags() { - List tags = new ArrayList<>(); - for (Map.Entry entry : this.stringTagMap.entrySet()) { - tags.add(entry.getValue()); - } - return tags; + return new ArrayList<>(stringTagMap.values()); } public void init() { @@ -73,6 +73,6 @@ public void init() { TagTime.register(); TagWorld.register(); - Reference.logger.info("Registered " + this.stringTagMap.size() + " tags."); + Reference.logger.info("Registered {} tags.", stringTagMap.size()); } } diff --git a/src/main/java/com/github/lunatrius/ingameinfo/value/Operation.java b/src/main/java/com/github/lunatrius/ingameinfo/value/Operation.java index 350beba..5f3b35e 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/value/Operation.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/value/Operation.java @@ -128,10 +128,12 @@ public String getValue(Value value) { } }; + public static final Operation[] VALUES = values(); + public abstract String getValue(Value value); public static Operation fromString(String str) { - for (Operation op : values()) { + for (Operation op : VALUES) { if (String.valueOf(op).equalsIgnoreCase(str)) { return op; } diff --git a/src/main/java/com/github/lunatrius/ingameinfo/value/Value.java b/src/main/java/com/github/lunatrius/ingameinfo/value/Value.java index cfc8d97..f8e2171 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/value/Value.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/value/Value.java @@ -3,20 +3,18 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import com.github.lunatrius.ingameinfo.client.gui.Info; +import org.apache.commons.lang3.StringUtils; + +import com.github.lunatrius.ingameinfo.client.gui.InfoText; import com.github.lunatrius.ingameinfo.reference.Reference; +import com.github.lunatrius.ingameinfo.tag.Tag; import com.github.lunatrius.ingameinfo.tag.registry.TagRegistry; import com.github.lunatrius.ingameinfo.value.registry.ValueRegistry; public abstract class Value { - private static final Pattern PATTERN = Pattern.compile("\\{([a-z0-9]+)\\}", Pattern.CASE_INSENSITIVE); - private static final Matcher MATCHER = PATTERN.matcher(""); - protected static List info; - + protected InfoText parent; private String name = null; private String[] aliases = new String[0]; protected String value = ""; @@ -54,13 +52,24 @@ public String getRawValue(boolean isText) { } protected String replaceVariables(String str) { - MATCHER.reset(str); + int tagAmount = StringUtils.countMatches(str, "{"); + if (tagAmount == 0 || tagAmount == 1 && str.contains("ICON")) { + return str; + } + StringBuilder builder = new StringBuilder(str); + + for (int i = 0; i < tagAmount; i++) { + int start = builder.indexOf("{"); + if (start == -1) break; - while (MATCHER.find()) { - str = str.replace(MATCHER.group(0), getVariableValue(MATCHER.group(1))); + int end = builder.indexOf("}", start); + if (end == -1) break; + String var = builder.substring(start + 1, end); + String replacement = getVariableValue(var); + builder.replace(start, end + 1, replacement); } - return str; + return builder.toString(); } public abstract boolean isSimple(); @@ -103,16 +112,20 @@ protected boolean getBooleanValue(int index) { protected String getVariableValue(String var) { try { - String value = TagRegistry.INSTANCE.getValue(var); - if (value != null) { - return value; + Tag tag = TagRegistry.INSTANCE.getTag(var); + String value = tag.getValue(); + if (value == null) { + return "{" + var + "}"; } + if (value.isEmpty()) { + value = tag.getValue(this.parent); + } + + return value; } catch (Exception e) { Reference.logger.debug("Failed to get value!", e); return "null"; } - - return "{" + var + "}"; } public String getReplacedValue() { @@ -124,8 +137,8 @@ public String toString() { return String.format(Locale.ENGLISH, "[%s] '%s'", getClass(), this.value); } - public static void setInfo(List info) { - Value.info = info; + public void setParent(InfoText parent) { + this.parent = parent; } public static Value fromString(String str) { diff --git a/src/main/java/com/github/lunatrius/ingameinfo/value/ValueComplex.java b/src/main/java/com/github/lunatrius/ingameinfo/value/ValueComplex.java index b92d833..ba7c1f7 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/value/ValueComplex.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/value/ValueComplex.java @@ -17,6 +17,7 @@ import com.github.lunatrius.core.entity.EntityHelper; import com.github.lunatrius.ingameinfo.InGameInfoCore; +import com.github.lunatrius.ingameinfo.client.gui.Info; import com.github.lunatrius.ingameinfo.client.gui.InfoIcon; import com.github.lunatrius.ingameinfo.client.gui.InfoItem; import com.github.lunatrius.ingameinfo.handler.ConfigurationHandler; @@ -242,12 +243,18 @@ public static void tick() { public static class ValueIcon extends ValueComplex { + private static int lastId; + + public ValueIcon() { + this.setName("icon" + lastId++); + } + @Override public boolean isValidSize() { - return this.values.size() == 1 || this.values.size() == 2 + return (this.values.size() == 1 || this.values.size() == 2 || this.values.size() == 5 || this.values.size() == 7 - || this.values.size() == 11; + || this.values.size() == 11); } @Override @@ -256,10 +263,12 @@ public String getValue() { int size = this.values.size(); String what = getValue(0); - if (size == 1 || size == 2) { - InfoItem item; - ItemStack itemStack; + Info value = parent.getAttachedValue(getName()); + if (value != null && value.getIdentifier().equals(what)) { + return ""; + } + if (size == 1 || size == 2) { int metadata = 0; if (size == 2) { metadata = getIntValue(1); @@ -270,22 +279,23 @@ public String getValue() { } } - itemStack = new ItemStack(GameData.getItemRegistry().getObject(what), 1, metadata); - if (itemStack.getItem() != null) { - item = new InfoItem(Minecraft.getMinecraft().fontRenderer, itemStack); - info.add(item); - return Tag.getIconTag(item); + ItemStack itemStack = new ItemStack(GameData.getItemRegistry().getObject(what), 1, metadata); + if (itemStack.getItem() == null) { + itemStack = new ItemStack(GameData.getBlockRegistry().getObject(what), 1, metadata); } - itemStack = new ItemStack(GameData.getBlockRegistry().getObject(what), 1, metadata); - if (itemStack.getItem() != null) { - item = new InfoItem(Minecraft.getMinecraft().fontRenderer, itemStack); - info.add(item); - return Tag.getIconTag(item); + if (itemStack.getItem() == null) return ""; + + InfoItem item = new InfoItem(itemStack); + item.setIdentifier(what); + if (parent != null) { + parent.attachValue(getName(), item); } + return Tag.getIconTag(item); } InfoIcon icon = new InfoIcon(what); + icon.setIdentifier(what); int index = 0; if (size == 5 || size == 11) { @@ -306,7 +316,9 @@ public String getValue() { icon.setTextureData(iconX, iconY, iconWidth, iconHeight, textureWidth, textureHeight); } - info.add(icon); + if (parent != null) { + parent.attachValue(getName(), icon); + } return Tag.getIconTag(icon); } catch (Exception e) { return "?"; diff --git a/src/main/java/com/github/lunatrius/ingameinfo/value/ValueSimple.java b/src/main/java/com/github/lunatrius/ingameinfo/value/ValueSimple.java index b826efe..e606f98 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/value/ValueSimple.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/value/ValueSimple.java @@ -29,7 +29,7 @@ public boolean isSimple() { @Override public boolean isValidSize() { - return this.values.size() == 0; + return this.values.isEmpty(); } public static class ValueString extends ValueSimple { diff --git a/src/main/java/com/github/lunatrius/ingameinfo/value/registry/ValueRegistry.java b/src/main/java/com/github/lunatrius/ingameinfo/value/registry/ValueRegistry.java index 313a619..67e3d45 100644 --- a/src/main/java/com/github/lunatrius/ingameinfo/value/registry/ValueRegistry.java +++ b/src/main/java/com/github/lunatrius/ingameinfo/value/registry/ValueRegistry.java @@ -49,7 +49,7 @@ public Value forName(String name) { try { final Class clazz = this.stringClassMap.get(name); if (clazz != null) { - return clazz.newInstance(); + return clazz.getDeclaredConstructor().newInstance(); } } catch (Exception e) { Reference.logger.error(String.format("Failed to create an instance for %s!", name), e);