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.Rectangle; import java.awt.font.GlyphVector; import java.awt.geom.Point2D; import java.lang.ref.WeakReference; import java.text.Bidi; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.WeakHashMap; /** * @author https://github.com/secretdataz/BetterFonts * The StringCache is the public interface for rendering of all Unicode strings using OpenType fonts. It caches the glyph layout * of individual strings, and it uses a GlyphCache instance to cache the pre-rendered images for individual glyphs. Once a string * and its glyph images are cached, the critical path in renderString() will draw the glyphs as fast as if using a bitmap font. * Strings are cached using weak references through a two layer string cache. Strings that are no longer in use by Minecraft will * be evicted from the cache, while the pre-rendered images of individual glyphs remains cached forever. The following diagram * illustrates how this works: * *
* String passed to Key object considers Entry object holds Each Glyph object GlyphCache.Entry stores
* renderString(); all ASCII digits equal an array of Glyph belongs to only one the texture ID, image
* mapped by weak to zero ('0'); objects which may Entry object; it has width/height and
* weakRefCache mapped by weak not directly the glyph x/y pos normalized texture
* to Key object stringCahe to Entry correspond to Unicode within the string coordinates.
* chars in string
* String("Fi1") ------------\ ---> Glyph("F") ----------> GlyphCache.Entry("F")
* N:1 \ 1:1 1:N / N:1
* String("Fi4") ------------> Key("Fi0") -------------> Entry("Fi0") -----+----> Glyph("i") ----------> GlyphCache.Entry("i")
* \ N:1
* ---> Glyph("0") -----\
* ----> GlyphCache.Entry("0")
* ---> Glyph("0") -----/
* N:1 1:1 1:N / N:1
* String("Be1") ------------> Key("Be0") -------------> Entry("Be0") -----+----> Glyph("e") ----------> GlyphCache.Entry("e")
* \ N:1
* ---> Glyph("B") ----------> GlyphCache.Entry("B")
*
*/
public class StringCache {
/**
* Vertical adjustment (in pixels * 2) to string position because Minecraft uses top of string instead of baseline
*/
private static final int BASELINE_OFFSET = 7;
/**
* Offset from the string's baseline as which to draw the underline (in pixels)
*/
private static final int UNDERLINE_OFFSET = 1;
/**
* Thickness of the underline (in pixels)
*/
private static final int UNDERLINE_THICKNESS = 2;
/**
* Offset from the string's baseline as which to draw the strikethrough line (in pixels)
*/
private static final int STRIKETHROUGH_OFFSET = -6;
/**
* Thickness of the strikethrough line (in pixels)
*/
private static final int STRIKETHROUGH_THICKNESS = 2;
// BetterFonts base scale: maps internal 2x glyph coords to GUI coords.
// With scale-aware rasterization, the effective scale becomes BASE_RENDER_SCALE / guiScaleFactor.
private static final float BASE_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 float renderScale() {
return BASE_RENDER_SCALE / glyphCache.getGuiScaleFactor();
}
private float pixelSnap(float coord) {
float scale = renderScale();
float invScale = 1.0F / scale;
return (float) Math.floor(coord * invScale + 0.5F) * 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.
*/
private GlyphCache glyphCache;
/**
* Color codes from original FontRender class. First 16 entries are the primary chat colors; second 16 are darker versions
* used for drop shadows.
*/
private int colorTable[];
/**
* A cache of recently seen strings to their fully layed-out state, complete with color changes and texture coordinates of
* all pre-rendered glyph images needed to display this string. The weakRefCache holds strong references to the Key
* objects used in this map.
*/
private WeakHashMapThe font style is applied by prepending the appropriate Minecraft formatting codes
* (§l for bold, §o for italic) to the string before measuring. This causes cacheString()
* to lay out the entire string using the specified font style.
*
* @param str compute the width of this string
* @param fontStyle combination of {@link java.awt.Font#BOLD} and {@link java.awt.Font#ITALIC}
* @return the width in pixels (in the scaled GUI coordinate system)
*/
public int getStringWidth(String str, int fontStyle) {
/* Check for invalid arguments */
if (str == null || str.isEmpty()) {
return 0;
}
/* If plain style, delegate to the normal method (no prefix needed) */
if (fontStyle == Font.PLAIN) {
return getStringWidth(str);
}
/* Build the style prefix: §l for bold, §o for italic */
StringBuilder sb = new StringBuilder();
if ((fontStyle & Font.BOLD) != 0) {
sb.append('\u00A7').append('l');
}
if ((fontStyle & Font.ITALIC) != 0) {
sb.append('\u00A7').append('o');
}
sb.append(str);
return getStringWidth(sb.toString());
}
/**
* Return the number of characters in a string that will completly fit inside the specified width when rendered, with
* or without prefering to break the line at whitespace instead of breaking in the middle of a word. This private provides
* the real implementation of both sizeStringToWidth() and trimStringToWidth().
*
* @param str the String to analyze
* @param width the desired string width (in GUI coordinate system)
* @param breakAtSpaces set to prefer breaking line at spaces than in the middle of a word
* @return the number of characters from str that will fit inside width
*/
private int sizeString(String str, int width, boolean breakAtSpaces) {
/* Check for invalid arguments */
if (str == null || str.isEmpty()) {
return 0;
}
/* Convert the width from GUI coordinate system to internal glyph pixels */
width = (int) (width / renderScale());
/* The glyph array for a string is sorted by the string's logical character position */
Glyph glyphs[] = cacheString(str).glyphs;
/* Index of the last whitespace found in the string; used if breakAtSpaces is true */
int wsIndex = -1;
/* Add up the individual advance of each glyph until it exceeds the specified width */
int advance = 0, index = 0;
while (index < glyphs.length && advance <= width) {
/* Keep track of spaces if breakAtSpaces it set */
if (breakAtSpaces) {
char c = str.charAt(glyphs[index].stringIndex);
if (c == ' ') {
wsIndex = index;
} else if (c == '\n') {
wsIndex = index;
break;
}
}
advance += glyphs[index].advance;
index++;
}
/* Avoid splitting individual words if breakAtSpaces set; same test condition as in Minecraft's FontRenderer */
if (index < glyphs.length && wsIndex != -1 && wsIndex < index) {
index = wsIndex;
}
/* The string index of the last glyph that wouldn't fit gives the total desired length of the string in characters */
return index < glyphs.length ? glyphs[index].stringIndex : str.length();
}
/**
* Return the number of characters in a string that will completly fit inside the specified width when rendered.
*
* @param str the String to analyze
* @param width the desired string width (in GUI coordinate system)
* @return the number of characters from str that will fit inside width
*/
public int sizeStringToWidth(String str, int width) {
return sizeString(str, width, true);
}
/**
* Trim a string so that it fits in the specified width when rendered, optionally reversing the string
*
* @param str the String to trim
* @param width the desired string width (in GUI coordinate system)
* @param reverse if true, the returned string will also be reversed
* @return the trimmed and optionally reversed string
*/
public String trimStringToWidth(String str, int width, boolean reverse) {
int length = sizeString(str, width, false);
str = str.substring(0, length);
if (reverse) {
str = (new StringBuilder(str)).reverse().toString();
}
return str;
}
/**
* Apply a new vertex color to the Tessellator instance based on the numeric chat color code. Only the RGB component of the
* color is replaced by a color code; the alpha component of the original default color will remain.
*
* @param colorCode the chat color code as a number 0-15 or -1 to reset the default color
* @param color the default color used when the colorCode is -1
* @param shadowFlag ir true, the color code will select a darker version of the color suitable for drop shadows
* @return the new RGBA color set by this function
*/
private int applyColorCode(int colorCode, int color, boolean shadowFlag) {
/* A -1 color code indicates a reset to the initial color passed into renderString() */
if (colorCode != -1) {
colorCode = shadowFlag ? colorCode + 16 : colorCode;
color = colorTable[colorCode] & 0xffffff | color & 0xff000000;
}
Tessellator.instance.setColorRGBA(color >> 16 & 0xff, color >> 8 & 0xff, color & 0xff, color >> 24 & 0xff);
return color;
}
/**
* Add a string to the string cache by perform full layout on it, remembering its glyph positions, and making sure that
* every font glyph used by the string is pre-rendering. If this string has already been cached, then simply return its
* existing Entry from the cahe. Note that for caching purposes, this method considers two strings to be identical if they
* only differ in their ASCII digits; the renderString() method performs fast glyph substitution based on the actual digits
* in the string at the time.
*
* @param str this String will be layed out and added to the cache (or looked up, if alraedy cached)
* @return the string's cache entry containing all the glyph positions
*/
private Entry cacheString(String str) {
/*
* New Key object allocated only if the string was not found in the StringCache using lookupKey. This variable must
* be outside the (entry == null) code block to have a temporary strong reference between the time when the Key is
* added to stringCache and added to weakRefCache.
*/
Key key;
/* Either a newly created Entry object for the string, or the cached Entry if the string is already in the cache */
Entry entry = null;
/* Don't perform a cache lookup from other threads because the stringCache is not synchronized */
if (mainThread == Thread.currentThread()) {
/* Re-use existing lookupKey to avoid allocation overhead on the critical rendering path */
lookupKey.str = str;
/* If this string is already in the cache, simply return the cached Entry object */
entry = stringCache.get(lookupKey);
}
/* If string is not cached (or not on main thread) then layout the string */
if (entry == null) {
/* layoutGlyphVector() requires a char[] so create it here and pass it around to avoid duplication later on */
char text[] = str.toCharArray();
/* Strip all color codes from the string */
entry = new Entry();
int length = stripColorCodes(entry, str, text);
/* Layout the entire string, splitting it up by color codes and the Unicode bidirectional algorithm */
List