Compare commits

..
Author SHA1 Message Date
Algent 267378a381 Add fast texture atlas stitcher 2026-07-09 00:19:50 +02:00
25 changed files with 479 additions and 856 deletions

No files matched your search

@@ -10,7 +10,6 @@ import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_LE
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_PAYLOAD;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.compat.etfuturum.EtFuturumFontCompat;
import com.gtnewhorizons.angelica.config.FontConfig;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
@@ -703,79 +702,30 @@ public class BatchingFontRenderer {
if (chr == ColorCodeUtils.ESCAPED_AMPERSAND) { chr = '&'; }
final boolean surrogatePair = EtFuturumFontCompat.MODERN_FONT_ENABLED && !unicodeFlag
&& Character.isHighSurrogate(chr) && (charIdx + 1) < stringEnd
&& Character.isLowSurrogate(string.charAt(charIdx + 1));
final int codepoint = surrogatePair ? Character.toCodePoint(chr, string.charAt(charIdx + 1)) : chr;
final SupplementaryGlyphSource supGlyph = surrogatePair ? supplementarySource(codepoint) : null;
final boolean supplementary = supGlyph != null;
if (!supplementary) {
if (EtFuturumFontCompat.MODERN_FONT_ENABLED && Character.isSurrogate(chr)) {
// Substitute U+FFFD for a bad malformed glyph
final boolean pairedHigh = Character.isHighSurrogate(chr) && charIdx + 1 < stringEnd
&& Character.isLowSurrogate(string.charAt(charIdx + 1));
final boolean pairedLow = Character.isLowSurrogate(chr) && charIdx > stringOffset
&& Character.isHighSurrogate(string.charAt(charIdx - 1));
if (!pairedHigh && !pairedLow) { warnIsolatedSurrogate(chr, string); }
chr = REPLACEMENT_GLYPH;
}
if (FontConfig.enableCustomFont && FontConfig.enableGlyphReplacements) {
final char replacement = GlyphReplacements.getReplacementGlyph(chr);
if (replacement != 0) {
if (FontProviderCustom.getPrimary().isGlyphAvailable(replacement)
|| FontProviderCustom.getFallback().isGlyphAvailable(replacement)
) {
chr = replacement;
}
if (FontConfig.enableCustomFont && FontConfig.enableGlyphReplacements) {
final char replacement = GlyphReplacements.getReplacementGlyph(chr);
if (replacement != 0) {
if (FontProviderCustom.getPrimary().isGlyphAvailable(replacement)
|| FontProviderCustom.getFallback().isGlyphAvailable(replacement)
) {
chr = replacement;
}
}
if (curRandom) {
chr = FontProviderMC.get(this.isSGA).getRandomReplacement(chr);
}
}
float uStart, vStart, xAdvance, glyphW, uSz, vSz, shadowOffset, provYScale, provBaselineShift;
ResourceLocation texture;
boolean unifontGlyph;
if (supplementary) {
unifontGlyph = supGlyph.isUnifont();
uStart = supGlyph.getUStartCp(codepoint);
vStart = supGlyph.getVStartCp(codepoint);
xAdvance = supGlyph.getXAdvanceCp(codepoint) * glyphScaleX;
if (unifontGlyph) { xAdvance = (int) xAdvance; }
glyphW = supGlyph.getGlyphWCp(codepoint) * glyphScaleX;
uSz = supGlyph.getUSizeCp(codepoint);
vSz = supGlyph.getVSizeCp(codepoint);
shadowOffset = supGlyph.getShadowOffset();
provYScale = supGlyph.getYScaleMultiplier();
provBaselineShift = supGlyph.getBaselineShift();
texture = supGlyph.getTextureCp(codepoint);
} else {
final FontProvider fontProvider = FontStrategist.getFontProvider(this, chr, FontConfig.enableCustomFont, unicodeFlag);
unifontGlyph = fontProvider == FontProviderUnicode.get();
uStart = fontProvider.getUStart(chr);
vStart = fontProvider.getVStart(chr);
xAdvance = fontProvider.getXAdvance(chr) * glyphScaleX;
if (unifontGlyph) { xAdvance = (int) xAdvance; }
glyphW = fontProvider.getGlyphW(chr) * glyphScaleX;
uSz = fontProvider.getUSize(chr);
vSz = fontProvider.getVSize(chr);
shadowOffset = fontProvider.getShadowOffset();
provYScale = fontProvider.getYScaleMultiplier();
provBaselineShift = fontProvider.getBaselineShift();
texture = fontProvider.getTexture(chr);
if (curRandom) {
chr = FontProviderMC.get(this.isSGA).getRandomReplacement(chr);
}
heightNorth = anchorY + (underlying.FONT_HEIGHT - 1.0f) * (0.5f - glyphScaleY * provYScale / 2)
+ provBaselineShift * glyphScaleY;
float heightSouth = (underlying.FONT_HEIGHT - 1.0f) * glyphScaleY * provYScale;
FontProvider fontProvider = FontStrategist.getFontProvider(this, chr, FontConfig.enableCustomFont, unicodeFlag);
heightNorth = anchorY + (underlying.FONT_HEIGHT - 1.0f) * (0.5f - glyphScaleY * fontProvider.getYScaleMultiplier() / 2);
float heightSouth = (underlying.FONT_HEIGHT - 1.0f) * glyphScaleY * fontProvider.getYScaleMultiplier();
visibleCharIndex++;
// Check ASCII space, NBSP, NNBSP
if (!supplementary && (chr == ' ' || chr == '\u00A0' || chr == '\u202F')) {
if (chr == ' ' || chr == '\u00A0' || chr == '\u202F') {
curX += 4 * this.getWhitespaceScale() + (curBold ? 1 : 0);
continue;
}
@@ -797,9 +747,17 @@ public class BatchingFontRenderer {
gradientCharIndex++;
}
final float uStart = fontProvider.getUStart(chr);
final float vStart = fontProvider.getVStart(chr);
final float xAdvance = fontProvider.getXAdvance(chr) * glyphScaleX;
final float glyphW = fontProvider.getGlyphW(chr) * glyphScaleX;
final float uSz = fontProvider.getUSize(chr);
final float vSz = fontProvider.getVSize(chr);
final float itOff = curItalic ? 1.0F : 0.0F; // italic offset
final float shadowOffset = fontProvider.getShadowOffset();
final int shadowCopies = FontConfig.shadowCopies;
final int boldCopies = FontConfig.boldCopies;
final ResourceLocation texture = fontProvider.getTexture(chr);
final int idxId = idxWriterIndex;
// Wave: Y offset via sine wave
@@ -844,7 +802,7 @@ public class BatchingFontRenderer {
if (drawShadow) { charCount += shadowCopies * (curBold ? 2 : 1); }
if (curBold) { charCount += boldCopies; }
final int vtxCount = 4 * charCount;
pushDrawCmd(idxId, vtxCount / 2 * 3, texture, unifontGlyph);
pushDrawCmd(idxId, vtxCount / 2 * 3, texture, chr > 255);
curX += (xAdvance + (curBold ? 1.0f : 0.0f)) + getGlyphSpacing();
if (bookMode) { curX = (int) curX; }
@@ -863,7 +821,6 @@ public class BatchingFontRenderer {
pushDrawCmd(stIdx, 6, null, false);
strikethroughStartX = strikethroughEndX;
}
if (supplementary) { charIdx++; }
}
if (curUnderline && underlineStartX != underlineEndX) {
@@ -888,64 +845,9 @@ public class BatchingFontRenderer {
return curX + (enableShadow ? 1.0f : 0.0f);
}
public int getStringWidthBatched(String text) {
if (text == null) return 0;
text = ColorCodeUtils.convertAmpersandToSectionX(text);
final boolean unicodeFlag = underlying.getUnicodeFlag();
final float glyphScaleX = getGlyphScaleX();
final int len = text.length();
boolean bold = false;
int width = 0;
for (int i = 0; i < len; i++) {
final char c0 = text.charAt(i);
if (EtFuturumFontCompat.MODERN_FONT_ENABLED && !unicodeFlag && Character.isHighSurrogate(c0)
&& i + 1 < len && Character.isLowSurrogate(text.charAt(i + 1))) {
final int cp = Character.toCodePoint(c0, text.charAt(i + 1));
final SupplementaryGlyphSource src = supplementarySource(cp);
if (src != null) {
final int w = (int) (src.getXAdvanceCp(cp) * glyphScaleX);
width += w;
if (bold && w > 0) width += 1;
i++;
continue;
}
}
int k = (int) getCharWidthFine(c0);
if (k < 0 && i < len - 1) {
// §-format code
i++;
final char code = text.charAt(i);
if (code == 'l' || code == 'L') {
bold = true;
} else if (code == 'r' || code == 'R') {
bold = false;
}
k = 0;
}
width += k;
if (bold && k > 0) width += 1;
}
return width;
}
private static final char REPLACEMENT_GLYPH = '\uFFFD';
private static boolean warnedIsolatedSurrogate;
private static void warnIsolatedSurrogate(char chr, CharSequence string) {
if (warnedIsolatedSurrogate) { return; }
warnedIsolatedSurrogate = true;
FontStrategist.LOGGER.warn(
"Split emoji/extended char U+{} in \"{}\". A GUI split a supplementary character into separate Java chars during cursor/text ops. Rendering U+FFFD instead.",
Integer.toHexString(chr).toUpperCase(), string, new Throwable("isolated-surrogate draw site"));
}
public float getCharWidthFine(char chr) {
if (chr == ColorCodeUtils.ESCAPED_AMPERSAND) { chr = '&'; }
if (chr == FORMATTING_CHAR) { return -1; }
if (EtFuturumFontCompat.MODERN_FONT_ENABLED && Character.isSurrogate(chr)) { chr = REPLACEMENT_GLYPH; }
if (chr == ' ' || chr == '\u00A0' || chr == '\u202F') {
return 4 * this.getWhitespaceScale();
@@ -956,20 +858,6 @@ public class BatchingFontRenderer {
return fp.getXAdvance(chr) * this.getGlyphScaleX();
}
public int supplementaryAdvance(int codepoint) {
if (!EtFuturumFontCompat.MODERN_FONT_ENABLED) return -1;
final SupplementaryGlyphSource src = supplementarySource(codepoint);
return src != null ? (int) (src.getXAdvanceCp(codepoint) * getGlyphScaleX()) : -1;
}
private SupplementaryGlyphSource supplementarySource(int codepoint) {
final FontProviderBitmap bitmap = (!bookMode && !isSplash) ? FontStrategist.findSupplementaryBitmap(codepoint) : null;
if (bitmap != null) return bitmap;
final FontProviderUnicode unicode = FontProviderUnicode.get();
return unicode.hasCodepoint(codepoint) ? unicode : null;
}
public void overrideBlendFunc(int srcRgb, int dstRgb) {
blendSrcRGB = srcRgb;
blendDstRGB = dstRgb;
@@ -1,8 +0,0 @@
package com.gtnewhorizons.angelica.client.font;
import net.minecraft.util.ResourceLocation;
public record BitmapGlyph(ResourceLocation texture, float uStart, float vStart, float uSize, float vSize, float glyphW,
float advance) {
}
@@ -18,6 +18,4 @@ public interface FontProvider {
float getShadowOffset();
ResourceLocation getTexture(char chr);
float getYScaleMultiplier();
default float getBaselineShift() { return 0.0f; }
}
@@ -1,211 +0,0 @@
package com.gtnewhorizons.angelica.client.font;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.gtnewhorizons.angelica.config.FontConfig;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* A backported modern hand-drawn bitmap font provider.
* Et Futurum: Requium provides the resources.
*/
public final class FontProviderBitmap implements SupplementaryGlyphSource {
private static final Logger LOGGER = LogManager.getLogger("Angelica");
private static final ResourceLocation HANDDRAWN_DEFINITION = new ResourceLocation("etfuturum", "font/handdrawn.json");
private static final float ASCII_CELL = 8.0f;
private static final float ASCII_ASCENT = 7.0f;
private final Int2ObjectOpenHashMap<BitmapGlyph> glyphs = new Int2ObjectOpenHashMap<>();
private final float yScale;
private final float baselineShift;
private FontProviderBitmap(int renderHeight, int ascent) {
this.yScale = renderHeight / ASCII_CELL;
this.baselineShift = (ASCII_ASCENT - 4.0f) + 4.0f * this.yScale - ascent;
}
public static List<FontProviderBitmap> loadProviders() {
final List<FontProviderBitmap> providers = new ArrayList<>();
final IResourceManager rm = Minecraft.getMinecraft().getResourceManager();
try (InputStreamReader reader = new InputStreamReader(
rm.getResource(HANDDRAWN_DEFINITION).getInputStream(), StandardCharsets.UTF_8)) {
final JsonObject root = new JsonParser().parse(reader).getAsJsonObject();
final JsonArray defs = root.getAsJsonArray("providers");
int glyphCount = 0;
for (int i = 0; i < defs.size(); i++) {
final FontProviderBitmap p = fromDefinition(defs.get(i).getAsJsonObject(), rm);
if (p != null && !p.glyphs.isEmpty()) {
providers.add(p);
glyphCount += p.glyphs.size();
}
}
if (!providers.isEmpty()) {
LOGGER.info("Loaded {} modern hand-drawn font glyph(s) across {} provider(s)", glyphCount, providers.size());
}
} catch (Exception e) {
LOGGER.debug("Modern hand-drawn font sheets not loaded ({})", e.toString());
}
return providers;
}
private static FontProviderBitmap fromDefinition(JsonObject def, IResourceManager rm) {
try {
final String file = def.get("file").getAsString();
final int height = def.has("height") ? def.get("height").getAsInt() : (int) ASCII_CELL;
final int ascent = def.get("ascent").getAsInt();
final JsonArray charRows = def.getAsJsonArray("chars");
// "namespace:font/x.png" -> "namespace:textures/font/x.png"
final int colon = file.indexOf(':');
final String namespace = colon >= 0 ? file.substring(0, colon) : "minecraft";
final String path = colon >= 0 ? file.substring(colon + 1) : file;
final ResourceLocation texture = new ResourceLocation(namespace, "textures/" + path);
final BufferedImage image = ImageIO.read(rm.getResource(texture).getInputStream());
final int texW = image.getWidth();
final int texH = image.getHeight();
final int rows = charRows.size();
final String firstRow = charRows.get(0).getAsString();
final int cols = firstRow.codePointCount(0, firstRow.length());
final int cellW = texW / cols;
final int cellH = texH / rows;
final float scale = (float) height / cellH;
final FontProviderBitmap provider = new FontProviderBitmap(height, ascent);
for (int row = 0; row < rows; row++) {
final String line = charRows.get(row).getAsString();
int col = 0;
for (int offset = 0; offset < line.length(); ) {
final int cp = line.codePointAt(offset);
offset += Character.charCount(cp);
if (cp != 0 && !provider.glyphs.containsKey(cp)) {
final int cellX = col * cellW;
final int cellY = row * cellH;
final int ink = inkWidth(image, cellX, cellY, cellW, cellH);
final float advance = (int) (0.5F + ink * scale) + 1.0f;
final float glyphW = cellW * scale + 1.0f;
provider.glyphs.put(cp, new BitmapGlyph(texture,
(float) cellX / texW, (float) cellY / texH, (float) cellW / texW, (float) cellH / texH,
glyphW, advance));
}
col++;
}
}
return provider;
} catch (Exception e) {
LOGGER.debug("Skipping a hand-drawn font provider ({})", e.toString());
return null;
}
}
/** Rightmost inked column + 1 within a cell. */
private static int inkWidth(BufferedImage image, int cellX, int cellY, int cellW, int cellH) {
for (int x = cellW - 1; x >= 0; x--) {
for (int y = 0; y < cellH; y++) {
if ((image.getRGB(cellX + x, cellY + y) >>> 24) != 0) {
return x + 1;
}
}
}
return 0;
}
private int lastCp = -1;
private BitmapGlyph lastGlyph;
private BitmapGlyph glyph(int cp) {
if (cp == this.lastCp && this.lastGlyph != null) {
return this.lastGlyph;
}
final BitmapGlyph g = this.glyphs.get(cp);
this.lastCp = cp;
this.lastGlyph = g;
return g;
}
public boolean hasGlyph(int cp) { return this.glyphs.containsKey(cp); }
@Override
public float getUStartCp(int cp) { return glyph(cp).uStart(); }
@Override
public float getVStartCp(int cp) { return glyph(cp).vStart(); }
@Override
public float getXAdvanceCp(int cp) { return glyph(cp).advance(); }
@Override
public float getGlyphWCp(int cp) { return glyph(cp).glyphW(); }
@Override
public float getUSizeCp(int cp) { return glyph(cp).uSize(); }
@Override
public float getVSizeCp(int cp) { return glyph(cp).vSize(); }
@Override
public ResourceLocation getTextureCp(int cp) { return glyph(cp).texture(); }
@Override
public boolean isUnifont() { return false; }
@Override
public boolean isGlyphAvailable(char chr) { return hasGlyph(chr); }
@Override
public char getRandomReplacement(char chr) {
return chr;
}
@Override
public float getUStart(char chr) { return getUStartCp(chr); }
@Override
public float getVStart(char chr) { return getVStartCp(chr); }
@Override
public float getXAdvance(char chr) { return getXAdvanceCp(chr); }
@Override
public float getGlyphW(char chr) { return getGlyphWCp(chr); }
@Override
public float getUSize(char chr) { return getUSizeCp(chr); }
@Override
public float getVSize(char chr) { return getVSizeCp(chr); }
@Override
public float getShadowOffset() {
return FontConfig.fontShadowOffset;
}
@Override
public ResourceLocation getTexture(char chr) { return getTextureCp(chr); }
@Override
public float getYScaleMultiplier() {
return this.yScale;
}
@Override
public float getBaselineShift() {
return this.baselineShift;
}
}
@@ -3,104 +3,43 @@ package com.gtnewhorizons.angelica.client.font;
import com.gtnewhorizons.angelica.config.FontConfig;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.io.InputStream;
public final class FontProviderUnicode implements SupplementaryGlyphSource {
private static final Logger LOGGER = LogManager.getLogger("Angelica");
public final class FontProviderUnicode implements FontProvider {
private FontProviderUnicode() {
}
private void loadBmpWidths() {
try (InputStream in = Minecraft.getMinecraft().getResourceManager()
.getResource(new ResourceLocation("font/glyph_sizes.bin")).getInputStream()) {
readWidths(in, this.glyphWidth);
} catch (IOException e) {
LOGGER.warn("Failed to load font/glyph_sizes.bin; BMP glyph widths default to 0", e);
try {
InputStream inputstream = Minecraft.getMinecraft().getResourceManager()
.getResource(new ResourceLocation("font/glyph_sizes.bin")).getInputStream();
//noinspection ResultOfMethodCallIgnored
inputstream.read(this.glyphWidth);
}
}
public static void readWidths(InputStream in, byte[] dest) throws IOException {
int off = 0, n;
while (off < dest.length && (n = in.read(dest, off, dest.length - off)) != -1) {
off += n;
catch (IOException ioexception) {
throw new RuntimeException(ioexception);
}
}
private static class InstLoader { static final FontProviderUnicode instance = new FontProviderUnicode(); }
public static FontProviderUnicode get() { return FontProviderUnicode.InstLoader.instance; }
private static final int SUPPLEMENTARY_BASE = 0x10000;
private static final ResourceLocation[] unicodePageLocations = new ResourceLocation[0x1100];
private static final ResourceLocation[] unicodePageLocations = new ResourceLocation[256];
private final byte[] glyphWidth = new byte[65536];
private boolean bmpLoaded;
private byte[] hiGlyphWidth;
private boolean hiLoaded;
private ResourceLocation getUnicodePageLocation(int page) {
if (page >= 0 && page < unicodePageLocations.length) {
final ResourceLocation lookup = unicodePageLocations[page];
if (lookup != null) return lookup;
// %02x is a minimum width, so supplementary pages still format correctly
final ResourceLocation rl = new ResourceLocation(String.format("textures/font/unicode_page_%02x.png", page));
final ResourceLocation lookup = unicodePageLocations[page];
if (lookup == null) {
final ResourceLocation rl = new ResourceLocation(String.format(
"textures/font/unicode_page_%02x.png",
page));
unicodePageLocations[page] = rl;
return rl;
}
return new ResourceLocation(String.format("textures/font/unicode_page_%02x.png", page));
}
private int widthByte(int codepoint) {
if (codepoint < SUPPLEMENTARY_BASE) {
ensureBmpWidths();
return this.glyphWidth[codepoint];
}
ensureHiWidths();
final int idx = codepoint - SUPPLEMENTARY_BASE;
return idx < this.hiGlyphWidth.length ? this.hiGlyphWidth[idx] : 0;
}
private void ensureBmpWidths() {
if (this.bmpLoaded) return;
this.bmpLoaded = true;
loadBmpWidths();
}
private void ensureHiWidths() {
if (this.hiLoaded) return;
this.hiLoaded = true;
this.hiGlyphWidth = new byte[0];
try (InputStream in = Minecraft.getMinecraft().getResourceManager()
.getResource(new ResourceLocation("font/glyph_sizes_hi.bin")).getInputStream()) {
java.io.ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream();
byte[] chunk = new byte[8192];
int n;
while ((n = in.read(chunk)) != -1) buf.write(chunk, 0, n);
this.hiGlyphWidth = buf.toByteArray();
} catch (IOException e) {
LOGGER.debug("font/glyph_sizes_hi.bin not loaded ({}); supplementary glyph widths default to 0", e.toString());
} else {
return lookup;
}
}
public void reload() {
this.bmpLoaded = false;
this.hiLoaded = false;
this.hiGlyphWidth = null;
}
public boolean hasCodepoint(int codepoint) {
return widthByte(codepoint) != 0;
}
@Override
public boolean isUnifont() { return true; }
@Override
public boolean isGlyphAvailable(char chr) {
return true;
@@ -111,61 +50,46 @@ public final class FontProviderUnicode implements SupplementaryGlyphSource {
return chr;
}
public float getUStartCp(int cp) {
final float startColumnF = (float) ((widthByte(cp) >>> 4) & 15);
return ((float) ((cp & 15) * 16) + startColumnF + 0.21f) / 256.0f;
@Override
public float getUStart(char chr) {
final float startColumnF = (float)((this.glyphWidth[chr] >>> 4) & 15);
return ((float) (chr % 16 * 16) + startColumnF + 0.21f) / 256.0f;
}
public float getVStartCp(int cp) {
return ((float) (((cp & 255) >> 4) * 16) + 0.21f) / 256.0f;
@Override
public float getVStart(char chr) {
return ((float) ((chr & 255) / 16 * 16) + 0.21f) / 256.0f;
}
public float getXAdvanceCp(int cp) {
final int w = widthByte(cp);
final int startColumn = (w >>> 4) & 15;
final int endColumn = w & 15;
return ((endColumn + 1) - startColumn) / 2.0F + 1.0F;
@Override
public float getXAdvance(char chr) {
final int startColumn = (this.glyphWidth[chr] >>> 4) & 15;
final int endColumn = this.glyphWidth[chr] & 15;
final float startColumnF = (float) startColumn;
final float endColumnF = (float) (endColumn + 1);
return (endColumnF - startColumnF) / 2.0F + 1.0F;
}
public float getGlyphWCp(int cp) {
final int w = widthByte(cp);
final int startColumn = (w >>> 4) & 15;
final int endColumn = w & 15;
final float chrWidth = (endColumn + 1) - startColumn - 0.02F;
@Override
public float getGlyphW(char chr) {
final int startColumn = (this.glyphWidth[chr] >>> 4) & 15;
final int endColumn = this.glyphWidth[chr] & 15;
final float startColumnF = (float) startColumn;
final float endColumnF = (float) (endColumn + 1);
final float chrWidth = endColumnF - startColumnF - 0.02F;
return chrWidth / 2.0f + 1.0f;
}
public float getUSizeCp(int cp) {
final int w = widthByte(cp);
final int startColumn = (w >>> 4) & 15;
final int endColumn = w & 15;
final float chrWidth = (endColumn + 1) - startColumn - 0.02F;
@Override
public float getUSize(char chr) {
final int startColumn = (this.glyphWidth[chr] >>> 4) & 15;
final int endColumn = this.glyphWidth[chr] & 15;
final float startColumnF = (float) startColumn;
final float endColumnF = (float) (endColumn + 1);
final float chrWidth = endColumnF - startColumnF - 0.02F;
return (chrWidth - 0.42f) / 256.0f;
}
public float getVSizeCp(int cp) {
return getVSize((char) 0);
}
public ResourceLocation getTextureCp(int cp) {
return getUnicodePageLocation(cp >>> 8);
}
@Override
public float getUStart(char chr) { return getUStartCp(chr); }
@Override
public float getVStart(char chr) { return getVStartCp(chr); }
@Override
public float getXAdvance(char chr) { return getXAdvanceCp(chr); }
@Override
public float getGlyphW(char chr) { return getGlyphWCp(chr); }
@Override
public float getUSize(char chr) { return getUSizeCp(chr); }
@Override
public float getVSize(char chr) {
return (16.0f - 0.42f) / 256.0f;
@@ -178,7 +102,8 @@ public final class FontProviderUnicode implements SupplementaryGlyphSource {
@Override
public ResourceLocation getTexture(char chr) {
return getTextureCp(chr);
final int uniPage = chr / 256;
return getUnicodePageLocation(uniPage);
}
@Override
@@ -1,7 +1,6 @@
package com.gtnewhorizons.angelica.client.font;
import com.google.common.collect.HashMultiset;
import com.gtnewhorizons.angelica.compat.etfuturum.EtFuturumFontCompat;
import com.gtnewhorizons.angelica.config.FontConfig;
import com.gtnewhorizons.angelica.mixins.interfaces.ResourceAccessor;
import cpw.mods.fml.client.SplashProgress;
@@ -9,7 +8,6 @@ import lombok.Getter;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.resources.DefaultResourcePack;
import net.minecraft.util.ResourceLocation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -19,10 +17,7 @@ import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
@@ -75,28 +70,13 @@ public class FontStrategist {
availableFonts = fontSet.values().stream().sorted(Comparator.comparing(Font::getFontName)).toArray(Font[]::new);
// create and add the resource pack that provides fonts
final HashMap<String, File> packMap = new HashMap<>();
HashMap<String, File> packMap = new HashMap<>();
for (int i = 0; i < FontProviderCustom.ATLAS_COUNT; i++) {
packMap.put(FontProviderCustom.getPrimary().getAtlasResourceName(i), new File(FontProviderCustom.getPrimary().getAtlasFullPath(i)));
packMap.put(FontProviderCustom.getFallback().getAtlasResourceName(i), new File(FontProviderCustom.getFallback().getAtlasFullPath(i)));
}
// Override vanilla resource pack with our textures
DefaultResourcePack fontResourcePack = new DefaultResourcePack(packMap) {
@Override
public InputStream getInputStream(ResourceLocation location) throws IOException {
final File file = packMap.get(location.toString());
if (file != null && file.isFile()) {
return new FileInputStream(file);
}
throw new FileNotFoundException(location.getResourcePath());
}
@Override
public boolean resourceExists(ResourceLocation location) {
return packMap.containsKey(location.toString());
}
};
DefaultResourcePack fontResourcePack = new DefaultResourcePack(packMap);
List defaultResourcePacks = ((ResourceAccessor) Minecraft.getMinecraft()).angelica$getDefaultResourcePacks();
defaultResourcePacks.add(fontResourcePack);
}
@@ -139,43 +119,6 @@ public class FontStrategist {
if (loaded > 0) LOGGER.info("Loaded {} bundled font(s) from the pack", loaded);
}
private static volatile List<FontProviderBitmap> bitmapProviders;
private static List<FontProviderBitmap> bitmapProviders() {
List<FontProviderBitmap> local = bitmapProviders;
if (local == null) {
synchronized (FontStrategist.class) {
local = bitmapProviders;
if (local == null) {
local = FontProviderBitmap.loadProviders();
bitmapProviders = local;
}
}
}
return local;
}
private static FontProviderBitmap findBitmap(int codepoint) {
final List<FontProviderBitmap> providers = bitmapProviders();
for (final FontProviderBitmap provider : providers) {
if (provider.hasGlyph(codepoint)) {
return provider;
}
}
return null;
}
public static FontProviderBitmap findSupplementaryBitmap(int codepoint) {
return EtFuturumFontCompat.MODERN_FONT_ENABLED ? findBitmap(codepoint) : null;
}
public static void reloadFontResources() {
synchronized (FontStrategist.class) {
bitmapProviders = null;
}
FontProviderUnicode.get().reload();
}
/**
Lets you get a FontProvider per char while respecting font priority and fallbacks, the unicode flag, whether
SGA is on, if we're in a splash screen, if a font can even display a character in the first place, etc.
@@ -193,16 +136,8 @@ public class FontStrategist {
if (fp.isGlyphAvailable(chr)) { return fp; }
fp = FontProviderCustom.getFallback();
if (fp.isGlyphAvailable(chr)) { return fp; }
if (!forceUnicode && EtFuturumFontCompat.MODERN_FONT_ENABLED) {
final FontProviderBitmap bitmap = findBitmap(chr);
if (bitmap != null) { return bitmap; }
}
return FontProviderUnicode.get();
} else {
if (!forceUnicode && !me.isSplash && EtFuturumFontCompat.MODERN_FONT_ENABLED) {
final FontProviderBitmap bitmap = findBitmap(chr);
if (bitmap != null) { return bitmap; }
}
if (!forceUnicode && FontProviderMC.get(false).isGlyphAvailable(chr)) {
return FontProviderMC.get(false);
} else {
@@ -1,16 +0,0 @@
package com.gtnewhorizons.angelica.client.font;
import net.minecraft.util.ResourceLocation;
public interface SupplementaryGlyphSource extends FontProvider {
float getUStartCp(int cp);
float getVStartCp(int cp);
float getXAdvanceCp(int cp);
float getGlyphWCp(int cp);
float getUSizeCp(int cp);
float getVSizeCp(int cp);
ResourceLocation getTextureCp(int cp);
boolean isUnifont();
}
@@ -1,19 +0,0 @@
package com.gtnewhorizons.angelica.compat.etfuturum;
import ganymedes01.etfuturum.configuration.configs.ConfigMixins;
public final class EtFuturumFontCompat {
public static final boolean MODERN_FONT_ENABLED = detect();
private EtFuturumFontCompat() {
}
private static boolean detect() {
try {
return ConfigMixins.unicodeFontPages;
} catch (LinkageError e) {
return false;
}
}
}
@@ -211,8 +211,6 @@ public enum Mixins implements IMixins {
.addClientMixins(
"rendering.MixinBlock"
, "rendering.MixinBlockFluidBase"
, "rendering.MixinBlockLiquid"
, "rendering.BlockLiquidFlowInvoker"
, "rendering.AccessorBiomeColorEvent"
, "rendering.MixinBiomeGenBase"
, "rendering.MixinChunk"
@@ -417,12 +415,6 @@ public enum Mixins implements IMixins {
.setApplyIf(() -> AngelicaConfig.removeUnicodeEvenScaling)
.addClientMixins("angelica.bugfixes.MixinScaledResolution_UnicodeFix")),
FARSEEK_WORLDSLICE_COMPAT(new MixinBuilder("Let Farseek resolve celeritas' WorldSlice so Streams' water renders properly")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.FARSEEK)
.setApplyIf(() -> AngelicaConfig.enableCeleritas)
.addClientMixins("client.farseek.MixinFarseekIBlockAccessValue")),
SECURITYCRAFT_COMPAT(new MixinBuilder("Fix reflection in SecurityCraft for compat with Angelica")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.SECURITYCRAFT)
@@ -471,7 +463,9 @@ public enum Mixins implements IMixins {
OPTIMIZE_TEXTURE_LOADING(new MixinBuilder()
.setPhase(Phase.EARLY)
.addClientMixins("angelica.textures.MixinTextureUtil_OptimizeMipmap")
.addClientMixins(
"angelica.textures.MixinTextureUtil_OptimizeMipmap",
"angelica.textures.MixinStitcher")
.setApplyIf(() -> AngelicaConfig.optimizeTextureLoading)),
REPLACE_FFP(new MixinBuilder()
@@ -17,7 +17,6 @@ public enum TargetedMod implements ITargetMod {
DRAGON_API("Reika.DragonAPI.Auxiliary.DragonAPIASMHandler", "DragonAPI"),
ET_FUTURUM_REQUIEM(null, "etfuturum"),
EXTRAUTILS(null, "ExtraUtilities"),
FARSEEK("farseek.core.FarseekCoreMod", "farseek"),
FALSETWEAKS("com.falsepattern.falsetweaks.asm.CoreLoadingPlugin", "falsetweaks"),
MINEFACTORY_RELOADED(null, "MineFactoryReloaded"),
NTM_SPACE("com.hbm.dim.SolarSystem"),
@@ -0,0 +1,269 @@
package com.gtnewhorizons.angelica.textures;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.client.renderer.StitcherException;
import net.minecraft.client.renderer.texture.Stitcher;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.util.MathHelper;
public final class FastTextureStitcher {
private FastTextureStitcher() {}
public static Result stitch(Stitcher.Holder[] holders, int maxWidth, int maxHeight, boolean forcePowerOf2) {
if (holders.length == 0) {
return new Result(0, 0, Collections.<TextureAtlasSprite>emptyList());
}
long area = 0L;
int minWidth = 1;
int minHeight = 1;
boolean[] initialRotations = new boolean[holders.length];
for (int i = 0; i < holders.length; i++) {
Stitcher.Holder holder = holders[i];
initialRotations[i] = holder.isRotated();
int width = holder.getWidth();
int height = holder.getHeight();
if (width > maxWidth || height > maxHeight) {
throw unableToFit(holder, maxWidth, maxHeight);
}
area += (long) width * height;
minWidth = Math.max(minWidth, width);
minHeight = Math.max(minHeight, height);
}
int width = roundDimension(Math.max(minWidth, (int) Math.ceil(Math.sqrt(area))), forcePowerOf2);
width = Math.min(width, maxWidth);
int height = roundDimension(Math.max(minHeight, (int) ((area + width - 1L) / width)), forcePowerOf2);
height = Math.min(height, maxHeight);
while (width <= maxWidth && height <= maxHeight) {
restoreRotations(holders, initialRotations);
Result result = tryStitch(holders, width, height, forcePowerOf2);
if (result != null) {
return result;
}
if ((width <= height && width < maxWidth) || height >= maxHeight) {
width = grow(width, maxWidth, forcePowerOf2);
} else {
height = grow(height, maxHeight, forcePowerOf2);
}
}
throw unableToFit(holders[0], maxWidth, maxHeight);
}
private static Result tryStitch(Stitcher.Holder[] holders, int atlasWidth, int atlasHeight, boolean forcePowerOf2) {
List<Node> skyline = new ArrayList<>();
List<TextureAtlasSprite> sprites = new ArrayList<>(holders.length);
int[] xs = new int[holders.length];
int[] ys = new int[holders.length];
skyline.add(new Node(0, 0, atlasWidth));
int usedWidth = 0;
int usedHeight = 0;
for (int i = 0; i < holders.length; i++) {
Stitcher.Holder holder = holders[i];
Placement placement = findPlacement(skyline, atlasWidth, atlasHeight, holder);
if (placement == null) {
return null;
}
if (holder.isRotated() != placement.rotated) {
holder.rotate();
}
place(skyline, placement);
int width = holder.getWidth();
int height = holder.getHeight();
usedWidth = Math.max(usedWidth, placement.x + width);
usedHeight = Math.max(usedHeight, placement.y + height);
sprites.add(holder.getAtlasSprite());
xs[i] = placement.x;
ys[i] = placement.y;
}
int resultWidth = forcePowerOf2 ? atlasWidth : usedWidth;
int resultHeight = forcePowerOf2 ? atlasHeight : usedHeight;
for (int i = 0; i < holders.length; i++) {
Stitcher.Holder holder = holders[i];
TextureAtlasSprite sprite = holder.getAtlasSprite();
sprite.initSprite(resultWidth, resultHeight, xs[i], ys[i], holder.isRotated());
}
return new Result(resultWidth, resultHeight, sprites);
}
private static Placement findPlacement(List<Node> skyline, int atlasWidth, int atlasHeight, Stitcher.Holder holder) {
Placement best = findPlacement(skyline, atlasWidth, atlasHeight, holder.getWidth(), holder.getHeight(), holder.isRotated());
holder.rotate();
Placement rotated = findPlacement(skyline, atlasWidth, atlasHeight, holder.getWidth(), holder.getHeight(), holder.isRotated());
holder.rotate();
if (best == null) {
return rotated;
}
if (rotated == null) {
return best;
}
return rotated.bottom < best.bottom || rotated.bottom == best.bottom && rotated.x < best.x ? rotated : best;
}
private static Placement findPlacement(List<Node> skyline, int atlasWidth, int atlasHeight, int width, int height, boolean rotated) {
Placement best = null;
for (int i = 0; i < skyline.size(); i++) {
Node node = skyline.get(i);
int y = fit(skyline, i, width, height, atlasWidth, atlasHeight);
if (y >= 0) {
int bottom = y + height;
if (best == null || bottom < best.bottom || bottom == best.bottom && node.x < best.x) {
best = new Placement(i, node.x, y, width, bottom, rotated);
}
}
}
return best;
}
private static int fit(List<Node> skyline, int index, int width, int height, int atlasWidth, int atlasHeight) {
Node node = skyline.get(index);
if (node.x + width > atlasWidth) {
return -1;
}
int y = node.y;
int widthLeft = width;
for (int i = index; widthLeft > 0; i++) {
if (i >= skyline.size()) {
return -1;
}
Node current = skyline.get(i);
y = Math.max(y, current.y);
if (y + height > atlasHeight) {
return -1;
}
widthLeft -= current.width;
}
return y;
}
private static void place(List<Node> skyline, Placement placement) {
skyline.add(placement.index, new Node(placement.x, placement.bottom, placement.width));
for (int i = placement.index + 1; i < skyline.size(); i++) {
Node previous = skyline.get(i - 1);
Node current = skyline.get(i);
int shrink = previous.x + previous.width - current.x;
if (shrink <= 0) {
break;
}
current.x += shrink;
current.width -= shrink;
if (current.width <= 0) {
skyline.remove(i--);
} else {
break;
}
}
for (int i = 0; i < skyline.size() - 1; i++) {
Node current = skyline.get(i);
Node next = skyline.get(i + 1);
if (current.y == next.y) {
current.width += next.width;
skyline.remove(i-- + 1);
}
}
}
private static void restoreRotations(Stitcher.Holder[] holders, boolean[] rotations) {
for (int i = 0; i < holders.length; i++) {
if (holders[i].isRotated() != rotations[i]) {
holders[i].rotate();
}
}
}
private static int roundDimension(int value, boolean forcePowerOf2) {
return forcePowerOf2 ? MathHelper.roundUpToPowerOfTwo(value) : value;
}
private static int grow(int value, int max, boolean forcePowerOf2) {
if (value >= max) {
return max + 1;
}
int next = forcePowerOf2 ? MathHelper.roundUpToPowerOfTwo(value + 1) : value * 2;
return Math.min(Math.max(next, value + 1), max);
}
private static StitcherException unableToFit(Stitcher.Holder holder, int maxWidth, int maxHeight) {
return new StitcherException(holder, "Unable to fit: " + holder.getAtlasSprite().getIconName()
+ " - size: " + holder.getAtlasSprite().getIconWidth() + "x" + holder.getAtlasSprite().getIconHeight()
+ " - max atlas: " + maxWidth + "x" + maxHeight);
}
public static final class Result {
public final int width;
public final int height;
public final List<TextureAtlasSprite> sprites;
private Result(int width, int height, List<TextureAtlasSprite> sprites) {
this.width = width;
this.height = height;
this.sprites = sprites;
}
}
private static final class Node {
int x;
int y;
int width;
private Node(int x, int y, int width) {
this.x = x;
this.y = y;
this.width = width;
}
}
private static final class Placement {
final int index;
final int x;
final int y;
final int width;
final int bottom;
final boolean rotated;
private Placement(int index, int x, int y, int width, int bottom, boolean rotated) {
this.index = index;
this.x = x;
this.y = y;
this.width = width;
this.bottom = bottom;
this.rotated = rotated;
}
}
}
@@ -40,7 +40,6 @@ final class BlockOrientation extends RenderBlockState {
private int altMetadata;
private int metadataBits;
private int renderType;
private boolean iCtmBlock;
private int blockFace;
private int textureFace;
@@ -77,11 +76,6 @@ final class BlockOrientation extends RenderBlockState {
return z;
}
@Override
public int getMetadata() {
return metadata;
}
@Override
public int getBlockFace() {
return blockFace;
@@ -162,8 +156,8 @@ final class BlockOrientation extends RenderBlockState {
@Override
public boolean shouldConnectByBlock(Block neighbor, int neighborX, int neighborY, int neighborZ) {
return iCtmBlock ? ((ICTMBlock) block).shouldConnectByBlock(this, neighbor, neighborX, neighborY, neighborZ)
: block == neighbor && (metadataBits & (1 << blockAccess.getBlockMetadata(neighborX, neighborY, neighborZ))) != 0;
return block == neighbor
&& (metadataBits & (1 << blockAccess.getBlockMetadata(neighborX, neighborY, neighborZ))) != 0;
}
@Override
@@ -181,7 +175,6 @@ final class BlockOrientation extends RenderBlockState {
copy.altMetadata = altMetadata;
copy.metadataBits = metadataBits;
copy.renderType = renderType;
copy.iCtmBlock = iCtmBlock;
copy.blockFace = blockFace;
copy.textureFace = textureFace;
copy.textureFaceOrig = textureFaceOrig;
@@ -210,7 +203,6 @@ final class BlockOrientation extends RenderBlockState {
this.z = z;
renderType = block.getRenderType();
metadata = altMetadata = blockAccess.getBlockMetadata(x, y, z);
iCtmBlock = block instanceof ICTMBlock;
offsetsComputed = false;
}
@@ -231,7 +223,6 @@ final class BlockOrientation extends RenderBlockState {
renderType = block.getRenderType();
blockFace = textureFace = textureFaceOrig = face;
this.metadata = metadata;
iCtmBlock = block instanceof ICTMBlock;
metadataBits = 1 << metadata;
dx = dy = dz = 0;
rotateUV = 0;
@@ -9,7 +9,6 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.StampedLock;
import java.util.function.Consumer;
import com.github.bsideup.jabel.Desugar;
import net.minecraft.block.Block;
@@ -35,22 +34,10 @@ public class CTMUtils {
public static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CONNECTED_TEXTURES, "CTM");
public static class Overrides {
private static class Overrides {
private final List<TileOverride> all = new ArrayList<>();
private final Map<Block, List<BlockStateMatcher>> block = new IdentityHashMap<>();
private final Map<String, List<TileOverride>> tile = new HashMap<>();
public List<TileOverride> getAll() {
return all;
}
public Map<Block, List<BlockStateMatcher>> getBlock() {
return block;
}
public Map<String, List<TileOverride>> getTile() {
return tile;
}
}
private static Overrides overrides = new Overrides();
@@ -95,8 +82,6 @@ public class CTMUtils {
private static final AtomicInteger texturePackChangeCounter = new AtomicInteger(0);
private static final ArrayList<Consumer<Overrides>> ctmRegistrationCallbacks = new ArrayList<>();
static {
try {
Class.forName(MCPatcherUtils.RENDER_PASS_CLASS)
@@ -132,9 +117,6 @@ public class CTMUtils {
.listResources(TexturePackAPI.MCPATCHER_SUBDIR + "ctm", ".properties", true)) {
registerOverrideWithoutLock(newOverrides, TileOverride.create(resource, tileLoader));
}
for (Consumer<Overrides> callback : ctmRegistrationCallbacks) {
callback.accept(newOverrides);
}
}
for (ResourceLocation resource : BlendMethod.getAllBlankResources()) {
tileLoader.preloadTile(resource, false);
@@ -275,7 +257,7 @@ public class CTMUtils {
return RenderPassAPI.instance.skipDefaultRendering(block);
}
public static void registerOverrideWithoutLock(Overrides overrides, TileOverride override) {
private static void registerOverrideWithoutLock(Overrides overrides, TileOverride override) {
if (override != null && !override.isDisabled()) {
boolean registered = false;
List<BlockStateMatcher> matchingBlocks = override.getMatchingBlocks();
@@ -326,8 +308,4 @@ public class CTMUtils {
private static TileOverrideIterator.Metadata newMetadataIterator() {
return new TileOverrideIterator.Metadata(overrides.block, overrides.tile);
}
public static void addCtmRegistrationCallback(Consumer<Overrides> consumer) {
ctmRegistrationCallbacks.add(consumer);
}
}
@@ -1,10 +0,0 @@
package com.prupe.mcpatcher.ctm;
import net.minecraft.block.Block;
/**
* Implement this interface on blocks that support connected textures to allow them to control if they connect to neighbors or not
*/
public interface ICTMBlock {
boolean shouldConnectByBlock(RenderBlockState renderBlockState, Block neighbor, int neighborX, int neighborY, int neighborZ);
}
@@ -109,8 +109,6 @@ abstract public class RenderBlockState {
abstract public int getZ();
abstract public int getMetadata();
abstract public int getBlockFace();
abstract public int getTextureFace();
@@ -33,7 +33,7 @@ public abstract class TileOverride implements Comparable<TileOverride> {
private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CONNECTED_TEXTURES, "CTM");
public final PropertiesFile properties;
protected final PropertiesFile properties;
private final String baseFilename;
protected final TileLoader tileLoader;
protected final int renderPass;
@@ -79,10 +79,7 @@ public abstract class TileOverride implements Comparable<TileOverride> {
if (properties == null) {
return null;
}
return create(properties, tileLoader);
}
public static TileOverride create(PropertiesFile properties, TileLoader tileLoader) {
String method = properties.getString("method", "default")
.toLowerCase();
TileOverride override = null;
@@ -214,7 +211,7 @@ public abstract class TileOverride implements Comparable<TileOverride> {
for (int i = 0;; i++) {
ResourceLocation resource = TileLoader
.parseTileAddress(properties.getResource(), String.valueOf(i), blankResource);
if (!TexturePackAPI.hasResource(resource) && !tileLoader.ignoreMissingTextures()) {
if (!TexturePackAPI.hasResource(resource)) {
break;
}
if (!addIcon(resource)) {
@@ -240,7 +237,7 @@ public abstract class TileOverride implements Comparable<TileOverride> {
.parseTileAddress(properties.getResource(), token, blankResource);
if (resource == null) {
tileNames.add(null);
} else if (TexturePackAPI.hasResource(resource) || tileLoader.ignoreMissingTextures()) {
} else if (TexturePackAPI.hasResource(resource)) {
addIcon(resource);
} else {
properties.warning("could not find image %s", resource);
@@ -255,7 +252,7 @@ public abstract class TileOverride implements Comparable<TileOverride> {
for (int i = from; i <= to; i++) {
ResourceLocation resource = TileLoader
.parseTileAddress(properties.getResource(), String.valueOf(i), blankResource);
if (TexturePackAPI.hasResource(resource) || tileLoader.ignoreMissingTextures()) {
if (TexturePackAPI.hasResource(resource)) {
addIcon(resource);
} else {
properties.warning("could not find image %s", resource);
@@ -9,12 +9,12 @@ import net.minecraft.util.ResourceLocation;
import com.prupe.mcpatcher.MCLogger;
import com.prupe.mcpatcher.MCPatcherUtils;
public class PropertiesFile {
final public class PropertiesFile {
protected final MCLogger logger;
protected final ResourceLocation resource;
protected final String prefix;
protected final Properties properties;
private final MCLogger logger;
private final ResourceLocation resource;
private final String prefix;
private final Properties properties;
private int errorCount;
public static PropertiesFile get(MCLogger logger, ResourceLocation resource) {
@@ -147,16 +147,4 @@ public class PropertiesFile {
return resource.equals(((PropertiesFile) that).resource);
}
}
public MCLogger getLogger() {
return logger;
}
public String getPrefix() {
return prefix;
}
public Properties getProperties() {
return properties;
}
}
@@ -275,7 +275,7 @@ public class TileLoader {
return false;
}
protected boolean registerOneIcon(TextureMap textureMap, String mapName, Map<String, TextureAtlasSprite> map) {
private boolean registerOneIcon(TextureMap textureMap, String mapName, Map<String, TextureAtlasSprite> map) {
ResourceLocation resource = tilesToRegister.iterator()
.next();
String name = resource.toString();
@@ -304,16 +304,6 @@ public class TileLoader {
return false;
}
}
TextureAtlasSprite icon = registerIconToMap(textureMap, resource, name);
map.put(name, icon);
iconMap.put(name, icon);
String extra = (width == height ? "" : ", " + (height / width) + " frames");
subLogger.finer("%s -> %s icon %dx%d%s", name, mapName, width, width, extra);
tilesToRegister.remove(resource);
return true;
}
protected TextureAtlasSprite registerIconToMap(TextureMap textureMap, ResourceLocation resource, String name) {
TextureAtlasSprite icon;
if(generatedTiles.contains(resource)){
icon = new GeneratedCTMAtlasSprite(this, textureMap.anisotropicFiltering > 1, name);
@@ -321,7 +311,12 @@ public class TileLoader {
}else{
icon = (TextureAtlasSprite)textureMap.registerIcon(name);
}
return icon;
map.put(name, icon);
iconMap.put(name, icon);
String extra = (width == height ? "" : ", " + (height / width) + " frames");
subLogger.finer("%s -> %s icon %dx%d%s", name, mapName, width, width, extra);
tilesToRegister.remove(resource);
return true;
}
public void finish() {
@@ -344,8 +339,4 @@ public class TileLoader {
public IIcon getIcon(ResourceLocation resource) {
return resource == null ? null : getIcon(resource.toString());
}
public boolean ignoreMissingTextures() {
return false;
}
}
+1 -1
View File
@@ -176,7 +176,7 @@ public enum Settings {
},
VOID_FOG(new NotFineOptionTickBox(false, OptionImpact.LOW)),
ZOOM_SMOOTH(new NotFineOptionTickBox(true, OptionImpact.LOW)),
ZOOM_SMOOTH_SPEED(new NotFineOptionSlider(20, 1, 30, 1, OptionImpact.LOW));
ZOOM_SMOOTH_SPEED(new NotFineOptionSlider(14, 1, 30, 1, OptionImpact.LOW));
public final NotFineOption<?> option;
@@ -2,12 +2,6 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.fontrenderer;
import com.gtnewhorizon.gtnhlib.util.font.IFontParameters;
import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer;
import com.gtnewhorizons.angelica.client.font.FontProviderUnicode;
import com.gtnewhorizons.angelica.client.font.FontStrategist;
import com.gtnewhorizons.angelica.compat.etfuturum.EtFuturumFontCompat;
import net.minecraft.client.resources.IResourceManager;
import java.io.IOException;
import java.io.InputStream;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.FORMATTING_CHAR;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.GRADIENT_LENGTH;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.SECTION_X_LENGTH;
@@ -133,17 +127,6 @@ public abstract class MixinFontRenderer implements FontRendererAccessor, IFontPa
}
}
@Inject(method = "onResourceManagerReload", at = @At("TAIL"))
private void angelica$reloadModernFont(IResourceManager manager, CallbackInfo ci) {
// FML's SplashFontRenderer calls onResourceManagerReload(null) on the splash thread
if (manager == null) return;
FontStrategist.reloadFontResources();
try (InputStream in = manager.getResource(new ResourceLocation("font/glyph_sizes.bin")).getInputStream()) {
FontProviderUnicode.readWidths(in, this.glyphWidth);
} catch (IOException ignored) {
}
}
@Unique
private static boolean angelica$charInRange(char what, char fromInclusive, char toInclusive) {
return (what >= fromInclusive) && (what <= toInclusive);
@@ -328,115 +311,15 @@ public abstract class MixinFontRenderer implements FontRendererAccessor, IFontPa
}
}
if (styles.isEmpty() && effects.isEmpty()) return lastColor;
if (styles.length() == 0 && effects.length() == 0) return lastColor;
final StringBuilder result = EXTRACT_RESULT; result.setLength(0);
result.append(lastColor).append(styles).append(effects);
return result.toString();
}
@Inject(method = "getStringWidth", at = @At("HEAD"), cancellable = true)
private void angelica$batchedStringWidth(String text, CallbackInfoReturnable<Integer> cir) {
cir.setReturnValue(angelica$getBatcher().getStringWidthBatched(text));
}
@Unique
private static boolean angelica$isFormatColor(char c) {
return angelica$charInRange(c, '0', '9') || angelica$charInRange(c, 'a', 'f') || angelica$charInRange(c, 'A', 'F');
}
@Unique
private boolean angelica$doesNotNeedsSurrogateWidth(String str) {
if (str == null || !EtFuturumFontCompat.MODERN_FONT_ENABLED || this.unicodeFlag) return true;
final int len = str.length();
for (int i = 0; i + 1 < len; i++) {
if (Character.isHighSurrogate(str.charAt(i)) && Character.isLowSurrogate(str.charAt(i + 1))) {
return false;
}
}
return true;
}
@Inject(method = "sizeStringToWidth", at = @At("HEAD"), cancellable = true)
private void angelica$surrogateAwareSize(String str, int wrapWidth, CallbackInfoReturnable<Integer> cir) {
if (angelica$doesNotNeedsSurrogateWidth(str)) return;
final BatchingFontRenderer batcher = angelica$getBatcher();
final int len = str.length();
int width = 0;
int lastSpace = -1;
boolean bold = false;
int idx = 0;
for (; idx < len; idx++) {
final char c0 = str.charAt(idx);
if (c0 == '\n') {
lastSpace = idx;
break;
} else if (c0 == FORMATTING_CHAR) {
if (idx < len - 1) {
final char code = str.charAt(idx + 1);
idx++;
if (code == 'l' || code == 'L') bold = true;
else if (code == 'r' || code == 'R' || angelica$isFormatColor(code)) bold = false;
}
continue;
} else {
if (c0 == ' ') lastSpace = idx;
if (EtFuturumFontCompat.MODERN_FONT_ENABLED && !this.unicodeFlag && Character.isHighSurrogate(c0)
&& idx + 1 < len && Character.isLowSurrogate(str.charAt(idx + 1))) {
final int sup = batcher.supplementaryAdvance(Character.toCodePoint(c0, str.charAt(idx + 1)));
if (sup >= 0) {
width += sup;
if (bold) width++;
if (width > wrapWidth) break;
idx++;
continue;
}
}
width += (int) batcher.getCharWidthFine(c0);
if (bold) width++;
}
if (width > wrapWidth) break;
}
cir.setReturnValue(idx != len && lastSpace != -1 && lastSpace < idx ? lastSpace : idx);
}
@Inject(method = "trimStringToWidth(Ljava/lang/String;IZ)Ljava/lang/String;", at = @At("HEAD"), cancellable = true)
private void angelica$surrogateAwareTrim(String str, int width, boolean reverse, CallbackInfoReturnable<String> cir) {
if (reverse || angelica$doesNotNeedsSurrogateWidth(str)) return;
final BatchingFontRenderer batcher = angelica$getBatcher();
final StringBuilder sb = new StringBuilder();
final int len = str.length();
int accum = 0;
boolean prevFormat = false;
boolean bold = false;
for (int i = 0; i < len && accum < width; i++) {
final char c0 = str.charAt(i);
if (prevFormat) {
// Vanilla trim only toggles bold on §l / §r here; color codes do not reset it
prevFormat = false;
if (c0 == 'l' || c0 == 'L') bold = true;
else if (c0 == 'r' || c0 == 'R') bold = false;
} else if (c0 == FORMATTING_CHAR) {
prevFormat = true;
} else {
boolean pair = false;
int adv;
if (EtFuturumFontCompat.MODERN_FONT_ENABLED && !this.unicodeFlag && Character.isHighSurrogate(c0)
&& i + 1 < len && Character.isLowSurrogate(str.charAt(i + 1))) {
final int sup = batcher.supplementaryAdvance(Character.toCodePoint(c0, str.charAt(i + 1)));
if (sup >= 0) { adv = sup; pair = true; } else adv = (int) batcher.getCharWidthFine(c0);
} else {
adv = (int) batcher.getCharWidthFine(c0);
}
accum += adv;
if (bold) accum++;
if (accum > width) break;
sb.append(c0);
if (pair) { sb.append(str.charAt(i + 1)); i++; }
continue;
}
sb.append(c0);
}
cir.setReturnValue(sb.toString());
@ModifyVariable(method = "getStringWidth", at = @At("HEAD"), argsOnly = true, ordinal = 0)
private String angelica$convertBeforeWidth(String str) {
return ColorCodeUtils.convertAmpersandToSectionX(str);
}
@ModifyVariable(method = "listFormattedStringToWidth", at = @At("HEAD"), argsOnly = true, ordinal = 0)
@@ -0,0 +1,53 @@
package com.gtnewhorizons.angelica.mixins.early.angelica.textures;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import com.gtnewhorizons.angelica.textures.FastTextureStitcher;
import net.minecraft.client.renderer.texture.Stitcher;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
@Mixin(Stitcher.class)
public abstract class MixinStitcher {
@Shadow @Final private Set setStitchHolders;
@Shadow @Final private int maxWidth;
@Shadow @Final private int maxHeight;
@Shadow @Final private boolean forcePowerOf2;
@Shadow private int currentWidth;
@Shadow private int currentHeight;
@Unique private List<TextureAtlasSprite> angelica$stitchedSprites = Collections.emptyList();
/**
* @author Angelica
* @reason Use a skyline packer instead of vanilla recursive slots.
*/
@Overwrite
public void doStitch() {
Stitcher.Holder[] holders = (Stitcher.Holder[]) this.setStitchHolders.toArray(new Stitcher.Holder[this.setStitchHolders.size()]);
Arrays.sort(holders);
FastTextureStitcher.Result result = FastTextureStitcher.stitch(holders, this.maxWidth, this.maxHeight, this.forcePowerOf2);
this.currentWidth = result.width;
this.currentHeight = result.height;
this.angelica$stitchedSprites = result.sprites;
}
/**
* @author Angelica
* @reason FastTextureStitcher initializes sprites directly.
*/
@Overwrite
public List getStichSlots() {
return new ArrayList(this.angelica$stitchedSprites);
}
}
@@ -1,14 +0,0 @@
package com.gtnewhorizons.angelica.mixins.early.rendering;
import net.minecraft.block.BlockLiquid;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
@Mixin(BlockLiquid.class)
public interface BlockLiquidFlowInvoker {
@Invoker("getFlowVector")
Vec3 angelica$getFlowVector(IBlockAccess world, int x, int y, int z);
}
@@ -1,22 +0,0 @@
package com.gtnewhorizons.angelica.mixins.early.rendering;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLiquid;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(BlockLiquid.class)
public class MixinBlockLiquid {
@Redirect(
method = "getFlowDirection",
at = @At(value = "INVOKE", target = "Lnet/minecraft/block/BlockLiquid;getFlowVector(Lnet/minecraft/world/IBlockAccess;III)Lnet/minecraft/util/Vec3;"))
private static Vec3 angelica$flowVectorOfActualBlock(BlockLiquid singleton, IBlockAccess world, int x, int y, int z) {
final Block block = world.getBlock(x, y, z);
final BlockLiquid liquid = block instanceof BlockLiquid ? (BlockLiquid) block : singleton;
return ((BlockLiquidFlowInvoker) liquid).angelica$getFlowVector(world, x, y, z);
}
}
@@ -1,22 +0,0 @@
package com.gtnewhorizons.angelica.mixins.late.client.farseek;
import com.gtnewhorizons.angelica.rendering.celeritas.world.WorldSlice;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.WorldProvider;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Pseudo
@Mixin(targets = "farseek.world.package$IBlockAccessValue$", remap = false)
public class MixinFarseekIBlockAccessValue {
@Inject(method = "worldProvider$extension", at = @At("HEAD"), cancellable = true, remap = false)
private void angelica$worldSliceProvider(IBlockAccess bac, CallbackInfoReturnable<WorldProvider> cir) {
if (bac instanceof WorldSlice slice) {
cir.setReturnValue(slice.getWorld().provider);
}
}
}
@@ -0,0 +1,58 @@
package com.gtnewhorizons.angelica.textures;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import net.minecraft.client.renderer.texture.Stitcher;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import org.junit.jupiter.api.Test;
class FastTextureStitcherTest {
@Test
void packsSpritesWithoutOverlap() {
Stitcher.Holder[] holders = {
holder("a", 32, 16),
holder("b", 16, 32),
holder("c", 16, 16),
holder("d", 8, 40),
holder("e", 24, 8)
};
Arrays.sort(holders);
FastTextureStitcher.Result result = FastTextureStitcher.stitch(holders, 128, 128, true);
assertTrue(result.width <= 128);
assertTrue(result.height <= 128);
assertEquals(holders.length, result.sprites.size());
List<Rectangle> rectangles = new ArrayList<>();
for (Stitcher.Holder holder : holders) {
TextureAtlasSprite sprite = holder.getAtlasSprite();
Rectangle rectangle = new Rectangle(sprite.getOriginX(), sprite.getOriginY(), holder.getWidth(), holder.getHeight());
assertTrue(rectangle.x >= 0);
assertTrue(rectangle.y >= 0);
assertTrue(rectangle.x + rectangle.width <= result.width);
assertTrue(rectangle.y + rectangle.height <= result.height);
for (Rectangle other : rectangles) {
assertFalse(rectangle.intersects(other), rectangle + " overlaps " + other);
}
rectangles.add(rectangle);
}
}
private static Stitcher.Holder holder(String name, int width, int height) {
TextureAtlasSprite sprite = new TextureAtlasSprite(name);
sprite.setIconWidth(width);
sprite.setIconHeight(height);
return new Stitcher.Holder(sprite, 0);
}
}