mirror of
https://github.com/xiaozhou233/OrangeX-Client.git
synced 2026-12-05 13:05:52 +08:00
Perf: Reduce font atlas memory and bake cost
- Size atlases from the requested glyph set (Latin 512-2048, CJK 1024-4096) and double on overflow instead of always using a 4096x4096 sheet - Share one atlas between logical sizes; CJK bake heights are bucketed (12-36px) so neighbouring sizes reuse the same Noto sheet - Pack Latin at 2x2 and CJK at 1x1 oversampling in two stb passes; the context-wide 2x2 setting was quadrupling CJK atlases - Budget font textures with -Dorangex.font.atlasBudgetMb (128 MB) using frame-pinned LRU eviction, plus idle release (-Dorangex.font.idleSeconds, 30s) and face cleanup - Upload 1.8.9 atlases as GL_LUMINANCE_ALPHA with premultiplied glyph blending (2 bytes per texel) and restore the previous blend function after a frame - Write 26.2 RGBA pixels straight into the NativeImage buffer instead of building a second full-size array - Move the string width cache into FontFace so it survives across frames, and hoist HUD getFont calls out of the render loops
This commit is contained in:
1 parent
524d540c1a
commit
6a045fd46f
14 files changed
+606
-198
No files matched your search
@@ -5,6 +5,7 @@ import cn.xiaozhou233.orangex.OrangeX;
|
|||||||
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
|
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
|
||||||
import cn.xiaozhou233.orangex.modules.Module;
|
import cn.xiaozhou233.orangex.modules.Module;
|
||||||
import cn.xiaozhou233.orangex.modules.ModuleCategory;
|
import cn.xiaozhou233.orangex.modules.ModuleCategory;
|
||||||
|
import cn.xiaozhou233.orangex.render.api.FontRenderer;
|
||||||
import org.greenrobot.eventbus.Subscribe;
|
import org.greenrobot.eventbus.Subscribe;
|
||||||
|
|
||||||
import java.awt.Color;
|
import java.awt.Color;
|
||||||
@@ -42,6 +43,7 @@ public class HUD extends Module {
|
|||||||
|
|
||||||
private void renderLogo(EventRender2D event, long currentTime) {
|
private void renderLogo(EventRender2D event, long currentTime) {
|
||||||
String title = "OrangeX";
|
String title = "OrangeX";
|
||||||
|
FontRenderer font = event.getRender2D().getFont(LOGO_FONT_SIZE);
|
||||||
|
|
||||||
int x = LOGO_START_X;
|
int x = LOGO_START_X;
|
||||||
int y = LOGO_START_Y;
|
int y = LOGO_START_Y;
|
||||||
@@ -49,31 +51,21 @@ public class HUD extends Module {
|
|||||||
for (int i = 0; i < title.length(); i++) {
|
for (int i = 0; i < title.length(); i++) {
|
||||||
String character = String.valueOf(title.charAt(i));
|
String character = String.valueOf(title.charAt(i));
|
||||||
|
|
||||||
event.getRender2D()
|
font.drawString(character, x, y, getRainbowColor(currentTime, i));
|
||||||
.getFont(LOGO_FONT_SIZE)
|
|
||||||
.drawString(
|
|
||||||
character,
|
|
||||||
x,
|
|
||||||
y,
|
|
||||||
getRainbowColor(currentTime, i)
|
|
||||||
);
|
|
||||||
|
|
||||||
x += (int) event.getRender2D()
|
x += (int) font.getStringWidth(character);
|
||||||
.getFont(LOGO_FONT_SIZE)
|
|
||||||
.getStringWidth(character);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void renderModuleList(EventRender2D event, long currentTime) {
|
private void renderModuleList(EventRender2D event, long currentTime) {
|
||||||
|
FontRenderer font = event.getRender2D().getFont(MODULE_FONT_SIZE);
|
||||||
List<Module> modules = OrangeX.getInstance()
|
List<Module> modules = OrangeX.getInstance()
|
||||||
.getModuleManager()
|
.getModuleManager()
|
||||||
.getAllModules()
|
.getAllModules()
|
||||||
.stream()
|
.stream()
|
||||||
.filter(Module::isEnabled)
|
.filter(Module::isEnabled)
|
||||||
.sorted(Comparator.comparingDouble(
|
.sorted(Comparator.comparingDouble(
|
||||||
module -> -event.getRender2D()
|
module -> -font.getStringWidth(module.getName())
|
||||||
.getFont(MODULE_FONT_SIZE)
|
|
||||||
.getStringWidth(module.getName())
|
|
||||||
))
|
))
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
@@ -84,26 +76,12 @@ public class HUD extends Module {
|
|||||||
Module module = modules.get(i);
|
Module module = modules.get(i);
|
||||||
String name = module.getName();
|
String name = module.getName();
|
||||||
|
|
||||||
int textWidth = (int) event.getRender2D()
|
int textWidth = (int) font.getStringWidth(name);
|
||||||
.getFont(MODULE_FONT_SIZE)
|
|
||||||
.getStringWidth(name);
|
|
||||||
|
|
||||||
int x = screenWidth - textWidth - MODULE_MARGIN;
|
int x = screenWidth - textWidth - MODULE_MARGIN;
|
||||||
|
|
||||||
event.getRender2D()
|
font.drawStringWithShadow(name, x, y, getRainbowColor(currentTime, i));
|
||||||
.getFont(MODULE_FONT_SIZE)
|
|
||||||
.drawStringWithShadow(
|
|
||||||
name,
|
|
||||||
x,
|
|
||||||
y,
|
|
||||||
getRainbowColor(currentTime, i)
|
|
||||||
);
|
|
||||||
|
|
||||||
y += (int) (
|
y += (int) (font.getStringHeight() + MODULE_SPACING);
|
||||||
event.getRender2D()
|
|
||||||
.getFont(MODULE_FONT_SIZE)
|
|
||||||
.getStringHeight() + MODULE_SPACING
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -54,6 +54,10 @@ public final class Render2DManager {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Pin atlases used by this frame and release long-idle ones (e.g. the
|
||||||
|
// previous GUI scale's faces) before they are needed again.
|
||||||
|
fonts.beginFrame();
|
||||||
|
|
||||||
Render2D context = backend.createRender2D(fonts, platformContext);
|
Render2D context = backend.createRender2D(fonts, platformContext);
|
||||||
try {
|
try {
|
||||||
eventBus.post(new EventRender2D(context, inWorld));
|
eventBus.post(new EventRender2D(context, inWorld));
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package cn.xiaozhou233.orangex.render.font;
|
||||||
|
|
||||||
|
import cn.xiaozhou233.orangex.render.internal.FontTexture;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One baked atlas and its GPU texture, shared by every {@link FontFace} that
|
||||||
|
* was baked at the same height and resource.
|
||||||
|
*
|
||||||
|
* <p>Logical sizes do not own atlases: {@link FontFace#getDrawScale()} maps
|
||||||
|
* atlas pixels back to GUI pixels, so many sizes reuse a single texture.</p>
|
||||||
|
*/
|
||||||
|
final class FontAtlasEntry {
|
||||||
|
|
||||||
|
final String resource;
|
||||||
|
final int bakeHeight;
|
||||||
|
final FontAtlas atlas;
|
||||||
|
final FontTexture texture;
|
||||||
|
final int texels;
|
||||||
|
long lastUsedNanos;
|
||||||
|
|
||||||
|
FontAtlasEntry(String resource, int bakeHeight, FontAtlas atlas,
|
||||||
|
FontTexture texture, long lastUsedNanos) {
|
||||||
|
this.resource = resource;
|
||||||
|
this.bakeHeight = bakeHeight;
|
||||||
|
this.atlas = atlas;
|
||||||
|
this.texture = texture;
|
||||||
|
this.texels = atlas.getWidth() * atlas.getHeight();
|
||||||
|
this.lastUsedNanos = lastUsedNanos;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,25 +2,34 @@ package cn.xiaozhou233.orangex.render.font;
|
|||||||
|
|
||||||
import cn.xiaozhou233.orangex.render.internal.FontTexture;
|
import cn.xiaozhou233.orangex.render.internal.FontTexture;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A baked atlas plus its GPU texture and the scale needed to draw it at the
|
* A font face bound to a shared {@link FontAtlasEntry} and a logical size.
|
||||||
* requested logical size.
|
*
|
||||||
|
* <p>The atlas is shared between sizes; {@link #getDrawScale()} converts atlas
|
||||||
|
* pixels back to GUI pixels. Each face owns a small width cache because widths
|
||||||
|
* also depend on the CJK fallback face that the primary face resolved.</p>
|
||||||
*/
|
*/
|
||||||
public final class FontFace {
|
public final class FontFace {
|
||||||
|
|
||||||
|
private static final int MAX_CACHED_WIDTHS = 1024;
|
||||||
|
|
||||||
private final FontFamily family;
|
private final FontFamily family;
|
||||||
private final FontAtlas atlas;
|
private final FontAtlasEntry entry;
|
||||||
private final FontTexture texture;
|
|
||||||
private final float logicalSize;
|
private final float logicalSize;
|
||||||
private final float drawScale;
|
private final float drawScale;
|
||||||
|
private final Map<String, Double> widthCache = new HashMap<String, Double>();
|
||||||
|
private long lastUsedNanos;
|
||||||
|
|
||||||
public FontFace(FontFamily family, FontAtlas atlas, FontTexture texture,
|
FontFace(FontFamily family, FontAtlasEntry entry,
|
||||||
float logicalSize, float drawScale) {
|
float logicalSize, float drawScale, long lastUsedNanos) {
|
||||||
this.family = family;
|
this.family = family;
|
||||||
this.atlas = atlas;
|
this.entry = entry;
|
||||||
this.texture = texture;
|
|
||||||
this.logicalSize = logicalSize;
|
this.logicalSize = logicalSize;
|
||||||
this.drawScale = drawScale;
|
this.drawScale = drawScale;
|
||||||
|
this.lastUsedNanos = lastUsedNanos;
|
||||||
}
|
}
|
||||||
|
|
||||||
public FontFamily getFamily() {
|
public FontFamily getFamily() {
|
||||||
@@ -28,11 +37,11 @@ public final class FontFace {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public FontAtlas getAtlas() {
|
public FontAtlas getAtlas() {
|
||||||
return atlas;
|
return entry.atlas;
|
||||||
}
|
}
|
||||||
|
|
||||||
public FontTexture getTexture() {
|
public FontTexture getTexture() {
|
||||||
return texture;
|
return entry.texture;
|
||||||
}
|
}
|
||||||
|
|
||||||
public float getLogicalSize() {
|
public float getLogicalSize() {
|
||||||
@@ -44,18 +53,45 @@ public final class FontFace {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Glyph getGlyph(int codePoint) {
|
public Glyph getGlyph(int codePoint) {
|
||||||
return atlas.getGlyph(codePoint);
|
return entry.atlas.getGlyph(codePoint);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Glyph getFallbackGlyph() {
|
public Glyph getFallbackGlyph() {
|
||||||
return atlas.getFallbackGlyph();
|
return entry.atlas.getFallbackGlyph();
|
||||||
}
|
}
|
||||||
|
|
||||||
public float getAscent() {
|
public float getAscent() {
|
||||||
return atlas.getAscent();
|
return entry.atlas.getAscent();
|
||||||
}
|
}
|
||||||
|
|
||||||
public float getLineHeight() {
|
public float getLineHeight() {
|
||||||
return atlas.getLineHeight();
|
return entry.atlas.getLineHeight();
|
||||||
|
}
|
||||||
|
|
||||||
|
FontAtlasEntry getEntry() {
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
long getLastUsedNanos() {
|
||||||
|
return lastUsedNanos;
|
||||||
|
}
|
||||||
|
|
||||||
|
void touch(long now) {
|
||||||
|
lastUsedNanos = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared across frames and renderers: {@code getStringWidth} is normally
|
||||||
|
* called every frame for static text.
|
||||||
|
*/
|
||||||
|
Double getCachedWidth(String text) {
|
||||||
|
return widthCache.get(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
void cacheWidth(String text, double width) {
|
||||||
|
if (widthCache.size() >= MAX_CACHED_WIDTHS) {
|
||||||
|
widthCache.clear();
|
||||||
|
}
|
||||||
|
widthCache.put(text, width);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,31 +7,73 @@ import java.io.ByteArrayOutputStream;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.Iterator;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates and caches {@link FontFace} instances.
|
* Creates and caches {@link FontFace} instances.
|
||||||
*
|
*
|
||||||
* <p>One face exists per (family, bold, logical size, GUI scale) tuple. The
|
* <p>Atlases are cached per (font resource, bake height) and shared between
|
||||||
* atlas is rasterised at {@code size * guiScale} pixels so text stays crisp on
|
* logical sizes; a face is a lightweight view adding the draw scale. The
|
||||||
* high GUI scales, while {@link FontFace#getDrawScale()} converts atlas pixels
|
* atlas is rasterised at {@code size * guiScale} pixels (rounded up to the
|
||||||
* back to GUI pixels.</p>
|
* family's bake-height bucket) so text stays crisp on high GUI scales, while
|
||||||
|
* {@link FontFace#getDrawScale()} converts atlas pixels back to GUI
|
||||||
|
* pixels.</p>
|
||||||
|
*
|
||||||
|
* <p>Textures are bounded by an idle timeout and a byte budget; least recently
|
||||||
|
* used atlases are closed when either is exceeded, so changing GUI scale or
|
||||||
|
* using many sizes no longer leaks VRAM. Frames should call
|
||||||
|
* {@link #beginFrame()} so atlases used by the current frame are pinned.</p>
|
||||||
*/
|
*/
|
||||||
public final class FontManager {
|
public final class FontManager {
|
||||||
|
|
||||||
private static final int MAX_RASTER_HEIGHT = 64;
|
private static final int MAX_RASTER_HEIGHT = 64;
|
||||||
private static final int MAX_CJK_RASTER_HEIGHT = 36;
|
private static final int MAX_CJK_RASTER_HEIGHT = 36;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Quantised bake heights for CJK faces. A full Noto atlas is large, so
|
||||||
|
* neighbouring sizes share a bucket instead of each baking their own sheet.
|
||||||
|
*/
|
||||||
|
private static final int[] CJK_BAKE_HEIGHTS =
|
||||||
|
new int[]{12, 16, 20, 24, 28, 32, 36};
|
||||||
|
|
||||||
|
private static final long TRIM_INTERVAL_NANOS = 2_000_000_000L;
|
||||||
|
private static final long DEFAULT_ATLAS_BUDGET_MB = 128L;
|
||||||
|
private static final int DEFAULT_IDLE_SECONDS = 30;
|
||||||
|
|
||||||
private static final FontFamily FALLBACK_FAMILY = FontFamily.PROXIMA;
|
private static final FontFamily FALLBACK_FAMILY = FontFamily.PROXIMA;
|
||||||
|
|
||||||
private final FontBackend backend;
|
private final FontBackend backend;
|
||||||
private final Map<Key, FontFace> faces = new HashMap<Key, FontFace>();
|
private final Map<AtlasKey, FontAtlasEntry> atlases =
|
||||||
|
new HashMap<AtlasKey, FontAtlasEntry>();
|
||||||
|
private final Map<FaceKey, FontFace> faces = new HashMap<FaceKey, FontFace>();
|
||||||
private final Map<String, byte[]> fontData = new HashMap<String, byte[]>();
|
private final Map<String, byte[]> fontData = new HashMap<String, byte[]>();
|
||||||
|
|
||||||
|
private final boolean fullGbk;
|
||||||
|
private final boolean debugCache;
|
||||||
|
private final int bytesPerTexel;
|
||||||
|
private final long atlasBudgetBytes;
|
||||||
|
private final long idleNanos;
|
||||||
|
|
||||||
private FontFamily defaultFamily;
|
private FontFamily defaultFamily;
|
||||||
|
private long frameStartNanos;
|
||||||
|
private long lastTrimNanos;
|
||||||
|
|
||||||
public FontManager(FontBackend backend) {
|
public FontManager(FontBackend backend) {
|
||||||
this.backend = backend;
|
this.backend = backend;
|
||||||
this.defaultFamily = resolveDefaultFamily();
|
this.defaultFamily = resolveDefaultFamily();
|
||||||
|
this.fullGbk = !"false".equalsIgnoreCase(
|
||||||
|
System.getProperty("orangex.font.fullGbk", "true"));
|
||||||
|
this.debugCache = Boolean.getBoolean("orangex.font.debugCache");
|
||||||
|
this.bytesPerTexel = Math.max(1, backend.getBytesPerTexel());
|
||||||
|
this.atlasBudgetBytes = Math.max(8L,
|
||||||
|
Long.getLong("orangex.font.atlasBudgetMb", DEFAULT_ATLAS_BUDGET_MB))
|
||||||
|
* 1024L * 1024L;
|
||||||
|
this.idleNanos = Math.max(1,
|
||||||
|
Integer.getInteger("orangex.font.idleSeconds", DEFAULT_IDLE_SECONDS))
|
||||||
|
* 1_000_000_000L;
|
||||||
|
this.frameStartNanos = System.nanoTime();
|
||||||
|
this.lastTrimNanos = this.frameStartNanos;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static FontFamily resolveDefaultFamily() {
|
private static FontFamily resolveDefaultFamily() {
|
||||||
@@ -65,6 +107,20 @@ public final class FontManager {
|
|||||||
this.defaultFamily = defaultFamily != null ? defaultFamily : FALLBACK_FAMILY;
|
this.defaultFamily = defaultFamily != null ? defaultFamily : FALLBACK_FAMILY;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Marks the start of a rendered frame. Atlases touched after this call are
|
||||||
|
* pinned against budget eviction until the next frame; idle atlases from
|
||||||
|
* earlier frames (for example after a GUI scale change) are released.
|
||||||
|
*/
|
||||||
|
public synchronized void beginFrame() {
|
||||||
|
long now = System.nanoTime();
|
||||||
|
this.frameStartNanos = now;
|
||||||
|
if (now - lastTrimNanos >= TRIM_INTERVAL_NANOS) {
|
||||||
|
lastTrimNanos = now;
|
||||||
|
evictIdle(now);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public synchronized FontFace getFace(FontFamily family, float logicalSize,
|
public synchronized FontFace getFace(FontFamily family, float logicalSize,
|
||||||
boolean bold, double guiScale) {
|
boolean bold, double guiScale) {
|
||||||
if (family == null) {
|
if (family == null) {
|
||||||
@@ -83,27 +139,137 @@ public final class FontManager {
|
|||||||
} else if (rasterHeight > maxRasterHeight) {
|
} else if (rasterHeight > maxRasterHeight) {
|
||||||
rasterHeight = maxRasterHeight;
|
rasterHeight = maxRasterHeight;
|
||||||
}
|
}
|
||||||
|
int bakeHeight = bakeHeight(family, rasterHeight);
|
||||||
|
|
||||||
Key key = new Key(family, bold, rasterHeight, logicalSize);
|
long now = System.nanoTime();
|
||||||
FontFace cached = faces.get(key);
|
String resource = family.getResource(bold);
|
||||||
if (cached != null) {
|
AtlasKey atlasKey = new AtlasKey(resource, bakeHeight, family.isCjkCapable());
|
||||||
return cached;
|
FontAtlasEntry entry = atlases.get(atlasKey);
|
||||||
|
if (entry == null) {
|
||||||
|
entry = bake(atlasKey, now);
|
||||||
|
atlases.put(atlasKey, entry);
|
||||||
|
enforceBudget();
|
||||||
}
|
}
|
||||||
|
entry.lastUsedNanos = now;
|
||||||
|
|
||||||
byte[] data = loadFont(family.getResource(bold));
|
FaceKey faceKey = new FaceKey(atlasKey, logicalSize);
|
||||||
|
FontFace face = faces.get(faceKey);
|
||||||
|
if (face == null) {
|
||||||
|
float drawScale = logicalSize / (float) bakeHeight;
|
||||||
|
face = new FontFace(family, entry, logicalSize, drawScale, now);
|
||||||
|
faces.put(faceKey, face);
|
||||||
|
} else {
|
||||||
|
face.touch(now);
|
||||||
|
}
|
||||||
|
return face;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int bakeHeight(FontFamily family, int rasterHeight) {
|
||||||
|
if (!family.isCjkCapable()) {
|
||||||
|
return rasterHeight;
|
||||||
|
}
|
||||||
|
for (int height : CJK_BAKE_HEIGHTS) {
|
||||||
|
if (rasterHeight <= height) {
|
||||||
|
return height;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return CJK_BAKE_HEIGHTS[CJK_BAKE_HEIGHTS.length - 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
private FontAtlasEntry bake(AtlasKey key, long now) {
|
||||||
|
byte[] data = loadFont(key.resource);
|
||||||
FontAtlas atlas = StbFontBaker.bake(
|
FontAtlas atlas = StbFontBaker.bake(
|
||||||
data,
|
data, key.bakeHeight, key.cjk, fullGbk);
|
||||||
rasterHeight,
|
|
||||||
family.isCjkCapable(),
|
|
||||||
!"false".equalsIgnoreCase(
|
|
||||||
System.getProperty("orangex.font.fullGbk", "true"))
|
|
||||||
);
|
|
||||||
FontTexture texture = backend.createTexture(atlas);
|
FontTexture texture = backend.createTexture(atlas);
|
||||||
atlas.releasePixels();
|
atlas.releasePixels();
|
||||||
float drawScale = logicalSize / (float) rasterHeight;
|
FontAtlasEntry entry = new FontAtlasEntry(
|
||||||
FontFace face = new FontFace(family, atlas, texture, logicalSize, drawScale);
|
key.resource, key.bakeHeight, atlas, texture, now);
|
||||||
faces.put(key, face);
|
if (debugCache) {
|
||||||
return face;
|
System.out.println("[OrangeX] Baked " + key.resource
|
||||||
|
+ " @" + key.bakeHeight + "px -> "
|
||||||
|
+ atlas.getWidth() + "x" + atlas.getHeight()
|
||||||
|
+ " (" + (entry.texels * (long) bytesPerTexel / (1024 * 1024))
|
||||||
|
+ " MB)");
|
||||||
|
}
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drops atlases and faces that have not been used for {@code idleSeconds}
|
||||||
|
* (for example the previous GUI scale's faces).
|
||||||
|
*/
|
||||||
|
private void evictIdle(long now) {
|
||||||
|
Iterator<Map.Entry<AtlasKey, FontAtlasEntry>> iterator =
|
||||||
|
atlases.entrySet().iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
Map.Entry<AtlasKey, FontAtlasEntry> next = iterator.next();
|
||||||
|
if (now - next.getValue().lastUsedNanos < idleNanos) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
iterator.remove();
|
||||||
|
close(next.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
Iterator<Map.Entry<FaceKey, FontFace>> facesIterator =
|
||||||
|
faces.entrySet().iterator();
|
||||||
|
while (facesIterator.hasNext()) {
|
||||||
|
if (now - facesIterator.next().getValue().getLastUsedNanos()
|
||||||
|
>= idleNanos) {
|
||||||
|
facesIterator.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evicts least recently used atlases until the texture budget is met.
|
||||||
|
* Atlases already used in the current frame are pinned, so a working set
|
||||||
|
* larger than the budget never causes per-frame re-baking.
|
||||||
|
*/
|
||||||
|
private void enforceBudget() {
|
||||||
|
long totalBytes = totalBytes();
|
||||||
|
while (totalBytes > atlasBudgetBytes) {
|
||||||
|
AtlasKey victimKey = null;
|
||||||
|
FontAtlasEntry victim = null;
|
||||||
|
for (Map.Entry<AtlasKey, FontAtlasEntry> candidate : atlases.entrySet()) {
|
||||||
|
FontAtlasEntry entry = candidate.getValue();
|
||||||
|
if (entry.lastUsedNanos >= frameStartNanos) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (victim == null || entry.lastUsedNanos < victim.lastUsedNanos) {
|
||||||
|
victim = entry;
|
||||||
|
victimKey = candidate.getKey();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (victim == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
atlases.remove(victimKey);
|
||||||
|
totalBytes -= (long) victim.texels * bytesPerTexel;
|
||||||
|
close(victim);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private long totalBytes() {
|
||||||
|
long total = 0L;
|
||||||
|
for (FontAtlasEntry entry : atlases.values()) {
|
||||||
|
total += (long) entry.texels * bytesPerTexel;
|
||||||
|
}
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void close(FontAtlasEntry entry) {
|
||||||
|
entry.texture.close();
|
||||||
|
Iterator<Map.Entry<FaceKey, FontFace>> iterator =
|
||||||
|
faces.entrySet().iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
if (iterator.next().getValue().getEntry() == entry) {
|
||||||
|
iterator.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (debugCache) {
|
||||||
|
System.out.println("[OrangeX] Released " + entry.resource
|
||||||
|
+ " @" + entry.bakeHeight + "px");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private byte[] loadFont(String resource) {
|
private byte[] loadFont(String resource) {
|
||||||
@@ -143,24 +309,54 @@ public final class FontManager {
|
|||||||
return backend.getName();
|
return backend.getName();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void clear() {
|
public synchronized void clear() {
|
||||||
for (FontFace face : faces.values()) {
|
for (FontAtlasEntry entry : atlases.values()) {
|
||||||
face.getTexture().close();
|
entry.texture.close();
|
||||||
}
|
}
|
||||||
|
atlases.clear();
|
||||||
faces.clear();
|
faces.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final class Key {
|
private static final class AtlasKey {
|
||||||
private final FontFamily family;
|
private final String resource;
|
||||||
private final boolean bold;
|
private final int bakeHeight;
|
||||||
private final int rasterHeight;
|
private final boolean cjk;
|
||||||
|
|
||||||
|
private AtlasKey(String resource, int bakeHeight, boolean cjk) {
|
||||||
|
this.resource = resource;
|
||||||
|
this.bakeHeight = bakeHeight;
|
||||||
|
this.cjk = cjk;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object other) {
|
||||||
|
if (this == other) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!(other instanceof AtlasKey)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
AtlasKey key = (AtlasKey) other;
|
||||||
|
return bakeHeight == key.bakeHeight
|
||||||
|
&& cjk == key.cjk
|
||||||
|
&& resource.equals(key.resource);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
int result = resource.hashCode();
|
||||||
|
result = 31 * result + bakeHeight;
|
||||||
|
result = 31 * result + (cjk ? 1 : 0);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class FaceKey {
|
||||||
|
private final AtlasKey atlasKey;
|
||||||
private final float logicalSize;
|
private final float logicalSize;
|
||||||
|
|
||||||
private Key(FontFamily family, boolean bold, int rasterHeight,
|
private FaceKey(AtlasKey atlasKey, float logicalSize) {
|
||||||
float logicalSize) {
|
this.atlasKey = atlasKey;
|
||||||
this.family = family;
|
|
||||||
this.bold = bold;
|
|
||||||
this.rasterHeight = rasterHeight;
|
|
||||||
this.logicalSize = logicalSize;
|
this.logicalSize = logicalSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,23 +365,17 @@ public final class FontManager {
|
|||||||
if (this == other) {
|
if (this == other) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (!(other instanceof Key)) {
|
if (!(other instanceof FaceKey)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
Key key = (Key) other;
|
FaceKey key = (FaceKey) other;
|
||||||
return bold == key.bold
|
return Float.compare(logicalSize, key.logicalSize) == 0
|
||||||
&& rasterHeight == key.rasterHeight
|
&& atlasKey.equals(key.atlasKey);
|
||||||
&& Float.compare(logicalSize, key.logicalSize) == 0
|
|
||||||
&& family == key.family;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
int result = family.hashCode();
|
return 31 * atlasKey.hashCode() + Float.floatToIntBits(logicalSize);
|
||||||
result = 31 * result + (bold ? 1 : 0);
|
|
||||||
result = 31 * result + rasterHeight;
|
|
||||||
result = 31 * result + Float.floatToIntBits(logicalSize);
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -20,13 +20,33 @@ import java.util.Set;
|
|||||||
* one fixed 4096x4096 sheet; here the character set is split into a Latin range
|
* one fixed 4096x4096 sheet; here the character set is split into a Latin range
|
||||||
* and an optional CJK range so oversampling/atlas pressure can be controlled
|
* and an optional CJK range so oversampling/atlas pressure can be controlled
|
||||||
* separately.</p>
|
* separately.</p>
|
||||||
|
*
|
||||||
|
* <p>Atlas size is chosen automatically from the requested glyph set (a fixed
|
||||||
|
* 4096x4096 sheet wastes 4x-16x the memory for Latin-only faces). The grown
|
||||||
|
* sizes are retried on overflow, so the estimate only affects bake time, never
|
||||||
|
* correctness. {@code -Dorangex.font.atlasSize=<n>} pins an exact size for
|
||||||
|
* compatibility with the old behaviour.</p>
|
||||||
*/
|
*/
|
||||||
public final class StbFontBaker {
|
public final class StbFontBaker {
|
||||||
|
|
||||||
private static final int DEFAULT_ATLAS_SIZE = 4096;
|
private static final int MIN_ATLAS_SIZE = 512;
|
||||||
|
private static final int MAX_ATLAS_SIZE = 8192;
|
||||||
private static final int LATIN_OVERSAMPLE = 2;
|
private static final int LATIN_OVERSAMPLE = 2;
|
||||||
private static final int CJK_OVERSAMPLE = 1;
|
private static final int CJK_OVERSAMPLE = 1;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fraction of the sheet expected to be occupied by glyph boxes. The
|
||||||
|
* per-glyph areas below are calibrated against stb's real packing output
|
||||||
|
* for the bundled fonts; overflow still doubles and retries, so the
|
||||||
|
* estimate only trades a possible extra bake against wasted VRAM.
|
||||||
|
*/
|
||||||
|
private static final double PACK_FILL = 0.92;
|
||||||
|
private static final double LATIN_AREA_FACTOR = 0.55;
|
||||||
|
private static final double CJK_AREA_FACTOR = 0.36;
|
||||||
|
|
||||||
|
/** CJK glyph sets never fit a 512 sheet in practice; skip the retry. */
|
||||||
|
private static final int MIN_CJK_ATLAS_SIZE = 1024;
|
||||||
|
|
||||||
private StbFontBaker() {
|
private StbFontBaker() {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,41 +73,67 @@ public final class StbFontBaker {
|
|||||||
float ascentPx = ascent[0] * fontScale;
|
float ascentPx = ascent[0] * fontScale;
|
||||||
float lineHeightPx = (ascent[0] - descent[0] + lineGap[0]) * fontScale;
|
float lineHeightPx = (ascent[0] - descent[0] + lineGap[0]) * fontScale;
|
||||||
|
|
||||||
int atlasSize = atlasSize();
|
int[] latin = latinCodepoints();
|
||||||
|
int[] cjk = includeCjk ? cjkCodepoints(fullGbk) : new int[0];
|
||||||
|
|
||||||
|
Integer pinned = Integer.getInteger("orangex.font.atlasSize");
|
||||||
|
int atlasSize = pinned != null
|
||||||
|
? clampAtlasSize(pinned)
|
||||||
|
: estimateAtlasSize(latin.length, cjk.length, pixelHeight);
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
Result result = bakeAt(fontData, pixelHeight, latin, cjk,
|
||||||
|
atlasSize, ascentPx, lineHeightPx);
|
||||||
|
if (!result.overflow) {
|
||||||
|
return result.atlas;
|
||||||
|
}
|
||||||
|
if (pinned != null || atlasSize >= MAX_ATLAS_SIZE) {
|
||||||
|
// Keep drawing with the glyphs that did fit rather than
|
||||||
|
// failing the whole frame.
|
||||||
|
System.out.println("[OrangeX] Font atlas overflow at "
|
||||||
|
+ atlasSize + "x" + atlasSize
|
||||||
|
+ "; some glyphs are missing. Raise "
|
||||||
|
+ "-Dorangex.font.atlasSize.");
|
||||||
|
return result.atlas;
|
||||||
|
}
|
||||||
|
atlasSize = Math.min(MAX_ATLAS_SIZE, atlasSize * 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Result bakeAt(byte[] fontData, int pixelHeight,
|
||||||
|
int[] latin, int[] cjk, int atlasSize,
|
||||||
|
float ascentPx, float lineHeightPx) {
|
||||||
byte[] pixels = new byte[atlasSize * atlasSize];
|
byte[] pixels = new byte[atlasSize * atlasSize];
|
||||||
|
|
||||||
StbTrueTypePackContext packContext = new StbTrueTypePackContext();
|
StbTrueTypePackContext packContext = new StbTrueTypePackContext();
|
||||||
if (StbRasterizer.C(packContext, pixels, atlasSize, atlasSize, 0, 1) == 0) {
|
if (StbRasterizer.C(packContext, pixels, atlasSize, atlasSize, 0, 1) == 0) {
|
||||||
throw new IllegalStateException("Unable to initialise the stb pack context");
|
throw new IllegalStateException("Unable to initialise the stb pack context");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// stb packs every range with the context-wide oversampling, so the
|
||||||
|
// ranges are packed in two passes to give Latin 2x2 and CJK 1x1 (the
|
||||||
|
// latter alone would otherwise quadruple CJK atlas memory).
|
||||||
|
StbTrueTypePackRange latinRange = createRange(
|
||||||
|
latin, pixelHeight, LATIN_OVERSAMPLE);
|
||||||
|
StbTrueTypePackRange cjkRange = cjk.length > 0
|
||||||
|
? createRange(cjk, pixelHeight, CJK_OVERSAMPLE)
|
||||||
|
: null;
|
||||||
|
|
||||||
StbRasterizer.n(packContext, LATIN_OVERSAMPLE, LATIN_OVERSAMPLE);
|
StbRasterizer.n(packContext, LATIN_OVERSAMPLE, LATIN_OVERSAMPLE);
|
||||||
|
boolean packed = StbRasterizer.c(packContext, fontData, 0,
|
||||||
int[] latin = latinCodepoints();
|
new StbTrueTypePackRange[]{latinRange}, 1) != 0;
|
||||||
StbTrueTypePackRange latinRange = createRange(latin, pixelHeight, LATIN_OVERSAMPLE);
|
|
||||||
StbTrueTypePackRange[] ranges;
|
|
||||||
|
|
||||||
int[] cjk = null;
|
|
||||||
StbTrueTypePackRange cjkRange = null;
|
|
||||||
if (includeCjk) {
|
|
||||||
cjk = cjkCodepoints(fullGbk);
|
|
||||||
if (cjk.length > 0) {
|
|
||||||
cjkRange = createRange(cjk, pixelHeight, CJK_OVERSAMPLE);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cjkRange != null) {
|
if (cjkRange != null) {
|
||||||
ranges = new StbTrueTypePackRange[]{latinRange, cjkRange};
|
StbRasterizer.n(packContext, CJK_OVERSAMPLE, CJK_OVERSAMPLE);
|
||||||
} else {
|
packed &= StbRasterizer.c(packContext, fontData, 0,
|
||||||
ranges = new StbTrueTypePackRange[]{latinRange};
|
new StbTrueTypePackRange[]{cjkRange}, 1) != 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
int packed = StbRasterizer.c(packContext, fontData, 0, ranges, ranges.length);
|
|
||||||
StbRasterizer.S(packContext);
|
StbRasterizer.S(packContext);
|
||||||
|
|
||||||
Map<Integer, Glyph> glyphs = new HashMap<Integer, Glyph>();
|
Map<Integer, Glyph> glyphs = new HashMap<Integer, Glyph>();
|
||||||
collectGlyphs(glyphs, latinRange, latin, atlasSize, packed != 0);
|
collectGlyphs(glyphs, latinRange, latin, atlasSize);
|
||||||
if (cjkRange != null) {
|
if (cjkRange != null) {
|
||||||
collectGlyphs(glyphs, cjkRange, cjk, atlasSize, packed != 0);
|
collectGlyphs(glyphs, cjkRange, cjk, atlasSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Missing glyph: '?' or space. The renderer falls back to it for
|
// Missing glyph: '?' or space. The renderer falls back to it for
|
||||||
@@ -99,43 +145,15 @@ public final class StbFontBaker {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new FontAtlas(atlasSize, atlasSize, pixels, glyphs,
|
FontAtlas atlas = new FontAtlas(atlasSize, atlasSize, pixels, glyphs,
|
||||||
ascentPx, lineHeightPx);
|
ascentPx, lineHeightPx);
|
||||||
}
|
return new Result(atlas, !packed);
|
||||||
|
|
||||||
private static int atlasSize() {
|
|
||||||
int configured = Integer.getInteger("orangex.font.atlasSize", DEFAULT_ATLAS_SIZE);
|
|
||||||
if (configured < 512) {
|
|
||||||
configured = 512;
|
|
||||||
} else if (configured > 8192) {
|
|
||||||
configured = 8192;
|
|
||||||
}
|
|
||||||
return configured;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static StbTrueTypePackRange createRange(int[] codepoints, int pixelHeight,
|
|
||||||
int oversample) {
|
|
||||||
StbTrueTypePackedChar[] packedChars = new StbTrueTypePackedChar[codepoints.length];
|
|
||||||
for (int i = 0; i < packedChars.length; i++) {
|
|
||||||
packedChars[i] = new StbTrueTypePackedChar();
|
|
||||||
}
|
|
||||||
|
|
||||||
StbTrueTypePackRange range = new StbTrueTypePackRange();
|
|
||||||
range.E = pixelHeight;
|
|
||||||
range.R = 0;
|
|
||||||
range.N = codepoints;
|
|
||||||
range.b = codepoints.length;
|
|
||||||
range.M = packedChars;
|
|
||||||
range.i = (byte) oversample;
|
|
||||||
range.y = (byte) oversample;
|
|
||||||
return range;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void collectGlyphs(Map<Integer, Glyph> out,
|
private static void collectGlyphs(Map<Integer, Glyph> out,
|
||||||
StbTrueTypePackRange range,
|
StbTrueTypePackRange range,
|
||||||
int[] codepoints,
|
int[] codepoints,
|
||||||
int atlasSize,
|
int atlasSize) {
|
||||||
boolean packedOk) {
|
|
||||||
float inverse = 1.0f / (float) atlasSize;
|
float inverse = 1.0f / (float) atlasSize;
|
||||||
for (int i = 0; i < codepoints.length; i++) {
|
for (int i = 0; i < codepoints.length; i++) {
|
||||||
StbTrueTypePackedChar packedChar = range.M[i];
|
StbTrueTypePackedChar packedChar = range.M[i];
|
||||||
@@ -155,10 +173,55 @@ public final class StbFontBaker {
|
|||||||
packedChar.A
|
packedChar.A
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if (!packedOk) {
|
}
|
||||||
System.out.println("[OrangeX] Font pack reported overflow (atlas "
|
|
||||||
+ atlasSize + "x" + atlasSize + ")");
|
private static int estimateAtlasSize(int latinCount, int cjkCount,
|
||||||
|
int pixelHeight) {
|
||||||
|
double latinCell = LATIN_OVERSAMPLE * (double) pixelHeight;
|
||||||
|
double cjkCell = CJK_OVERSAMPLE * (double) pixelHeight;
|
||||||
|
double area = latinCount * latinCell * latinCell * LATIN_AREA_FACTOR
|
||||||
|
+ cjkCount * cjkCell * cjkCell * CJK_AREA_FACTOR;
|
||||||
|
int side = (int) Math.ceil(Math.sqrt(area / PACK_FILL));
|
||||||
|
if (cjkCount > 0 && side < MIN_CJK_ATLAS_SIZE) {
|
||||||
|
side = MIN_CJK_ATLAS_SIZE;
|
||||||
}
|
}
|
||||||
|
return nextPowerOfTwo(clampAtlasSize(side));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int nextPowerOfTwo(int value) {
|
||||||
|
int result = MIN_ATLAS_SIZE;
|
||||||
|
while (result < value && result < MAX_ATLAS_SIZE) {
|
||||||
|
result <<= 1;
|
||||||
|
}
|
||||||
|
return Math.min(result, MAX_ATLAS_SIZE);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int clampAtlasSize(int size) {
|
||||||
|
if (size < MIN_ATLAS_SIZE) {
|
||||||
|
return MIN_ATLAS_SIZE;
|
||||||
|
}
|
||||||
|
if (size > MAX_ATLAS_SIZE) {
|
||||||
|
return MAX_ATLAS_SIZE;
|
||||||
|
}
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static StbTrueTypePackRange createRange(int[] codepoints, int pixelHeight,
|
||||||
|
int oversample) {
|
||||||
|
StbTrueTypePackedChar[] packedChars = new StbTrueTypePackedChar[codepoints.length];
|
||||||
|
for (int i = 0; i < packedChars.length; i++) {
|
||||||
|
packedChars[i] = new StbTrueTypePackedChar();
|
||||||
|
}
|
||||||
|
|
||||||
|
StbTrueTypePackRange range = new StbTrueTypePackRange();
|
||||||
|
range.E = pixelHeight;
|
||||||
|
range.R = 0;
|
||||||
|
range.N = codepoints;
|
||||||
|
range.b = codepoints.length;
|
||||||
|
range.M = packedChars;
|
||||||
|
range.i = (byte) oversample;
|
||||||
|
range.y = (byte) oversample;
|
||||||
|
return range;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int[] latinCodepoints() {
|
private static int[] latinCodepoints() {
|
||||||
@@ -212,4 +275,14 @@ public final class StbFontBaker {
|
|||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static final class Result {
|
||||||
|
private final FontAtlas atlas;
|
||||||
|
private final boolean overflow;
|
||||||
|
|
||||||
|
private Result(FontAtlas atlas, boolean overflow) {
|
||||||
|
this.atlas = atlas;
|
||||||
|
this.overflow = overflow;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -3,9 +3,6 @@ package cn.xiaozhou233.orangex.render.font;
|
|||||||
import cn.xiaozhou233.orangex.render.api.FontRenderer;
|
import cn.xiaozhou233.orangex.render.api.FontRenderer;
|
||||||
import cn.xiaozhou233.orangex.render.internal.GlyphDrawer;
|
import cn.xiaozhou233.orangex.render.internal.GlyphDrawer;
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Draws UTF-16 text with a primary face and an optional CJK fallback face.
|
* Draws UTF-16 text with a primary face and an optional CJK fallback face.
|
||||||
*
|
*
|
||||||
@@ -28,7 +25,6 @@ public final class TrueTypeFontRenderer implements FontRenderer {
|
|||||||
private final boolean bold;
|
private final boolean bold;
|
||||||
private final double guiScale;
|
private final double guiScale;
|
||||||
|
|
||||||
private final Map<String, Double> widthCache = new HashMap<String, Double>();
|
|
||||||
private FontFace fallback;
|
private FontFace fallback;
|
||||||
|
|
||||||
public TrueTypeFontRenderer(FontManager manager, FontFace primary,
|
public TrueTypeFontRenderer(FontManager manager, FontFace primary,
|
||||||
@@ -53,13 +49,13 @@ public final class TrueTypeFontRenderer implements FontRenderer {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void drawCenteredString(String text, double centerX, double y, int argb) {
|
public void drawCenteredString(String text, double centerX, double y, int argb) {
|
||||||
drawString(text, centerX - getUncachedWidth(text) / 2.0, y, argb);
|
drawString(text, centerX - getStringWidth(text) / 2.0, y, argb);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void drawCenteredStringWithShadow(String text, double centerX,
|
public void drawCenteredStringWithShadow(String text, double centerX,
|
||||||
double y, int argb) {
|
double y, int argb) {
|
||||||
drawStringWithShadow(text, centerX - getUncachedWidth(text) / 2.0, y, argb);
|
drawStringWithShadow(text, centerX - getStringWidth(text) / 2.0, y, argb);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -67,15 +63,12 @@ public final class TrueTypeFontRenderer implements FontRenderer {
|
|||||||
if (text == null || text.isEmpty()) {
|
if (text == null || text.isEmpty()) {
|
||||||
return 0.0;
|
return 0.0;
|
||||||
}
|
}
|
||||||
Double cached = widthCache.get(text);
|
Double cached = primary.getCachedWidth(text);
|
||||||
if (cached != null) {
|
if (cached != null) {
|
||||||
return cached;
|
return cached;
|
||||||
}
|
}
|
||||||
double width = getUncachedWidth(text);
|
double width = getUncachedWidth(text);
|
||||||
if (widthCache.size() > 4096) {
|
primary.cacheWidth(text, width);
|
||||||
widthCache.clear();
|
|
||||||
}
|
|
||||||
widthCache.put(text, width);
|
|
||||||
return width;
|
return width;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,15 @@ public interface FontBackend {
|
|||||||
|
|
||||||
FontTexture createTexture(FontAtlas atlas);
|
FontTexture createTexture(FontAtlas atlas);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bytes per atlas texel as uploaded by {@link #createTexture}, used to
|
||||||
|
* enforce the texture memory budget. RGBA backends return 4; legacy
|
||||||
|
* alpha backends can override this.
|
||||||
|
*/
|
||||||
|
default int getBytesPerTexel() {
|
||||||
|
return 4;
|
||||||
|
}
|
||||||
|
|
||||||
Render2D createRender2D(FontManager fonts, Object platformContext);
|
Render2D createRender2D(FontManager fonts, Object platformContext);
|
||||||
|
|
||||||
String getName();
|
String getName();
|
||||||
|
|||||||
+13
-8
@@ -56,22 +56,22 @@ public final class V1_8_9FontBackend implements FontBackend {
|
|||||||
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
|
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
|
||||||
GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
|
GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
|
||||||
|
|
||||||
|
// Two bytes per texel instead of four. GL_ALPHA would be even smaller
|
||||||
|
// but samples RGB as 0, which GL_MODULATE turns into black text;
|
||||||
|
// LUMINANCE_ALPHA keeps RGB = coverage and therefore behaves exactly
|
||||||
|
// like the RGBA upload.
|
||||||
ByteBuffer buffer = BufferUtils.createByteBuffer(
|
ByteBuffer buffer = BufferUtils.createByteBuffer(
|
||||||
atlas.getWidth() * atlas.getHeight() * 4);
|
atlas.getWidth() * atlas.getHeight() * 2);
|
||||||
byte[] coverage = atlas.getPixels();
|
byte[] coverage = atlas.getPixels();
|
||||||
for (int i = 0; i < coverage.length; i++) {
|
for (int i = 0; i < coverage.length; i++) {
|
||||||
// RGBA is the most compatible fixed-function format: white RGB
|
buffer.put(coverage[i]);
|
||||||
// keeps the vertex colour, alpha carries the glyph coverage.
|
|
||||||
buffer.put((byte) 0xFF);
|
|
||||||
buffer.put((byte) 0xFF);
|
|
||||||
buffer.put((byte) 0xFF);
|
|
||||||
buffer.put(coverage[i]);
|
buffer.put(coverage[i]);
|
||||||
}
|
}
|
||||||
buffer.flip();
|
buffer.flip();
|
||||||
|
|
||||||
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA,
|
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_LUMINANCE_ALPHA,
|
||||||
atlas.getWidth(), atlas.getHeight(), 0,
|
atlas.getWidth(), atlas.getHeight(), 0,
|
||||||
GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
|
GL11.GL_LUMINANCE_ALPHA, GL11.GL_UNSIGNED_BYTE, buffer);
|
||||||
|
|
||||||
GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, previousAlignment);
|
GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, previousAlignment);
|
||||||
GL11.glBindTexture(GL11.GL_TEXTURE_2D, previousTexture);
|
GL11.glBindTexture(GL11.GL_TEXTURE_2D, previousTexture);
|
||||||
@@ -79,6 +79,11 @@ public final class V1_8_9FontBackend implements FontBackend {
|
|||||||
return new V1_8_9FontTexture(textureId, atlas.getWidth(), atlas.getHeight());
|
return new V1_8_9FontTexture(textureId, atlas.getWidth(), atlas.getHeight());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getBytesPerTexel() {
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Render2D createRender2D(FontManager fonts, Object platformContext) {
|
public Render2D createRender2D(FontManager fonts, Object platformContext) {
|
||||||
return new V1_8_9Render2D(fonts, runtimeInfo, resolver, minecraft, drawer, state);
|
return new V1_8_9Render2D(fonts, runtimeInfo, resolver, minecraft, drawer, state);
|
||||||
|
|||||||
+1
-1
@@ -31,7 +31,7 @@ final class V1_8_9GlyphDrawer implements GlyphDrawer {
|
|||||||
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId);
|
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId);
|
||||||
boundTexture = textureId;
|
boundTexture = textureId;
|
||||||
}
|
}
|
||||||
state.setColor(argb);
|
state.setGlyphColor(argb);
|
||||||
|
|
||||||
double left = penX + glyph.getX0() * scale;
|
double left = penX + glyph.getX0() * scale;
|
||||||
double right = penX + glyph.getX1() * scale;
|
double right = penX + glyph.getX1() * scale;
|
||||||
|
|||||||
+42
@@ -20,6 +20,7 @@ final class V1_8_9RenderState {
|
|||||||
private final IntBuffer scissorBuffer = BufferUtils.createIntBuffer(16);
|
private final IntBuffer scissorBuffer = BufferUtils.createIntBuffer(16);
|
||||||
|
|
||||||
private boolean active;
|
private boolean active;
|
||||||
|
private boolean premultipliedBlend;
|
||||||
private boolean previousBlend;
|
private boolean previousBlend;
|
||||||
private boolean previousTexture2D;
|
private boolean previousTexture2D;
|
||||||
private boolean previousAlphaTest;
|
private boolean previousAlphaTest;
|
||||||
@@ -32,6 +33,8 @@ final class V1_8_9RenderState {
|
|||||||
private int previousTextureEnvMode;
|
private int previousTextureEnvMode;
|
||||||
private int previousActiveTexture;
|
private int previousActiveTexture;
|
||||||
private int previousShadeModel;
|
private int previousShadeModel;
|
||||||
|
private int previousBlendSrc;
|
||||||
|
private int previousBlendDst;
|
||||||
private float previousLineWidth;
|
private float previousLineWidth;
|
||||||
private int previousScissorX;
|
private int previousScissorX;
|
||||||
private int previousScissorY;
|
private int previousScissorY;
|
||||||
@@ -55,6 +58,8 @@ final class V1_8_9RenderState {
|
|||||||
previousTextureEnvMode = GL11.glGetTexEnvi(
|
previousTextureEnvMode = GL11.glGetTexEnvi(
|
||||||
GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE);
|
GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE);
|
||||||
previousShadeModel = GL11.glGetInteger(GL11.GL_SHADE_MODEL);
|
previousShadeModel = GL11.glGetInteger(GL11.GL_SHADE_MODEL);
|
||||||
|
previousBlendSrc = GL11.glGetInteger(GL11.GL_BLEND_SRC);
|
||||||
|
previousBlendDst = GL11.glGetInteger(GL11.GL_BLEND_DST);
|
||||||
previousLineWidth = GL11.glGetFloat(GL11.GL_LINE_WIDTH);
|
previousLineWidth = GL11.glGetFloat(GL11.GL_LINE_WIDTH);
|
||||||
previousActiveTexture = GL11.glGetInteger(GL13.GL_ACTIVE_TEXTURE);
|
previousActiveTexture = GL11.glGetInteger(GL13.GL_ACTIVE_TEXTURE);
|
||||||
|
|
||||||
@@ -73,6 +78,7 @@ final class V1_8_9RenderState {
|
|||||||
|
|
||||||
GL11.glEnable(GL11.GL_BLEND);
|
GL11.glEnable(GL11.GL_BLEND);
|
||||||
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
|
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
|
||||||
|
premultipliedBlend = false;
|
||||||
GL11.glDisable(GL11.GL_TEXTURE_2D);
|
GL11.glDisable(GL11.GL_TEXTURE_2D);
|
||||||
GL11.glDisable(GL11.GL_ALPHA_TEST);
|
GL11.glDisable(GL11.GL_ALPHA_TEST);
|
||||||
GL11.glDisable(GL11.GL_DEPTH_TEST);
|
GL11.glDisable(GL11.GL_DEPTH_TEST);
|
||||||
@@ -103,6 +109,7 @@ final class V1_8_9RenderState {
|
|||||||
setEnabled(GL11.GL_SCISSOR_TEST, previousScissorTest);
|
setEnabled(GL11.GL_SCISSOR_TEST, previousScissorTest);
|
||||||
GL11.glScissor(previousScissorX, previousScissorY,
|
GL11.glScissor(previousScissorX, previousScissorY,
|
||||||
previousScissorWidth, previousScissorHeight);
|
previousScissorWidth, previousScissorHeight);
|
||||||
|
GL11.glBlendFunc(previousBlendSrc, previousBlendDst);
|
||||||
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
|
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
|
||||||
GL11.GL_TEXTURE_ENV_MODE, previousTextureEnvMode);
|
GL11.GL_TEXTURE_ENV_MODE, previousTextureEnvMode);
|
||||||
GL11.glShadeModel(previousShadeModel);
|
GL11.glShadeModel(previousShadeModel);
|
||||||
@@ -119,6 +126,7 @@ final class V1_8_9RenderState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void setColor(int argb) {
|
void setColor(int argb) {
|
||||||
|
useStandardBlend();
|
||||||
GL11.glColor4f(
|
GL11.glColor4f(
|
||||||
((argb >> 16) & 0xFF) / 255.0f,
|
((argb >> 16) & 0xFF) / 255.0f,
|
||||||
((argb >> 8) & 0xFF) / 255.0f,
|
((argb >> 8) & 0xFF) / 255.0f,
|
||||||
@@ -127,6 +135,40 @@ final class V1_8_9RenderState {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Colours for {@code LUMINANCE_ALPHA} glyph atlases.
|
||||||
|
*
|
||||||
|
* <p>That atlas format stores the coverage in both luminance and alpha, so
|
||||||
|
* {@code GL_MODULATE} produces {@code Cf * coverage} twice. Premultiplying
|
||||||
|
* the vertex colour and blending with {@code (ONE, ONE_MINUS_SRC_ALPHA)}
|
||||||
|
* keeps the result identical to the old RGBA upload while halving the
|
||||||
|
* texture size.</p>
|
||||||
|
*/
|
||||||
|
void setGlyphColor(int argb) {
|
||||||
|
usePremultipliedBlend();
|
||||||
|
float alpha = ((argb >>> 24) & 0xFF) / 255.0f;
|
||||||
|
GL11.glColor4f(
|
||||||
|
((argb >> 16) & 0xFF) / 255.0f * alpha,
|
||||||
|
((argb >> 8) & 0xFF) / 255.0f * alpha,
|
||||||
|
(argb & 0xFF) / 255.0f * alpha,
|
||||||
|
alpha
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void useStandardBlend() {
|
||||||
|
if (premultipliedBlend) {
|
||||||
|
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
|
||||||
|
premultipliedBlend = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void usePremultipliedBlend() {
|
||||||
|
if (!premultipliedBlend) {
|
||||||
|
GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
|
||||||
|
premultipliedBlend = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static void setEnabled(int capability, boolean enabled) {
|
private static void setEnabled(int capability, boolean enabled) {
|
||||||
if (enabled) {
|
if (enabled) {
|
||||||
GL11.glEnable(capability);
|
GL11.glEnable(capability);
|
||||||
|
|||||||
+1
-9
@@ -30,16 +30,8 @@ public final class V26_2FontBackend implements FontBackend {
|
|||||||
int height = atlas.getHeight();
|
int height = atlas.getHeight();
|
||||||
byte[] coverage = atlas.getPixels();
|
byte[] coverage = atlas.getPixels();
|
||||||
|
|
||||||
byte[] rgba = new byte[coverage.length * 4];
|
|
||||||
for (int i = 0, j = 0; i < coverage.length; i++, j += 4) {
|
|
||||||
rgba[j] = (byte) 0xFF;
|
|
||||||
rgba[j + 1] = (byte) 0xFF;
|
|
||||||
rgba[j + 2] = (byte) 0xFF;
|
|
||||||
rgba[j + 3] = coverage[i];
|
|
||||||
}
|
|
||||||
|
|
||||||
V26_2GpuTexture texture = V26_2TextureHelper.create(
|
V26_2GpuTexture texture = V26_2TextureHelper.create(
|
||||||
loader, width, height, rgba);
|
loader, width, height, coverage);
|
||||||
return new V26_2FontTexture(texture.texture, texture.textureView,
|
return new V26_2FontTexture(texture.texture, texture.textureView,
|
||||||
texture.sampler, width, height);
|
texture.sampler, width, height);
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-2
@@ -11,7 +11,7 @@ import java.util.function.Supplier;
|
|||||||
final class V26_2TextureHelper {
|
final class V26_2TextureHelper {
|
||||||
|
|
||||||
static V26_2GpuTexture create(ClassLoader loader, int width, int height,
|
static V26_2GpuTexture create(ClassLoader loader, int width, int height,
|
||||||
byte[] rgba) {
|
byte[] coverage) {
|
||||||
try {
|
try {
|
||||||
Class<?> nativeImageClass = Class.forName(
|
Class<?> nativeImageClass = Class.forName(
|
||||||
"com.mojang.blaze3d.platform.NativeImage", false, loader);
|
"com.mojang.blaze3d.platform.NativeImage", false, loader);
|
||||||
@@ -19,9 +19,16 @@ final class V26_2TextureHelper {
|
|||||||
.getDeclaredConstructor(int.class, int.class, boolean.class);
|
.getDeclaredConstructor(int.class, int.class, boolean.class);
|
||||||
Object image = nativeImageConstructor.newInstance(width, height, false);
|
Object image = nativeImageConstructor.newInstance(width, height, false);
|
||||||
|
|
||||||
|
// Expand straight into the NativeImage buffer: avoids a second
|
||||||
|
// full-size RGBA array on top of the atlas and the image.
|
||||||
ByteBuffer buffer = (ByteBuffer) nativeImageClass
|
ByteBuffer buffer = (ByteBuffer) nativeImageClass
|
||||||
.getMethod("getPixelBytes").invoke(image);
|
.getMethod("getPixelBytes").invoke(image);
|
||||||
buffer.put(rgba);
|
for (byte alpha : coverage) {
|
||||||
|
buffer.put((byte) 0xFF);
|
||||||
|
buffer.put((byte) 0xFF);
|
||||||
|
buffer.put((byte) 0xFF);
|
||||||
|
buffer.put(alpha);
|
||||||
|
}
|
||||||
|
|
||||||
Class<?> dynamicTextureClass = Class.forName(
|
Class<?> dynamicTextureClass = Class.forName(
|
||||||
"net.minecraft.client.renderer.texture.DynamicTexture", false, loader);
|
"net.minecraft.client.renderer.texture.DynamicTexture", false, loader);
|
||||||
|
|||||||
+72
-23
@@ -14,8 +14,9 @@ OrangeX/src/main/java/cn/xiaozhou233/orangex/
|
|||||||
│ │ └── Render2D.java # 每帧 2D 上下文
|
│ │ └── Render2D.java # 每帧 2D 上下文
|
||||||
│ ├── font/
|
│ ├── font/
|
||||||
│ │ ├── FontFamily.java # 内置字体族
|
│ │ ├── FontFamily.java # 内置字体族
|
||||||
│ │ ├── FontManager.java # 按 (family,size,bold,scale) 缓存
|
│ │ ├── FontManager.java # 图集/字号缓存、显存预算与回收
|
||||||
│ │ ├── FontFace.java # 图集 + 纹理 + drawScale
|
│ │ ├── FontAtlasEntry.java # 共享图集 + GPU 纹理
|
||||||
|
│ │ ├── FontFace.java # 图集视图 + drawScale + 宽度缓存
|
||||||
│ │ ├── FontAtlas.java # 烘焙结果
|
│ │ ├── FontAtlas.java # 烘焙结果
|
||||||
│ │ ├── Glyph.java # 单字形度量 / UV
|
│ │ ├── Glyph.java # 单字形度量 / UV
|
||||||
│ │ ├── StbFontBaker.java # stb 打包适配
|
│ │ ├── StbFontBaker.java # stb 打包适配
|
||||||
@@ -45,6 +46,7 @@ public void onRender2D(EventRender2D event) {
|
|||||||
|
|
||||||
FontRenderer title = render2D.getFont(14.0f, true);
|
FontRenderer title = render2D.getFont(14.0f, true);
|
||||||
FontRenderer body = render2D.getFont(10.0f, false);
|
FontRenderer body = render2D.getFont(10.0f, false);
|
||||||
|
FontRenderer mono = render2D.getFont(FontFamily.MONTSERRAT, 10.0f, true);
|
||||||
|
|
||||||
title.drawStringWithShadow("OrangeX", 8, 8, 0xFFFFFFFF);
|
title.drawStringWithShadow("OrangeX", 8, 8, 0xFFFFFFFF);
|
||||||
body.drawString("中文测试:钻石剑", 8, 30, 0xFFFFAA00);
|
body.drawString("中文测试:钻石剑", 8, 30, 0xFFFFAA00);
|
||||||
@@ -55,8 +57,11 @@ public void onRender2D(EventRender2D event) {
|
|||||||
|
|
||||||
- 坐标和字号都是 **Minecraft GUI 像素**(`ScaledResolution` / `getGuiScaledWidth` 空间)。
|
- 坐标和字号都是 **Minecraft GUI 像素**(`ScaledResolution` / `getGuiScaledWidth` 空间)。
|
||||||
- `FontRenderer` 只在当前帧有效,不要缓存到字段里跨帧使用。
|
- `FontRenderer` 只在当前帧有效,不要缓存到字段里跨帧使用。
|
||||||
- `getFont(size, bold)` 返回的对象可以在一帧内重复使用。
|
- `getFont(size, bold)` 返回的对象可以在一帧内重复使用;文本宽度会缓存,但不要在
|
||||||
|
绘制循环里对每个字符重复 `getFont`。
|
||||||
- 英文默认使用 Proxima;遇到 CJK 字符时自动懒加载 Noto 回退。
|
- 英文默认使用 Proxima;遇到 CJK 字符时自动懒加载 Noto 回退。
|
||||||
|
- `getFont(FontFamily, size, bold)` 可以显式选择内置字体族;默认族可用
|
||||||
|
`-Dorangex.font.family` 切换。
|
||||||
|
|
||||||
## 3. 光栅化流程
|
## 3. 光栅化流程
|
||||||
|
|
||||||
@@ -65,27 +70,61 @@ public void onRender2D(EventRender2D event) {
|
|||||||
- ASCII `32..126`
|
- ASCII `32..126`
|
||||||
- Latin-1 `160..255`
|
- Latin-1 `160..255`
|
||||||
- Noto 额外解码 GBK 双字节区间(默认全 GBK,`noto.ttf` 子集实际约 6900 个汉字)
|
- Noto 额外解码 GBK 双字节区间(默认全 GBK,`noto.ttf` 子集实际约 6900 个汉字)
|
||||||
3. 在 `4096 × 4096` 的 8 位覆盖度位图上打包:
|
3. 图集边长按字符集自动估算(`512..8192`),打包溢出时自动翻倍重试;只有显式设置
|
||||||
|
`-Dorangex.font.atlasSize` 时才固定尺寸。Latin 面通常只有 `512/1024/2048`,
|
||||||
|
不再固定 4096。
|
||||||
|
4. 打包分两遍进行(stb 的 oversampling 是上下文级设置):
|
||||||
- Latin 使用 `2×2` oversampling
|
- Latin 使用 `2×2` oversampling
|
||||||
- CJK 使用 `1×1` oversampling
|
- CJK 使用 `1×1` oversampling(按 2×2 打包会让 CJK 图集大 4 倍)
|
||||||
4. 每个字形记录 `x0/y0/x1/y1`(相对基线)、`u0/v0/u1/v1`、`advance`。
|
5. 每个字形记录 `x0/y0/x1/y1`(相对基线)、`u0/v0/u1/v1`、`advance`。
|
||||||
5. 纹理上传:
|
6. 纹理上传:
|
||||||
- 1.8.9:`GL_ALPHA` + 固定管线 `GL_MODULATE`
|
- 1.8.9:`GL_LUMINANCE_ALPHA`(2 字节/像素,RGB=L=alpha=覆盖度)。`GL_ALPHA`
|
||||||
- 26.2:扩展为 RGBA(白色 RGB + 覆盖度 alpha),包装成 `DynamicTexture`
|
的 RGB 恒为 0,`GL_MODULATE` 会把文字乘成黑色;`LUMINANCE_ALPHA` 没有这个问题。
|
||||||
|
- 26.2:扩展为 RGBA(白色 RGB + 覆盖度 alpha),直接写入 `NativeImage` 缓冲区,
|
||||||
|
不再额外分配一份 RGBA 数组。
|
||||||
|
|
||||||
|
实际图集尺寸(本仓库字体实测):
|
||||||
|
|
||||||
|
| 场景 | 图集 |
|
||||||
|
| --- | --- |
|
||||||
|
| Latin 14px 以下(raster ≤ 22) | `512²` |
|
||||||
|
| Latin 28~44px(HUD Logo 等) | `1024²` |
|
||||||
|
| Latin 64px | `2048²` |
|
||||||
|
| 全 GBK,raster 8~16 | `1024²` |
|
||||||
|
| 全 GBK,raster 20~36 | `2048²` |
|
||||||
|
| 全 GBK,raster 44+ | `4096²`(默认最大 36,不会走到) |
|
||||||
|
|
||||||
字号策略:
|
字号策略:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
rasterHeight = round(logicalSize * guiScale)
|
rasterHeight = round(logicalSize * guiScale) # 再按字体族上限裁剪
|
||||||
drawScale = logicalSize / rasterHeight
|
drawScale = logicalSize / bakeHeight
|
||||||
```
|
```
|
||||||
|
|
||||||
因此 GUI Scale 只提高烘焙分辨率,不改变逻辑排版宽度。为避免 4096 图集溢出:
|
因此 GUI Scale 只提高烘焙分辨率,不改变逻辑排版宽度。
|
||||||
|
|
||||||
| 字体 | 最大 rasterHeight |
|
## 3.1 图集复用与显存
|
||||||
| --- | --- |
|
|
||||||
| 非 CJK(Proxima/Poppins) | 64 |
|
图集按 `(字体资源, bakeHeight)` 缓存,逻辑字号只影响 `drawScale`,所以多个字号共用
|
||||||
| CJK(Noto) | 36 |
|
一张纹理。为避免 4096 图集溢出,烘焙高度上限为:
|
||||||
|
|
||||||
|
| 字体 | 最大 rasterHeight | 烘焙高度 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 非 CJK(Proxima/Poppins/Jello/Montserrat) | 64 | 精确高度(图集自适应) |
|
||||||
|
| CJK(Noto) | 36 | 量化到 `12/16/20/24/28/32/36` |
|
||||||
|
|
||||||
|
Noto 的每个烘焙高度都是一整张全字符图集,量化可以让相邻字号共享同一张纹理。
|
||||||
|
例如 guiScale=2 时,11px 和 12px 都会落到 24px 桶。
|
||||||
|
|
||||||
|
显存控制(`FontManager`):
|
||||||
|
|
||||||
|
- `beginFrame()` 由 `Render2DManager` 每帧调用,把本帧用到的图集标记为“钉住”。
|
||||||
|
- 超过 `orangex.font.atlasBudgetMb` 时,从**非本帧使用**的图集里按 LRU 释放,
|
||||||
|
因此不会出现每帧重新烘焙的抖动,当前帧的工作集可以暂时超出预算。
|
||||||
|
- 图集空闲超过 `orangex.font.idleSeconds` 后释放;GUI Scale 切换后的旧图集
|
||||||
|
会在下一个 trim 周期回收。
|
||||||
|
- 每个 `FontFace` 自带一个宽度缓存(跨帧共享,最多 1024 条),`getStringWidth`
|
||||||
|
对静态文本只计算一次。
|
||||||
|
|
||||||
## 4. 版本接入
|
## 4. 版本接入
|
||||||
|
|
||||||
@@ -100,7 +139,12 @@ drawScale = logicalSize / rasterHeight
|
|||||||
- `GL_CULL_FACE` / `GL_LIGHTING` / `GL_FOG` / `GL_SCISSOR_TEST`
|
- `GL_CULL_FACE` / `GL_LIGHTING` / `GL_FOG` / `GL_SCISSOR_TEST`
|
||||||
- `GL_TEXTURE_ENV_MODE`
|
- `GL_TEXTURE_ENV_MODE`
|
||||||
- 当前 `glColor`
|
- 当前 `glColor`
|
||||||
- 图集使用 `GL_RGBA`(白色 RGB + 覆盖度 alpha),避免 `GL_ALPHA` 在固定管线中 RGB 为 0 导致文字发黑。
|
- 图集使用 `GL_LUMINANCE_ALPHA`(RGB=L=覆盖度,A=覆盖度,2 字节/像素):
|
||||||
|
- `GL_ALPHA` 的 RGB 为 0,`GL_MODULATE` 会让文字发黑;
|
||||||
|
- `GL_RGBA` 要多占一倍显存;
|
||||||
|
- 由于 L 也会被 `GL_MODULATE` 乘一次,字形顶点色需要预乘 alpha,并使用
|
||||||
|
`GL_ONE / GL_ONE_MINUS_SRC_ALPHA` 混合;形状绘制仍用普通 alpha 混合,
|
||||||
|
切换由 `V1_8_9RenderState` 自动管理并在帧末恢复原混合函数。
|
||||||
|
|
||||||
> 坑:LWJGL2 的 `glGetFloat(GL_CURRENT_COLOR, buffer)` 有
|
> 坑:LWJGL2 的 `glGetFloat(GL_CURRENT_COLOR, buffer)` 有
|
||||||
> `BufferChecks` 限制,缓冲区至少要有 **16** 个元素;只分配 4 个会在首个字形
|
> `BufferChecks` 限制,缓冲区至少要有 **16** 个元素;只分配 4 个会在首个字形
|
||||||
@@ -152,8 +196,12 @@ ASCII 0123456789
|
|||||||
|
|
||||||
| 属性 | 默认 | 说明 |
|
| 属性 | 默认 | 说明 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `-Dorangex.font.fullGbk` | `true` | `false` 时只烘焙 GB2312 一级汉字(约 3755 个) |
|
| `-Dorangex.font.fullGbk` | `true` | `false` 时只烘焙 GB2312 一级汉字(约 3755 个),CJK 图集可缩小到 2048 以内 |
|
||||||
| `-Dorangex.font.atlasSize` | `4096` | 图集边长,允许 `512..8192`。26.2 使用 RGBA 纹理,8192 约占用 256 MB 显存 |
|
| `-Dorangex.font.atlasSize` | 自动 | 固定图集边长(`512..8192`)。不设置时按字形集自动估算并在溢出时翻倍 |
|
||||||
|
| `-Dorangex.font.atlasBudgetMb` | `128` | 字体纹理显存预算(MB)。超出后按 LRU 释放非当前帧使用的图集 |
|
||||||
|
| `-Dorangex.font.idleSeconds` | `30` | 图集空闲多久后释放(秒) |
|
||||||
|
| `-Dorangex.font.debugCache` | `false` | 打印图集烘焙/释放日志与占用大小 |
|
||||||
|
| `-Dorangex.font.family` | `Proxima` | 默认字体族,支持显示名/枚举名/文件名,如 `Montserrat Light` |
|
||||||
|
|
||||||
启动日志会输出:
|
启动日志会输出:
|
||||||
|
|
||||||
@@ -175,11 +223,12 @@ ASCII 0123456789
|
|||||||
## 7. 当前限制
|
## 7. 当前限制
|
||||||
|
|
||||||
- 没有移植 Vape 的 `StbSmoothFontRenderer`(直接读游戏 `FontSet`),因此没有“MC 原版字体”选项。
|
- 没有移植 Vape 的 `StbSmoothFontRenderer`(直接读游戏 `FontSet`),因此没有“MC 原版字体”选项。
|
||||||
- 没有多页图集;CJK 在超大字号下会被限制到 36px 烘焙高度。
|
- 没有多页图集;CJK 在超大字号下会被限制到 36px 烘焙高度(对应当前 `2048²`
|
||||||
|
全字符图集,26.2 约 16 MB)。
|
||||||
- 只支持 `§0-9/a-f/r`,没有 italic / underline / obfuscated。
|
- 只支持 `§0-9/a-f/r`,没有 italic / underline / obfuscated。
|
||||||
- 粗体只对内置了 bold 文件的字体生效(Proxima);Noto 使用同一文件。
|
- 粗体只对内置了 bold 文件的字体生效(Proxima/Montserrat/Jello);Noto 使用同一文件。
|
||||||
- `FontManager` 目前不会在 GUI Scale 变化时主动释放旧纹理,需要时可调用 `clear()`。
|
- 26.2 的 `DynamicTexture` 固定为 RGBA,无法只用 1 字节/像素的 R8;目前靠自适应图集
|
||||||
- 26.2 使用 RGBA 图集,4096² 单张约 67 MB 显存;不同字号会各自持有一张。若要做大量字号,建议后续改成 R8 + 自定义画字管线或做字号分桶。
|
尺寸、CJK 字号分桶、1× CJK oversampling 和显存预算控制占用。
|
||||||
|
|
||||||
## 8. 已验证环境
|
## 8. 已验证环境
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user