From be4aa2592a80911299101fde803f89ab43ce9c80 Mon Sep 17 00:00:00 2001 From: bigguy345 Date: Thu, 12 Mar 2026 10:39:02 +0200 Subject: [PATCH] MASSIVE FONT RENDERING FIX, HUGE HUGE HUGE --- .../java/noppes/npcs/config/GlyphCache.java | 71 +++++++-- .../java/noppes/npcs/config/StringCache.java | 145 +++++++++++++----- 2 files changed, 168 insertions(+), 48 deletions(-) diff --git a/src/main/java/noppes/npcs/config/GlyphCache.java b/src/main/java/noppes/npcs/config/GlyphCache.java index 86f34d433..5379cb1b9 100644 --- a/src/main/java/noppes/npcs/config/GlyphCache.java +++ b/src/main/java/noppes/npcs/config/GlyphCache.java @@ -4,6 +4,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GLAllocation; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; import java.awt.AlphaComposite; import java.awt.Color; @@ -43,13 +44,13 @@ public class GlyphCache { * The width in pixels of every texture used for caching pre-rendered glyph images. Used by GlyphCache when calculating * floating point 0.0-1.0 texture coordinates. Must be a power of two for mip-mapping to work. */ - private static final int TEXTURE_WIDTH = 256; + private static final int TEXTURE_WIDTH = 512; /** * The height in pixels of every texture used for caching pre-rendered glyph images. Used by GlyphCache when calculating * floating point 0.0-1.0 texture coordinates. Must be a power of two for mip-mapping to work. */ - private static final int TEXTURE_HEIGHT = 256; + private static final int TEXTURE_HEIGHT = 512; /** * Initial width in pixels of the stringImage buffer used to extract individual glyph images. @@ -66,7 +67,14 @@ public class GlyphCache { * glyphs from "bleeding through" when the scaled GUI resolution is not pixel aligned and sometimes results in off-by-one * sampling of the glyph cache textures. */ - private static final int GLYPH_BORDER = 1; + private static final int GLYPH_BORDER = 2; + + /** + * Extra padding (in pixels) added around each glyph's reported pixel bounds before blitting into the atlas. + * Font hinting (especially GASP-aware rendering) can cause rendered pixels to extend beyond the bounds + * reported by GlyphVector.getGlyphPixelBounds(). This padding ensures those overflow pixels are captured. + */ + private static final int GLYPH_PADDING = 2; /** * Transparent (alpha zero) white background color for use with BufferedImage.clearRect(). @@ -107,9 +115,23 @@ public class GlyphCache { /** * Needed for all text layout operations that create GlyphVectors (maps point size to pixel size). + * Rebuilt after setRenderingHints() so layout FRC matches rendering FRC (especially for GASP hinting). */ private FontRenderContext fontRenderContext = glyphCacheGraphics.getFontRenderContext(); + /** + * Return the current FontRenderContext used for glyph layout and rendering. + * StringCache must use this same FRC when computing glyph pixel bounds for positioning, + * so that layout positions match the GASP-aware hinting used during rasterization. + */ + FontRenderContext getFontRenderContext() { + return fontRenderContext; + } + + int getGlyphPadding() { + return GLYPH_PADDING; + } + /** * Intermediate data array for use with textureImage.getRgb(). @@ -282,6 +304,11 @@ public class GlyphCache { return (int) (font.getLineMetrics(s, this.fontRenderContext).getHeight()); } + java.awt.font.LineMetrics getLineMetrics(String s) { + Font font = lookupFont(s.toCharArray(), 0, s.length(), 0); + return font.getLineMetrics(s, this.fontRenderContext); + } + /** * Given a single OpenType font, perform full text layout and create a new GlyphVector for a string. * @@ -386,6 +413,14 @@ public class GlyphCache { boolean vectorRendered = false; /* True if entire GlyphVector was rendered into stringImage */ for (int index = 0; index < numGlyphs; index++) { + int charIndex = start + vector.getGlyphCharIndex(index); + if (charIndex >= start && charIndex < limit) { + char c = text[charIndex]; + if (c == '\n' || c == '\r') { + continue; + } + } + /* If this glyph code is already in glyphCache, then there is no reason to pre-render it again */ int glyphCode = vector.getGlyphCode(index); if (glyphCache.containsKey(fontKey | glyphCode)) { @@ -422,6 +457,9 @@ public class GlyphCache { */ vectorBounds = vector.getPixelBounds(fontRenderContext, 0, 0); + /* Expand bounds to account for hinting overflow */ + vectorBounds.grow(GLYPH_PADDING, GLYPH_PADDING); + /* Enlage the stringImage if it is too small to store the entire rendered string */ if (stringImage == null || vectorBounds.width > stringImage.getWidth() || vectorBounds.height > stringImage.getHeight()) { int width = Math.max(vectorBounds.width, stringImage.getWidth()); @@ -429,7 +467,7 @@ public class GlyphCache { allocateStringImage(width, height); } - /* Erase the upper-left corner where the string will get drawn*/ + /* Erase the region where the string will get drawn (expanded for hinting overflow) */ stringGraphics.clearRect(0, 0, vectorBounds.width, vectorBounds.height); /* Draw string with opaque white color and baseline adjustment so the upper-left corner of the image is at (0,0) */ @@ -441,8 +479,11 @@ public class GlyphCache { * by this method is positioned around the origin of each individual glyph." However, the actual * bounds are all relative to the start of the entire GlyphVector, which is actually more useful * for extracting the glyph's image from the rendered string. + * + * Passing fontRenderContext ensures bounds match the GASP-aware rendering hints. */ - Rectangle rect = vector.getGlyphPixelBounds(index, null, -vectorBounds.x, -vectorBounds.y); + Rectangle rect = vector.getGlyphPixelBounds(index, fontRenderContext, -vectorBounds.x, -vectorBounds.y); + rect.grow(GLYPH_PADDING, GLYPH_PADDING); /* If the current line in cache image is full, then advance to the next line */ if (cachePosX + rect.width + GLYPH_BORDER > TEXTURE_WIDTH) { @@ -573,10 +614,20 @@ public class GlyphCache { private void setRenderingHints() { stringGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antiAliasEnabled ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF); - stringGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, - antiAliasEnabled ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); + + if (antiAliasEnabled) { + stringGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, + RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); + stringGraphics.setRenderingHint(RenderingHints.KEY_RENDERING, + RenderingHints.VALUE_RENDER_QUALITY); + } else { + stringGraphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, + RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); + } stringGraphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF); + + fontRenderContext = stringGraphics.getFontRenderContext(); } /** @@ -608,8 +659,10 @@ public class GlyphCache { GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, imageBuffer); /* Explicitely disable mipmap support becuase updateTexture() will only update the base level 0 */ - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); - GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + 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); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); + GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); } /** diff --git a/src/main/java/noppes/npcs/config/StringCache.java b/src/main/java/noppes/npcs/config/StringCache.java index c40d59f1c..773e0680c 100644 --- a/src/main/java/noppes/npcs/config/StringCache.java +++ b/src/main/java/noppes/npcs/config/StringCache.java @@ -3,11 +3,13 @@ package noppes.npcs.config; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.ResourceLocation; +import noppes.npcs.LogWriter; import org.lwjgl.opengl.GL11; import java.awt.Font; -import java.awt.Point; +import java.awt.Rectangle; import java.awt.font.GlyphVector; +import java.awt.geom.Point2D; import java.lang.ref.WeakReference; import java.text.Bidi; import java.util.ArrayList; @@ -71,6 +73,31 @@ public class StringCache { */ private static final int STRIKETHROUGH_THICKNESS = 2; + // BetterFonts renders glyphs at 2x internal resolution; this scale converts to GUI coords + private static final float RENDER_SCALE = 0.5F; + private static final boolean FONT_DEBUG_LOG = Boolean.getBoolean("cnpc.font.debug"); + private static final boolean FONT_DEBUG_DISABLE_INK_OFFSET = Boolean.getBoolean("cnpc.font.debug.disableInkOffset"); + + private static boolean isLineBreak(char c) { + return c == '\n' || c == '\r'; + } + + private static boolean isSpacingDebugGlyph(char c) { + return c == '(' || c == '"' || c == 't' || c == '.'; + } + + private static String debugGlyphLabel(char c) { + return c == '"' ? "\\\"" : String.valueOf(c); + } + + private static float pixelSnap(float coord) { + return (float) Math.floor(coord * 2.0F + 0.5F) * RENDER_SCALE; + } + + private int baselineOffset = BASELINE_OFFSET; + private int underlineOffset = UNDERLINE_OFFSET; + private int strikethroughOffset = STRIKETHROUGH_OFFSET; + /** * Reference to the unicode.FontRenderer class. Needed for creating GlyphVectors and retrieving glyph texture coordinates. */ @@ -319,31 +346,21 @@ public class StringCache { * the string to which this Glyph object belongs. */ static private class Glyph implements Comparable { - /** - * The index into the original string (i.e. with color codes) for the character that generated this glyph. - */ public int stringIndex; - - /** - * Texture ID and position/size of the glyph's pre-rendered image within the cache texture. - */ public GlyphCache.Entry texture; - /** - * Glyph's horizontal position (in pixels) relative to the entire string's baseline - */ + /** Logical horizontal position from getGlyphPosition() — used for spacing/advance */ public int x; - /** - * Glyph's vertical position (in pixels) relative to the entire string's baseline - */ + /** Ink vertical position from getGlyphPixelBounds() — used for texture quad placement */ public int y; - /** - * Glyph's horizontal advance (in pixels) used for strikethrough and underline effects - */ + /** Horizontal advance (logical) used for strikethrough and underline effects */ public int advance; + /** Ink X offset from logical position (inkBoundsX - logicalX) for texture quad placement */ + public int inkOffsetX; + /** * Allows arrays of Glyph objects to be sorted. Performs numeric comparison on stringIndex. * @@ -452,6 +469,17 @@ public class StringCache { maxY = g.y; } fontHeight = (int) ((maxY + height) / 2.0F - minY / 2.0F); + updateFontMetrics(); + } + + private void updateFontMetrics() { + java.awt.font.LineMetrics lm = glyphCache.getLineMetrics("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); + float ascent = lm.getAscent(); + float descent = lm.getDescent(); + + baselineOffset = (int) (ascent * RENDER_SCALE + 0.5f); + underlineOffset = (int) (descent * 0.25f + 0.5f); + strikethroughOffset = -(int) (ascent * 0.35f + 0.5f); } /** @@ -495,7 +523,7 @@ public class StringCache { Entry entry = cacheString(str); /* Adjust the baseline of the string because the startY coordinate in Minecraft is for the top of the string */ - startY += BASELINE_OFFSET; + startY += baselineOffset; /* Color currently selected by color code; reapplied to Tessellator instance after glBindTexture() */ @@ -548,7 +576,7 @@ public class StringCache { /* Select the current glyph's texture information and horizontal layout position within this string */ Glyph glyph = entry.glyphs[glyphIndex]; GlyphCache.Entry texture = glyph.texture; - int glyphX = glyph.x; + int glyphX = glyph.x + glyph.inkOffsetX; /* * Replace ASCII digits in the string with their respective glyphs; strings differing by digits are only cached once. @@ -557,6 +585,10 @@ public class StringCache { * of the width mismatch. */ char c = str.charAt(glyph.stringIndex); + if (isLineBreak(c)) { + continue; + } + if (c >= '0' && c <= '9') { int oldWidth = texture.width; texture = digitGlyphs[fontStyle][c - '0'].texture; @@ -580,10 +612,20 @@ public class StringCache { } /* The divide by 2.0F is needed to align with the scaled GUI coordinate system; startX/startY are already scaled */ - float x1 = startX + (glyphX) / 2.0F; - float x2 = startX + (glyphX + texture.width) / 2.0F; - float y1 = startY + (glyph.y) / 2.0F; - float y2 = startY + (glyph.y + texture.height) / 2.0F; + if (FONT_DEBUG_DISABLE_INK_OFFSET) { + glyphX = glyph.x; + } + float x1 = pixelSnap(startX + (glyphX) * RENDER_SCALE); + float x2 = pixelSnap(startX + (glyphX + texture.width) * RENDER_SCALE); + float y1 = pixelSnap(startY + (glyph.y) * RENDER_SCALE); + float y2 = pixelSnap(startY + (glyph.y + texture.height) * RENDER_SCALE); + + if (FONT_DEBUG_LOG && isSpacingDebugGlyph(c)) { + LogWriter.info("[StringCache glyph-debug] char='" + debugGlyphLabel(c) + "' idx=" + glyph.stringIndex + + " x=" + glyph.x + " advance=" + glyph.advance + " texW=" + texture.width + + " inkOffsetX=" + glyph.inkOffsetX + " quadX1=" + x1 + " quadX2=" + x2 + + " y=" + glyph.y + " tex=" + texture.textureName); + } tessellator.addVertexWithUV(x1, y1, 0, texture.u1, texture.v1); tessellator.addVertexWithUV(x1, y2, 0, texture.u1, texture.v2); @@ -625,10 +667,10 @@ public class StringCache { /* Draw underline under glyph if the style is enabled */ if ((renderStyle & ColorCode.UNDERLINE) != 0) { /* The divide by 2.0F is needed to align with the scaled GUI coordinate system; startX/startY are already scaled */ - float x1 = startX + (glyph.x - glyphSpace) / 2.0F; - float x2 = startX + (glyph.x + glyph.advance) / 2.0F; - float y1 = startY + (UNDERLINE_OFFSET) / 2.0F; - float y2 = startY + (UNDERLINE_OFFSET + UNDERLINE_THICKNESS) / 2.0F; + float x1 = pixelSnap(startX + (glyph.x - glyphSpace) * RENDER_SCALE); + float x2 = pixelSnap(startX + (glyph.x + glyph.advance) * RENDER_SCALE); + float y1 = pixelSnap(startY + (underlineOffset) * RENDER_SCALE); + float y2 = pixelSnap(startY + (underlineOffset + UNDERLINE_THICKNESS) * RENDER_SCALE); tessellator.addVertex(x1, y1, 0); tessellator.addVertex(x1, y2, 0); @@ -639,10 +681,10 @@ public class StringCache { /* Draw strikethrough in the middle of glyph if the style is enabled */ if ((renderStyle & ColorCode.STRIKETHROUGH) != 0) { /* The divide by 2.0F is needed to align with the scaled GUI coordinate system; startX/startY are already scaled */ - float x1 = startX + (glyph.x - glyphSpace) / 2.0F; - float x2 = startX + (glyph.x + glyph.advance) / 2.0F; - float y1 = startY + (STRIKETHROUGH_OFFSET) / 2.0F; - float y2 = startY + (STRIKETHROUGH_OFFSET + STRIKETHROUGH_THICKNESS) / 2.0F; + float x1 = pixelSnap(startX + (glyph.x - glyphSpace) * RENDER_SCALE); + float x2 = pixelSnap(startX + (glyph.x + glyph.advance) * RENDER_SCALE); + float y1 = pixelSnap(startY + (strikethroughOffset) * RENDER_SCALE); + float y2 = pixelSnap(startY + (strikethroughOffset + STRIKETHROUGH_THICKNESS) * RENDER_SCALE); tessellator.addVertex(x1, y1, 0); tessellator.addVertex(x1, y2, 0); @@ -1125,6 +1167,11 @@ public class StringCache { /* Break the string up into segments, where each segment can be displayed using a single font */ while (start < limit) { + if (isLineBreak(text[start])) { + start++; + continue; + } + Font font = glyphCache.lookupFont(text, start, limit, style); int next = font.canDisplayUpTo(text, start, limit); @@ -1177,20 +1224,41 @@ public class StringCache { /* Creating a GlyphVector takes care of all language specific OpenType glyph substitutions and positionings */ GlyphVector vector = glyphCache.layoutGlyphVector(font, text, start, limit, layoutFlags); + /* + * Use the same GASP-aware FontRenderContext that was used to rasterize glyphs into the atlas. + * Passing null here would use a default FRC that can produce different pixel bounds for hinted + * glyphs, causing position mismatches and visible spacing gaps (especially on punctuation). + */ + java.awt.font.FontRenderContext frc = glyphCache.getFontRenderContext(); + /* * Extract all needed information for each glyph from the GlyphVector so it won't be needed for actual rendering. * Note that initially, glyph.start holds the character index into the stripped text array. But after the entire * string is layed out, this field will be adjusted on every Glyph object to correctly index the original unstripped * string. + * + * Use getGlyphPosition() (logical font metrics) for horizontal placement and advance calculation. + * Use getGlyphPixelBounds() only for the Y position and to compute the ink X offset from the logical X. + * This separation ensures proper inter-glyph spacing (from logical metrics) while keeping correct + * texture quad alignment (from ink bounds). Under GASP hinting, ink bounds can be tighter than + * logical positions, causing glyphs to visually touch or overlap if used for spacing. */ Glyph glyph = null; int numGlyphs = vector.getNumGlyphs(); + int glyphPadding = glyphCache.getGlyphPadding(); for (int index = 0; index < numGlyphs; index++) { - Point position = vector.getGlyphPixelBounds(index, null, advance, 0).getLocation(); + int charIndex = start + vector.getGlyphCharIndex(index); + if (charIndex >= start && charIndex < limit && isLineBreak(text[charIndex])) { + continue; + } - /* Compute horizontal advance for the previous glyph based on this glyph's position */ + Point2D logicalPos = vector.getGlyphPosition(index); + int logicalX = advance + (int) logicalPos.getX(); + Rectangle inkBounds = vector.getGlyphPixelBounds(index, frc, advance, 0); + + /* Compute horizontal advance for the previous glyph based on logical positions */ if (glyph != null) { - glyph.advance = position.x - glyph.x; + glyph.advance = logicalX - glyph.x; } /* @@ -1198,10 +1266,11 @@ public class StringCache { * it will be corrected later to account for the color codes that have been stripped out. */ glyph = new Glyph(); - glyph.stringIndex = start + vector.getGlyphCharIndex(index); + glyph.stringIndex = charIndex; glyph.texture = glyphCache.lookupGlyph(font, vector.getGlyphCode(index)); - glyph.x = position.x; - glyph.y = position.y; + glyph.x = logicalX; + glyph.y = inkBounds.y - glyphPadding; + glyph.inkOffsetX = (inkBounds.x - logicalX) - glyphPadding; glyphList.add(glyph); } @@ -1215,5 +1284,3 @@ public class StringCache { return advance; } } - -