mirror of
https://github.com/xiaozhou233/OrangeX-Client.git
synced 2026-12-05 13:05:52 +08:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8183eae9d1 | ||
|
|
6a045fd46f | ||
|
|
524d540c1a | ||
|
|
5f3721c294 |
No files matched your search
@@ -55,16 +55,16 @@ public final class InputEvents {
|
||||
}
|
||||
|
||||
/**
|
||||
* Called from {@code GuiScreen#keyTyped(char, int)}. Returns {@code true}
|
||||
* only for the toggle key, so other keys (ESC, etc.) still reach vanilla
|
||||
* screen handling.
|
||||
* Called from {@code GuiScreen#keyTyped(char, int)}. The event is posted to
|
||||
* the EventBus; returning {@code false} keeps vanilla key handling (ESC,
|
||||
* etc.) intact.
|
||||
*/
|
||||
public static boolean onKeyTyped(Object screen, int keyCode) {
|
||||
if (!isOurs(screen)) {
|
||||
return false;
|
||||
}
|
||||
KeyEvents.fire(keyCode);
|
||||
return keyCode == KeyCodes.M;
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void onDrawScreen(Object screen, int mouseX, int mouseY) {
|
||||
|
||||
@@ -15,11 +15,6 @@ import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
|
||||
*/
|
||||
public final class ClientInput {
|
||||
|
||||
/**
|
||||
* GUI toggle key name. The canonical key code is {@link KeyCodes#M}.
|
||||
*/
|
||||
public static final String TOGGLE_KEY_NAME = "M";
|
||||
|
||||
private static volatile boolean open;
|
||||
private static volatile double mouseX;
|
||||
private static volatile double mouseY;
|
||||
@@ -82,23 +77,6 @@ public final class ClientInput {
|
||||
pendingClose = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a key event posted on the EventBus. Only the canonical toggle
|
||||
* key (M) changes the GUI state; all other keys are ignored here but stay
|
||||
* available to other subscribers.
|
||||
*/
|
||||
public static void onKey(Minecraft minecraft, int key) {
|
||||
if (minecraft == null || key != KeyCodes.M) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (minecraft.isInputScreenOpen()) {
|
||||
requestClose();
|
||||
} else if (minecraft.isInWorld() && !minecraft.isScreenOpen()) {
|
||||
requestOpen();
|
||||
}
|
||||
}
|
||||
|
||||
public static void onMouseMove(double x, double y) {
|
||||
mouseX = x;
|
||||
mouseY = y;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package cn.xiaozhou233.orangex.input;
|
||||
|
||||
import cn.xiaozhou233.orangex.event.impl.EventKey;
|
||||
import cn.xiaozhou233.orangex.event.impl.EventTickPost;
|
||||
import cn.xiaozhou233.orangex.event.impl.EventTickPre;
|
||||
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
|
||||
@@ -8,8 +7,7 @@ import org.greenrobot.eventbus.Subscribe;
|
||||
import org.greenrobot.eventbus.ThreadMode;
|
||||
|
||||
/**
|
||||
* Drives {@link ClientInput}: handles {@code EventKey} from the EventBus and
|
||||
* reconciles the input screen state around the game tick.
|
||||
* Drives {@link ClientInput} around the game tick.
|
||||
*/
|
||||
public final class InputController {
|
||||
|
||||
@@ -20,20 +18,6 @@ public final class InputController {
|
||||
this.minecraft = minecraft;
|
||||
}
|
||||
|
||||
/**
|
||||
* Consumes key events posted by the injected input hooks. Only the toggle
|
||||
* key changes the input screen state; every event is still visible to
|
||||
* other subscribers.
|
||||
*/
|
||||
@Subscribe(threadMode = ThreadMode.POSTING)
|
||||
public void onKey(EventKey event) {
|
||||
try {
|
||||
ClientInput.onKey(minecraft, event.getKey());
|
||||
} catch (Throwable throwable) {
|
||||
logFailure(throwable);
|
||||
}
|
||||
}
|
||||
|
||||
@Subscribe(threadMode = ThreadMode.POSTING)
|
||||
public void onTick(EventTickPre event) {
|
||||
try {
|
||||
|
||||
@@ -16,6 +16,9 @@ public final class KeyCodes {
|
||||
/** LWJGL 2 {@code Keyboard.KEY_M}. */
|
||||
public static final int M = 50;
|
||||
|
||||
/** LWJGL 2 {@code Keyboard.KEY_RSHIFT}. */
|
||||
public static final int RSHIFT = 54;
|
||||
|
||||
/**
|
||||
* Translates a GLFW key code (26.x) to the 1.8.9 LWJGL 2 key code used by
|
||||
* {@code EventKey}.
|
||||
|
||||
@@ -2,6 +2,7 @@ package cn.xiaozhou233.orangex.modules;
|
||||
|
||||
import cn.xiaozhou233.orangex.OrangeX;
|
||||
import cn.xiaozhou233.orangex.event.impl.EventKey;
|
||||
import cn.xiaozhou233.orangex.modules.impl.render.ClickGUI;
|
||||
import cn.xiaozhou233.orangex.modules.impl.render.HUD;
|
||||
import org.greenrobot.eventbus.Subscribe;
|
||||
|
||||
@@ -24,6 +25,7 @@ public class ModuleManager {
|
||||
|
||||
public void registerAll() {
|
||||
register(new HUD());
|
||||
register(new ClickGUI());
|
||||
}
|
||||
|
||||
public void register(Module module) {
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package cn.xiaozhou233.orangex.modules.impl.render;
|
||||
|
||||
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
|
||||
import cn.xiaozhou233.orangex.event.impl.EventTickPre;
|
||||
import cn.xiaozhou233.orangex.input.ClientInput;
|
||||
import cn.xiaozhou233.orangex.input.KeyCodes;
|
||||
import cn.xiaozhou233.orangex.modules.Module;
|
||||
import cn.xiaozhou233.orangex.modules.ModuleCategory;
|
||||
import org.greenrobot.eventbus.Subscribe;
|
||||
|
||||
/**
|
||||
* Host module for the ClickGUI.
|
||||
*
|
||||
* <p>RSHIFT is the default keybind. Enabling the module opens the empty input
|
||||
* screen and disabling it closes the screen again. Draw the actual GUI in
|
||||
* {@link #onRender2D(EventRender2D)}.</p>
|
||||
*/
|
||||
public class ClickGUI extends Module {
|
||||
|
||||
private boolean justEnabled;
|
||||
|
||||
public ClickGUI() {
|
||||
super("ClickGUI", ModuleCategory.RENDER, KeyCodes.RSHIFT);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onEnable() {
|
||||
super.onEnable();
|
||||
if (!mc.isInWorld() || mc.isScreenOpen()) {
|
||||
// The input screen cannot open right now (title screen, chat,
|
||||
// inventory, ...); do not leave the module in a half-enabled state.
|
||||
setEnabled(false);
|
||||
return;
|
||||
}
|
||||
justEnabled = true;
|
||||
// Defer opening to EventTickPost: opening inside the keyboard callback
|
||||
// would let the same RSHIFT event reach the new screen and close it.
|
||||
ClientInput.requestOpen();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDisable() {
|
||||
justEnabled = false;
|
||||
ClientInput.requestClose();
|
||||
super.onDisable();
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onTick(EventTickPre event) {
|
||||
if (justEnabled) {
|
||||
justEnabled = false;
|
||||
return;
|
||||
}
|
||||
if (!ClientInput.isOpen()) {
|
||||
// The screen was closed by vanilla handling (for example ESC);
|
||||
// keep the module state in sync instead of requiring two RSHIFT
|
||||
// presses to open it again.
|
||||
setEnabled(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onRender2D(EventRender2D event) {
|
||||
if (!ClientInput.isOpen()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: draw the ClickGUI here.
|
||||
// Cursor: ClientInput.getMouseX() / getMouseY()
|
||||
// Buttons: ClientInput.isLeftDown() / isRightDown() / isMiddleDown()
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import cn.xiaozhou233.orangex.OrangeX;
|
||||
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
|
||||
import cn.xiaozhou233.orangex.modules.Module;
|
||||
import cn.xiaozhou233.orangex.modules.ModuleCategory;
|
||||
import cn.xiaozhou233.orangex.render.api.FontRenderer;
|
||||
import org.greenrobot.eventbus.Subscribe;
|
||||
|
||||
import java.awt.Color;
|
||||
@@ -42,6 +43,7 @@ public class HUD extends Module {
|
||||
|
||||
private void renderLogo(EventRender2D event, long currentTime) {
|
||||
String title = "OrangeX";
|
||||
FontRenderer font = event.getRender2D().getFont(LOGO_FONT_SIZE);
|
||||
|
||||
int x = LOGO_START_X;
|
||||
int y = LOGO_START_Y;
|
||||
@@ -49,31 +51,21 @@ public class HUD extends Module {
|
||||
for (int i = 0; i < title.length(); i++) {
|
||||
String character = String.valueOf(title.charAt(i));
|
||||
|
||||
event.getRender2D()
|
||||
.getFont(LOGO_FONT_SIZE)
|
||||
.drawString(
|
||||
character,
|
||||
x,
|
||||
y,
|
||||
getRainbowColor(currentTime, i)
|
||||
);
|
||||
font.drawString(character, x, y, getRainbowColor(currentTime, i));
|
||||
|
||||
x += (int) event.getRender2D()
|
||||
.getFont(LOGO_FONT_SIZE)
|
||||
.getStringWidth(character);
|
||||
x += (int) font.getStringWidth(character);
|
||||
}
|
||||
}
|
||||
|
||||
private void renderModuleList(EventRender2D event, long currentTime) {
|
||||
FontRenderer font = event.getRender2D().getFont(MODULE_FONT_SIZE);
|
||||
List<Module> modules = OrangeX.getInstance()
|
||||
.getModuleManager()
|
||||
.getAllModules()
|
||||
.stream()
|
||||
.filter(Module::isEnabled)
|
||||
.sorted(Comparator.comparingDouble(
|
||||
module -> -event.getRender2D()
|
||||
.getFont(MODULE_FONT_SIZE)
|
||||
.getStringWidth(module.getName())
|
||||
module -> -font.getStringWidth(module.getName())
|
||||
))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
@@ -84,26 +76,12 @@ public class HUD extends Module {
|
||||
Module module = modules.get(i);
|
||||
String name = module.getName();
|
||||
|
||||
int textWidth = (int) event.getRender2D()
|
||||
.getFont(MODULE_FONT_SIZE)
|
||||
.getStringWidth(name);
|
||||
|
||||
int textWidth = (int) font.getStringWidth(name);
|
||||
int x = screenWidth - textWidth - MODULE_MARGIN;
|
||||
|
||||
event.getRender2D()
|
||||
.getFont(MODULE_FONT_SIZE)
|
||||
.drawStringWithShadow(
|
||||
name,
|
||||
x,
|
||||
y,
|
||||
getRainbowColor(currentTime, i)
|
||||
);
|
||||
font.drawStringWithShadow(name, x, y, getRainbowColor(currentTime, i));
|
||||
|
||||
y += (int) (
|
||||
event.getRender2D()
|
||||
.getFont(MODULE_FONT_SIZE)
|
||||
.getStringHeight() + MODULE_SPACING
|
||||
);
|
||||
y += (int) (font.getStringHeight() + MODULE_SPACING);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ public final class FontDebugOverlay {
|
||||
+ " mouse " + (int) ClientInput.getMouseX()
|
||||
+ ", " + (int) ClientInput.getMouseY(),
|
||||
8, 68, 0xFF55FF55);
|
||||
body.drawString("M: toggle input screen", 8, 82, 0xFF888888);
|
||||
body.drawString("RSHIFT: ClickGUI", 8, 82, 0xFF888888);
|
||||
|
||||
// Large high-contrast marker: if this is invisible too, the problem is
|
||||
// GL state/coordinates rather than the glyph atlas.
|
||||
|
||||
@@ -54,6 +54,10 @@ public final class Render2DManager {
|
||||
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);
|
||||
try {
|
||||
eventBus.post(new EventRender2D(context, inWorld));
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package cn.xiaozhou233.orangex.render.api;
|
||||
|
||||
import cn.xiaozhou233.orangex.render.font.FontFamily;
|
||||
|
||||
/**
|
||||
* The 2D drawing context for one frame.
|
||||
*
|
||||
@@ -16,10 +18,22 @@ public interface Render2D {
|
||||
|
||||
double getGuiScale();
|
||||
|
||||
/**
|
||||
* Font using the configured default family
|
||||
* ({@code -Dorangex.font.family}, Proxima when unset).
|
||||
*/
|
||||
FontRenderer getFont(float size);
|
||||
|
||||
FontRenderer getFont(float size, boolean bold);
|
||||
|
||||
/**
|
||||
* Font using an explicit bundled family, e.g.
|
||||
* {@link FontFamily#MONTSERRAT} or {@link FontFamily#JELLO_LIGHT}.
|
||||
*/
|
||||
FontRenderer getFont(FontFamily family, float size);
|
||||
|
||||
FontRenderer getFont(FontFamily family, float size, boolean bold);
|
||||
|
||||
void fillRect(double x, double y, double width, double height, int argb);
|
||||
|
||||
void fillGradient(double x, double y, double width, double height,
|
||||
|
||||
@@ -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 java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A baked atlas plus its GPU texture and the scale needed to draw it at the
|
||||
* requested logical size.
|
||||
* A font face bound to a shared {@link FontAtlasEntry} and a 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 {
|
||||
|
||||
private static final int MAX_CACHED_WIDTHS = 1024;
|
||||
|
||||
private final FontFamily family;
|
||||
private final FontAtlas atlas;
|
||||
private final FontTexture texture;
|
||||
private final FontAtlasEntry entry;
|
||||
private final float logicalSize;
|
||||
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,
|
||||
float logicalSize, float drawScale) {
|
||||
FontFace(FontFamily family, FontAtlasEntry entry,
|
||||
float logicalSize, float drawScale, long lastUsedNanos) {
|
||||
this.family = family;
|
||||
this.atlas = atlas;
|
||||
this.texture = texture;
|
||||
this.entry = entry;
|
||||
this.logicalSize = logicalSize;
|
||||
this.drawScale = drawScale;
|
||||
this.lastUsedNanos = lastUsedNanos;
|
||||
}
|
||||
|
||||
public FontFamily getFamily() {
|
||||
@@ -28,11 +37,11 @@ public final class FontFace {
|
||||
}
|
||||
|
||||
public FontAtlas getAtlas() {
|
||||
return atlas;
|
||||
return entry.atlas;
|
||||
}
|
||||
|
||||
public FontTexture getTexture() {
|
||||
return texture;
|
||||
return entry.texture;
|
||||
}
|
||||
|
||||
public float getLogicalSize() {
|
||||
@@ -44,18 +53,45 @@ public final class FontFace {
|
||||
}
|
||||
|
||||
public Glyph getGlyph(int codePoint) {
|
||||
return atlas.getGlyph(codePoint);
|
||||
return entry.atlas.getGlyph(codePoint);
|
||||
}
|
||||
|
||||
public Glyph getFallbackGlyph() {
|
||||
return atlas.getFallbackGlyph();
|
||||
return entry.atlas.getFallbackGlyph();
|
||||
}
|
||||
|
||||
public float getAscent() {
|
||||
return atlas.getAscent();
|
||||
return entry.atlas.getAscent();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,60 @@
|
||||
package cn.xiaozhou233.orangex.render.font;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Bundled font families.
|
||||
*
|
||||
* <p>Every family maps a regular face and a bold face. Weights without a
|
||||
* dedicated bold file reuse a heavier (or the same) face, so asking for
|
||||
* {@code bold} text never fails to load.</p>
|
||||
*
|
||||
* <p>Families can be selected globally with
|
||||
* {@code -Dorangex.font.family=<name>}, where {@code <name>} is either the
|
||||
* display name ({@code "Montserrat Light"}), the constant name
|
||||
* ({@code MONTSERRAT_LIGHT}) or the file name ({@code Montserrat-Light.ttf}).
|
||||
* Matching ignores case, spaces and punctuation.</p>
|
||||
*/
|
||||
public enum FontFamily {
|
||||
|
||||
PROXIMA("assets/orangex/font/proxima.ttf", "assets/orangex/font/proximabd.ttf", false),
|
||||
NOTO("assets/orangex/font/noto.ttf", "assets/orangex/font/noto.ttf", true),
|
||||
POPPINS("assets/orangex/font/poppins_rg.ttf", "assets/orangex/font/poppins_rg.ttf", false);
|
||||
PROXIMA("Proxima", "proxima.ttf", "proximabd.ttf", false),
|
||||
NOTO("Noto Sans", "noto.ttf", "noto.ttf", true),
|
||||
POPPINS("Poppins", "poppins_rg.ttf", "poppins_rg.ttf", false),
|
||||
JELLO("Jello", "JelloRegular.ttf", "JelloMedium.ttf", false),
|
||||
JELLO_LIGHT("Jello Light", "JelloLight.ttf", "JelloMedium.ttf", false),
|
||||
JELLO_MEDIUM("Jello Medium", "JelloMedium.ttf", "JelloMedium.ttf", false),
|
||||
MONTSERRAT("Montserrat", "Montserrat-Regular.ttf", "Montserrat-Bold.ttf", false),
|
||||
MONTSERRAT_LIGHT("Montserrat Light", "Montserrat-Light.ttf", "Montserrat-Bold.ttf", false),
|
||||
MONTSERRAT_MEDIUM("Montserrat Medium", "Montserrat-Medium.ttf", "Montserrat-Bold.ttf", false);
|
||||
|
||||
private static final String FONT_DIRECTORY = "assets/orangex/font/";
|
||||
|
||||
private final String displayName;
|
||||
private final String regularResource;
|
||||
private final String boldResource;
|
||||
private final boolean cjkCapable;
|
||||
|
||||
FontFamily(String regularResource, String boldResource, boolean cjkCapable) {
|
||||
this.regularResource = regularResource;
|
||||
this.boldResource = boldResource;
|
||||
private final String constantKey;
|
||||
private final String displayKey;
|
||||
private final String fileKey;
|
||||
|
||||
FontFamily(String displayName, String regularFile, String boldFile,
|
||||
boolean cjkCapable) {
|
||||
this.displayName = displayName;
|
||||
this.regularResource = FONT_DIRECTORY + regularFile;
|
||||
this.boldResource = FONT_DIRECTORY + boldFile;
|
||||
this.cjkCapable = cjkCapable;
|
||||
|
||||
this.constantKey = normalize(name());
|
||||
this.displayKey = normalize(displayName);
|
||||
this.fileKey = normalize(stripExtension(regularFile));
|
||||
}
|
||||
|
||||
/**
|
||||
* Human readable name, suitable for configuration screens.
|
||||
*/
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public String getRegularResource() {
|
||||
@@ -34,4 +72,37 @@ public enum FontFamily {
|
||||
public boolean isCjkCapable() {
|
||||
return cjkCapable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a family from its display name, constant name or font file
|
||||
* name. Matching is case-insensitive and ignores spaces/punctuation.
|
||||
*
|
||||
* @return the matching family, or {@code null} when nothing matches.
|
||||
*/
|
||||
public static FontFamily byName(String name) {
|
||||
if (name == null) {
|
||||
return null;
|
||||
}
|
||||
String key = normalize(stripExtension(name));
|
||||
if (key.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
for (FontFamily family : values()) {
|
||||
if (key.equals(family.constantKey)
|
||||
|| key.equals(family.displayKey)
|
||||
|| key.equals(family.fileKey)) {
|
||||
return family;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String stripExtension(String fileName) {
|
||||
int dot = fileName.lastIndexOf('.');
|
||||
return dot > 0 ? fileName.substring(0, dot) : fileName;
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
return value.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]", "");
|
||||
}
|
||||
}
|
||||
@@ -7,33 +7,124 @@ import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Creates and caches {@link FontFace} instances.
|
||||
*
|
||||
* <p>One face exists per (family, bold, logical size, GUI scale) tuple. The
|
||||
* atlas is rasterised at {@code size * guiScale} pixels so text stays crisp on
|
||||
* high GUI scales, while {@link FontFace#getDrawScale()} converts atlas pixels
|
||||
* back to GUI pixels.</p>
|
||||
* <p>Atlases are cached per (font resource, bake height) and shared between
|
||||
* logical sizes; a face is a lightweight view adding the draw scale. The
|
||||
* atlas is rasterised at {@code size * guiScale} pixels (rounded up to the
|
||||
* 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 {
|
||||
|
||||
private static final int MAX_RASTER_HEIGHT = 64;
|
||||
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 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 boolean fullGbk;
|
||||
private final boolean debugCache;
|
||||
private final int bytesPerTexel;
|
||||
private final long atlasBudgetBytes;
|
||||
private final long idleNanos;
|
||||
|
||||
private FontFamily defaultFamily;
|
||||
private long frameStartNanos;
|
||||
private long lastTrimNanos;
|
||||
|
||||
public FontManager(FontBackend backend) {
|
||||
this.backend = backend;
|
||||
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() {
|
||||
String configured = System.getProperty("orangex.font.family");
|
||||
if (configured == null || configured.trim().isEmpty()) {
|
||||
return FALLBACK_FAMILY;
|
||||
}
|
||||
FontFamily family = FontFamily.byName(configured);
|
||||
if (family == null) {
|
||||
System.out.println("[OrangeX] Unknown font family '" + configured
|
||||
+ "', falling back to " + FALLBACK_FAMILY.getDisplayName());
|
||||
return FALLBACK_FAMILY;
|
||||
}
|
||||
return family;
|
||||
}
|
||||
|
||||
/**
|
||||
* The family used by {@code Render2D#getFont(size)}. Defaults to
|
||||
* {@link #FALLBACK_FAMILY}, overridable with
|
||||
* {@code -Dorangex.font.family=<name>}.
|
||||
*/
|
||||
public synchronized FontFamily getDefaultFamily() {
|
||||
return defaultFamily;
|
||||
}
|
||||
|
||||
/**
|
||||
* Switches the family used by the size-only {@code getFont} overloads.
|
||||
* Already created {@link FontFace} instances stay valid.
|
||||
*/
|
||||
public synchronized void setDefaultFamily(FontFamily defaultFamily) {
|
||||
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,
|
||||
boolean bold, double guiScale) {
|
||||
if (family == null) {
|
||||
family = FontFamily.PROXIMA;
|
||||
family = defaultFamily;
|
||||
}
|
||||
if (logicalSize <= 0.0f) {
|
||||
throw new IllegalArgumentException("logicalSize must be positive");
|
||||
@@ -48,27 +139,137 @@ public final class FontManager {
|
||||
} else if (rasterHeight > maxRasterHeight) {
|
||||
rasterHeight = maxRasterHeight;
|
||||
}
|
||||
int bakeHeight = bakeHeight(family, rasterHeight);
|
||||
|
||||
Key key = new Key(family, bold, rasterHeight, logicalSize);
|
||||
FontFace cached = faces.get(key);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
long now = System.nanoTime();
|
||||
String resource = family.getResource(bold);
|
||||
AtlasKey atlasKey = new AtlasKey(resource, bakeHeight, family.isCjkCapable());
|
||||
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(
|
||||
data,
|
||||
rasterHeight,
|
||||
family.isCjkCapable(),
|
||||
!"false".equalsIgnoreCase(
|
||||
System.getProperty("orangex.font.fullGbk", "true"))
|
||||
);
|
||||
data, key.bakeHeight, key.cjk, fullGbk);
|
||||
FontTexture texture = backend.createTexture(atlas);
|
||||
atlas.releasePixels();
|
||||
float drawScale = logicalSize / (float) rasterHeight;
|
||||
FontFace face = new FontFace(family, atlas, texture, logicalSize, drawScale);
|
||||
faces.put(key, face);
|
||||
return face;
|
||||
FontAtlasEntry entry = new FontAtlasEntry(
|
||||
key.resource, key.bakeHeight, atlas, texture, now);
|
||||
if (debugCache) {
|
||||
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) {
|
||||
@@ -108,24 +309,54 @@ public final class FontManager {
|
||||
return backend.getName();
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
for (FontFace face : faces.values()) {
|
||||
face.getTexture().close();
|
||||
public synchronized void clear() {
|
||||
for (FontAtlasEntry entry : atlases.values()) {
|
||||
entry.texture.close();
|
||||
}
|
||||
atlases.clear();
|
||||
faces.clear();
|
||||
}
|
||||
|
||||
private static final class Key {
|
||||
private final FontFamily family;
|
||||
private final boolean bold;
|
||||
private final int rasterHeight;
|
||||
private static final class AtlasKey {
|
||||
private final String resource;
|
||||
private final int bakeHeight;
|
||||
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 Key(FontFamily family, boolean bold, int rasterHeight,
|
||||
float logicalSize) {
|
||||
this.family = family;
|
||||
this.bold = bold;
|
||||
this.rasterHeight = rasterHeight;
|
||||
private FaceKey(AtlasKey atlasKey, float logicalSize) {
|
||||
this.atlasKey = atlasKey;
|
||||
this.logicalSize = logicalSize;
|
||||
}
|
||||
|
||||
@@ -134,23 +365,17 @@ public final class FontManager {
|
||||
if (this == other) {
|
||||
return true;
|
||||
}
|
||||
if (!(other instanceof Key)) {
|
||||
if (!(other instanceof FaceKey)) {
|
||||
return false;
|
||||
}
|
||||
Key key = (Key) other;
|
||||
return bold == key.bold
|
||||
&& rasterHeight == key.rasterHeight
|
||||
&& Float.compare(logicalSize, key.logicalSize) == 0
|
||||
&& family == key.family;
|
||||
FaceKey key = (FaceKey) other;
|
||||
return Float.compare(logicalSize, key.logicalSize) == 0
|
||||
&& atlasKey.equals(key.atlasKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = family.hashCode();
|
||||
result = 31 * result + (bold ? 1 : 0);
|
||||
result = 31 * result + rasterHeight;
|
||||
result = 31 * result + Float.floatToIntBits(logicalSize);
|
||||
return result;
|
||||
return 31 * atlasKey.hashCode() + Float.floatToIntBits(logicalSize);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,13 +20,33 @@ import java.util.Set;
|
||||
* 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
|
||||
* 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 {
|
||||
|
||||
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 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() {
|
||||
}
|
||||
|
||||
@@ -53,41 +73,67 @@ public final class StbFontBaker {
|
||||
float ascentPx = ascent[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];
|
||||
|
||||
StbTrueTypePackContext packContext = new StbTrueTypePackContext();
|
||||
if (StbRasterizer.C(packContext, pixels, atlasSize, atlasSize, 0, 1) == 0) {
|
||||
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);
|
||||
|
||||
int[] latin = latinCodepoints();
|
||||
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);
|
||||
}
|
||||
}
|
||||
boolean packed = StbRasterizer.c(packContext, fontData, 0,
|
||||
new StbTrueTypePackRange[]{latinRange}, 1) != 0;
|
||||
|
||||
if (cjkRange != null) {
|
||||
ranges = new StbTrueTypePackRange[]{latinRange, cjkRange};
|
||||
} else {
|
||||
ranges = new StbTrueTypePackRange[]{latinRange};
|
||||
StbRasterizer.n(packContext, CJK_OVERSAMPLE, CJK_OVERSAMPLE);
|
||||
packed &= StbRasterizer.c(packContext, fontData, 0,
|
||||
new StbTrueTypePackRange[]{cjkRange}, 1) != 0;
|
||||
}
|
||||
|
||||
int packed = StbRasterizer.c(packContext, fontData, 0, ranges, ranges.length);
|
||||
StbRasterizer.S(packContext);
|
||||
|
||||
Map<Integer, Glyph> glyphs = new HashMap<Integer, Glyph>();
|
||||
collectGlyphs(glyphs, latinRange, latin, atlasSize, packed != 0);
|
||||
collectGlyphs(glyphs, latinRange, latin, atlasSize);
|
||||
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
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
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;
|
||||
return new Result(atlas, !packed);
|
||||
}
|
||||
|
||||
private static void collectGlyphs(Map<Integer, Glyph> out,
|
||||
StbTrueTypePackRange range,
|
||||
int[] codepoints,
|
||||
int atlasSize,
|
||||
boolean packedOk) {
|
||||
int atlasSize) {
|
||||
float inverse = 1.0f / (float) atlasSize;
|
||||
for (int i = 0; i < codepoints.length; i++) {
|
||||
StbTrueTypePackedChar packedChar = range.M[i];
|
||||
@@ -155,10 +173,55 @@ public final class StbFontBaker {
|
||||
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() {
|
||||
@@ -212,4 +275,14 @@ public final class StbFontBaker {
|
||||
}
|
||||
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.internal.GlyphDrawer;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 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 double guiScale;
|
||||
|
||||
private final Map<String, Double> widthCache = new HashMap<String, Double>();
|
||||
private FontFace fallback;
|
||||
|
||||
public TrueTypeFontRenderer(FontManager manager, FontFace primary,
|
||||
@@ -53,13 +49,13 @@ public final class TrueTypeFontRenderer implements FontRenderer {
|
||||
|
||||
@Override
|
||||
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
|
||||
public void drawCenteredStringWithShadow(String text, double centerX,
|
||||
double y, int argb) {
|
||||
drawStringWithShadow(text, centerX - getUncachedWidth(text) / 2.0, y, argb);
|
||||
drawStringWithShadow(text, centerX - getStringWidth(text) / 2.0, y, argb);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -67,15 +63,12 @@ public final class TrueTypeFontRenderer implements FontRenderer {
|
||||
if (text == null || text.isEmpty()) {
|
||||
return 0.0;
|
||||
}
|
||||
Double cached = widthCache.get(text);
|
||||
Double cached = primary.getCachedWidth(text);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
double width = getUncachedWidth(text);
|
||||
if (widthCache.size() > 4096) {
|
||||
widthCache.clear();
|
||||
}
|
||||
widthCache.put(text, width);
|
||||
primary.cacheWidth(text, width);
|
||||
return width;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,15 @@ public interface FontBackend {
|
||||
|
||||
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);
|
||||
|
||||
String getName();
|
||||
|
||||
+13
-8
@@ -56,22 +56,22 @@ public final class V1_8_9FontBackend implements FontBackend {
|
||||
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
|
||||
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(
|
||||
atlas.getWidth() * atlas.getHeight() * 4);
|
||||
atlas.getWidth() * atlas.getHeight() * 2);
|
||||
byte[] coverage = atlas.getPixels();
|
||||
for (int i = 0; i < coverage.length; i++) {
|
||||
// RGBA is the most compatible fixed-function format: white RGB
|
||||
// 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();
|
||||
|
||||
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,
|
||||
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.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());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getBytesPerTexel() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Render2D createRender2D(FontManager fonts, Object platformContext) {
|
||||
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);
|
||||
boundTexture = textureId;
|
||||
}
|
||||
state.setColor(argb);
|
||||
state.setGlyphColor(argb);
|
||||
|
||||
double left = penX + glyph.getX0() * scale;
|
||||
double right = penX + glyph.getX1() * scale;
|
||||
|
||||
+11
-1
@@ -107,7 +107,17 @@ final class V1_8_9Render2D implements Render2D {
|
||||
|
||||
@Override
|
||||
public FontRenderer getFont(float size, boolean bold) {
|
||||
FontFace face = fonts.getFace(FontFamily.PROXIMA, size, bold, guiScale);
|
||||
return getFont(fonts.getDefaultFamily(), size, bold);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FontRenderer getFont(FontFamily family, float size) {
|
||||
return getFont(family, size, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FontRenderer getFont(FontFamily family, float size, boolean bold) {
|
||||
FontFace face = fonts.getFace(family, size, bold, guiScale);
|
||||
return new TrueTypeFontRenderer(fonts, face, bold, guiScale, drawer);
|
||||
}
|
||||
|
||||
|
||||
+42
@@ -20,6 +20,7 @@ final class V1_8_9RenderState {
|
||||
private final IntBuffer scissorBuffer = BufferUtils.createIntBuffer(16);
|
||||
|
||||
private boolean active;
|
||||
private boolean premultipliedBlend;
|
||||
private boolean previousBlend;
|
||||
private boolean previousTexture2D;
|
||||
private boolean previousAlphaTest;
|
||||
@@ -32,6 +33,8 @@ final class V1_8_9RenderState {
|
||||
private int previousTextureEnvMode;
|
||||
private int previousActiveTexture;
|
||||
private int previousShadeModel;
|
||||
private int previousBlendSrc;
|
||||
private int previousBlendDst;
|
||||
private float previousLineWidth;
|
||||
private int previousScissorX;
|
||||
private int previousScissorY;
|
||||
@@ -55,6 +58,8 @@ final class V1_8_9RenderState {
|
||||
previousTextureEnvMode = GL11.glGetTexEnvi(
|
||||
GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE);
|
||||
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);
|
||||
previousActiveTexture = GL11.glGetInteger(GL13.GL_ACTIVE_TEXTURE);
|
||||
|
||||
@@ -73,6 +78,7 @@ final class V1_8_9RenderState {
|
||||
|
||||
GL11.glEnable(GL11.GL_BLEND);
|
||||
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
|
||||
premultipliedBlend = false;
|
||||
GL11.glDisable(GL11.GL_TEXTURE_2D);
|
||||
GL11.glDisable(GL11.GL_ALPHA_TEST);
|
||||
GL11.glDisable(GL11.GL_DEPTH_TEST);
|
||||
@@ -103,6 +109,7 @@ final class V1_8_9RenderState {
|
||||
setEnabled(GL11.GL_SCISSOR_TEST, previousScissorTest);
|
||||
GL11.glScissor(previousScissorX, previousScissorY,
|
||||
previousScissorWidth, previousScissorHeight);
|
||||
GL11.glBlendFunc(previousBlendSrc, previousBlendDst);
|
||||
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
|
||||
GL11.GL_TEXTURE_ENV_MODE, previousTextureEnvMode);
|
||||
GL11.glShadeModel(previousShadeModel);
|
||||
@@ -119,6 +126,7 @@ final class V1_8_9RenderState {
|
||||
}
|
||||
|
||||
void setColor(int argb) {
|
||||
useStandardBlend();
|
||||
GL11.glColor4f(
|
||||
((argb >> 16) & 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) {
|
||||
if (enabled) {
|
||||
GL11.glEnable(capability);
|
||||
|
||||
+2
-10
@@ -30,16 +30,8 @@ public final class V26_2FontBackend implements FontBackend {
|
||||
int height = atlas.getHeight();
|
||||
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(
|
||||
loader, width, height, rgba);
|
||||
V26_2GpuTexture texture = V26_2TextureHelper.createFromCoverage(
|
||||
loader, width, height, coverage);
|
||||
return new V26_2FontTexture(texture.texture, texture.textureView,
|
||||
texture.sampler, width, height);
|
||||
}
|
||||
|
||||
+11
-1
@@ -140,7 +140,17 @@ final class V26_2Render2D implements Render2D {
|
||||
|
||||
@Override
|
||||
public FontRenderer getFont(float size, boolean bold) {
|
||||
FontFace face = fonts.getFace(FontFamily.PROXIMA, size, bold, guiScale);
|
||||
return getFont(fonts.getDefaultFamily(), size, bold);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FontRenderer getFont(FontFamily family, float size) {
|
||||
return getFont(family, size, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FontRenderer getFont(FontFamily family, float size, boolean bold) {
|
||||
FontFace face = fonts.getFace(family, size, bold, guiScale);
|
||||
return new TrueTypeFontRenderer(fonts, face, bold, guiScale, drawer);
|
||||
}
|
||||
|
||||
|
||||
+38
-4
@@ -5,13 +5,43 @@ import java.nio.ByteBuffer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Creates a {@code DynamicTexture} from an RGBA byte array without linking
|
||||
* against Mojang's classes.
|
||||
* Creates a {@code DynamicTexture} without linking against Mojang's classes.
|
||||
*
|
||||
* <p>Two input formats are supported so callers cannot mix them up: raw RGBA
|
||||
* (shapes, sprites) and one-byte coverage/font atlases, which are expanded to
|
||||
* white RGB + coverage alpha directly inside the {@code NativeImage} buffer.</p>
|
||||
*/
|
||||
final class V26_2TextureHelper {
|
||||
|
||||
static V26_2GpuTexture create(ClassLoader loader, int width, int height,
|
||||
byte[] rgba) {
|
||||
final byte[] rgba) {
|
||||
return create(loader, width, height, new PixelWriter() {
|
||||
@Override
|
||||
public void write(ByteBuffer buffer) {
|
||||
buffer.put(rgba);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static V26_2GpuTexture createFromCoverage(ClassLoader loader, int width,
|
||||
int height, final byte[] coverage) {
|
||||
return create(loader, width, height, new PixelWriter() {
|
||||
@Override
|
||||
public void write(ByteBuffer buffer) {
|
||||
// Expand straight into the NativeImage buffer: avoids a second
|
||||
// full-size RGBA array on top of the atlas and the image.
|
||||
for (byte alpha : coverage) {
|
||||
buffer.put((byte) 0xFF);
|
||||
buffer.put((byte) 0xFF);
|
||||
buffer.put((byte) 0xFF);
|
||||
buffer.put(alpha);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static V26_2GpuTexture create(ClassLoader loader, int width,
|
||||
int height, PixelWriter writer) {
|
||||
try {
|
||||
Class<?> nativeImageClass = Class.forName(
|
||||
"com.mojang.blaze3d.platform.NativeImage", false, loader);
|
||||
@@ -21,7 +51,7 @@ final class V26_2TextureHelper {
|
||||
|
||||
ByteBuffer buffer = (ByteBuffer) nativeImageClass
|
||||
.getMethod("getPixelBytes").invoke(image);
|
||||
buffer.put(rgba);
|
||||
writer.write(buffer);
|
||||
|
||||
Class<?> dynamicTextureClass = Class.forName(
|
||||
"net.minecraft.client.renderer.texture.DynamicTexture", false, loader);
|
||||
@@ -46,6 +76,10 @@ final class V26_2TextureHelper {
|
||||
}
|
||||
}
|
||||
|
||||
private interface PixelWriter {
|
||||
void write(ByteBuffer buffer);
|
||||
}
|
||||
|
||||
private V26_2TextureHelper() {
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+72
-23
@@ -14,8 +14,9 @@ OrangeX/src/main/java/cn/xiaozhou233/orangex/
|
||||
│ │ └── Render2D.java # 每帧 2D 上下文
|
||||
│ ├── font/
|
||||
│ │ ├── FontFamily.java # 内置字体族
|
||||
│ │ ├── FontManager.java # 按 (family,size,bold,scale) 缓存
|
||||
│ │ ├── FontFace.java # 图集 + 纹理 + drawScale
|
||||
│ │ ├── FontManager.java # 图集/字号缓存、显存预算与回收
|
||||
│ │ ├── FontAtlasEntry.java # 共享图集 + GPU 纹理
|
||||
│ │ ├── FontFace.java # 图集视图 + drawScale + 宽度缓存
|
||||
│ │ ├── FontAtlas.java # 烘焙结果
|
||||
│ │ ├── Glyph.java # 单字形度量 / UV
|
||||
│ │ ├── StbFontBaker.java # stb 打包适配
|
||||
@@ -45,6 +46,7 @@ public void onRender2D(EventRender2D event) {
|
||||
|
||||
FontRenderer title = render2D.getFont(14.0f, true);
|
||||
FontRenderer body = render2D.getFont(10.0f, false);
|
||||
FontRenderer mono = render2D.getFont(FontFamily.MONTSERRAT, 10.0f, true);
|
||||
|
||||
title.drawStringWithShadow("OrangeX", 8, 8, 0xFFFFFFFF);
|
||||
body.drawString("中文测试:钻石剑", 8, 30, 0xFFFFAA00);
|
||||
@@ -55,8 +57,11 @@ public void onRender2D(EventRender2D event) {
|
||||
|
||||
- 坐标和字号都是 **Minecraft GUI 像素**(`ScaledResolution` / `getGuiScaledWidth` 空间)。
|
||||
- `FontRenderer` 只在当前帧有效,不要缓存到字段里跨帧使用。
|
||||
- `getFont(size, bold)` 返回的对象可以在一帧内重复使用。
|
||||
- `getFont(size, bold)` 返回的对象可以在一帧内重复使用;文本宽度会缓存,但不要在
|
||||
绘制循环里对每个字符重复 `getFont`。
|
||||
- 英文默认使用 Proxima;遇到 CJK 字符时自动懒加载 Noto 回退。
|
||||
- `getFont(FontFamily, size, bold)` 可以显式选择内置字体族;默认族可用
|
||||
`-Dorangex.font.family` 切换。
|
||||
|
||||
## 3. 光栅化流程
|
||||
|
||||
@@ -65,27 +70,61 @@ public void onRender2D(EventRender2D event) {
|
||||
- ASCII `32..126`
|
||||
- Latin-1 `160..255`
|
||||
- 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
|
||||
- CJK 使用 `1×1` oversampling
|
||||
4. 每个字形记录 `x0/y0/x1/y1`(相对基线)、`u0/v0/u1/v1`、`advance`。
|
||||
5. 纹理上传:
|
||||
- 1.8.9:`GL_ALPHA` + 固定管线 `GL_MODULATE`
|
||||
- 26.2:扩展为 RGBA(白色 RGB + 覆盖度 alpha),包装成 `DynamicTexture`
|
||||
- CJK 使用 `1×1` oversampling(按 2×2 打包会让 CJK 图集大 4 倍)
|
||||
5. 每个字形记录 `x0/y0/x1/y1`(相对基线)、`u0/v0/u1/v1`、`advance`。
|
||||
6. 纹理上传:
|
||||
- 1.8.9:`GL_LUMINANCE_ALPHA`(2 字节/像素,RGB=L=alpha=覆盖度)。`GL_ALPHA`
|
||||
的 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
|
||||
rasterHeight = round(logicalSize * guiScale)
|
||||
drawScale = logicalSize / rasterHeight
|
||||
rasterHeight = round(logicalSize * guiScale) # 再按字体族上限裁剪
|
||||
drawScale = logicalSize / bakeHeight
|
||||
```
|
||||
|
||||
因此 GUI Scale 只提高烘焙分辨率,不改变逻辑排版宽度。为避免 4096 图集溢出:
|
||||
因此 GUI Scale 只提高烘焙分辨率,不改变逻辑排版宽度。
|
||||
|
||||
| 字体 | 最大 rasterHeight |
|
||||
| --- | --- |
|
||||
| 非 CJK(Proxima/Poppins) | 64 |
|
||||
| CJK(Noto) | 36 |
|
||||
## 3.1 图集复用与显存
|
||||
|
||||
图集按 `(字体资源, bakeHeight)` 缓存,逻辑字号只影响 `drawScale`,所以多个字号共用
|
||||
一张纹理。为避免 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. 版本接入
|
||||
|
||||
@@ -100,7 +139,12 @@ drawScale = logicalSize / rasterHeight
|
||||
- `GL_CULL_FACE` / `GL_LIGHTING` / `GL_FOG` / `GL_SCISSOR_TEST`
|
||||
- `GL_TEXTURE_ENV_MODE`
|
||||
- 当前 `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)` 有
|
||||
> `BufferChecks` 限制,缓冲区至少要有 **16** 个元素;只分配 4 个会在首个字形
|
||||
@@ -152,8 +196,12 @@ ASCII 0123456789
|
||||
|
||||
| 属性 | 默认 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `-Dorangex.font.fullGbk` | `true` | `false` 时只烘焙 GB2312 一级汉字(约 3755 个) |
|
||||
| `-Dorangex.font.atlasSize` | `4096` | 图集边长,允许 `512..8192`。26.2 使用 RGBA 纹理,8192 约占用 256 MB 显存 |
|
||||
| `-Dorangex.font.fullGbk` | `true` | `false` 时只烘焙 GB2312 一级汉字(约 3755 个),CJK 图集可缩小到 2048 以内 |
|
||||
| `-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. 当前限制
|
||||
|
||||
- 没有移植 Vape 的 `StbSmoothFontRenderer`(直接读游戏 `FontSet`),因此没有“MC 原版字体”选项。
|
||||
- 没有多页图集;CJK 在超大字号下会被限制到 36px 烘焙高度。
|
||||
- 没有多页图集;CJK 在超大字号下会被限制到 36px 烘焙高度(对应当前 `2048²`
|
||||
全字符图集,26.2 约 16 MB)。
|
||||
- 只支持 `§0-9/a-f/r`,没有 italic / underline / obfuscated。
|
||||
- 粗体只对内置了 bold 文件的字体生效(Proxima);Noto 使用同一文件。
|
||||
- `FontManager` 目前不会在 GUI Scale 变化时主动释放旧纹理,需要时可调用 `clear()`。
|
||||
- 26.2 使用 RGBA 图集,4096² 单张约 67 MB 显存;不同字号会各自持有一张。若要做大量字号,建议后续改成 R8 + 自定义画字管线或做字号分桶。
|
||||
- 粗体只对内置了 bold 文件的字体生效(Proxima/Montserrat/Jello);Noto 使用同一文件。
|
||||
- 26.2 的 `DynamicTexture` 固定为 RGBA,无法只用 1 字节/像素的 R8;目前靠自适应图集
|
||||
尺寸、CJK 字号分桶、1× CJK oversampling 和显存预算控制占用。
|
||||
|
||||
## 8. 已验证环境
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
1. 为什么 1.8.9 的字体 / GUI 只在进入世界后绘制,而 26.2 在主界面也会绘制,以及 OrangeX 现在如何统一。
|
||||
2. 客户端 GUI 打开时,如何让鼠标在 GUI 上移动,而不是继续控制游戏视角。
|
||||
|
||||
> 状态:第 1 部分和第 2 部分的空 GUI / 鼠标输入已落地。M 键打开或关闭输入界面。
|
||||
> 状态:第 1 部分和第 2 部分的空 GUI / 鼠标输入已落地。RSHIFT(右 Shift)打开或关闭输入界面。
|
||||
|
||||
---
|
||||
|
||||
@@ -280,7 +280,7 @@ Minecraft262Stubs/
|
||||
OrangeX/src/main/java/cn/xiaozhou233/orangex/
|
||||
├── input/
|
||||
│ ├── ClientInput.java 跨版本输入状态:开/关、鼠标坐标、按键状态
|
||||
│ ├── InputController.java 订阅 EventKey 并驱动 ClientInput
|
||||
│ ├── InputController.java 在 tick 前后驱动 ClientInput
|
||||
│ ├── KeyCodes.java 统一的按键编号(1.8.9 LWJGL 2)+ GLFW 转换
|
||||
│ ├── internal/
|
||||
│ │ ├── VersionInput.java 版本输入接口
|
||||
@@ -292,6 +292,7 @@ OrangeX/src/main/java/cn/xiaozhou233/orangex/
|
||||
│ ├── facade/InputEvents.java 输入门面(1.8.9 注入代码)
|
||||
│ ├── facade/KeyEvents.java 按键事件统一投递到 EventBus
|
||||
│ └── impl/EventKey.java 按键事件(统一使用 1.8.9 key code)
|
||||
├── modules/impl/render/ClickGUI.java ClickGUI 模块,默认 keybind = RSHIFT
|
||||
└── hook/impl/
|
||||
├── GuiInputHook.java 1.8.9 GuiScreen 输入 / 按键 Hook
|
||||
└── KeyPressHook.java 1.8.9 KeyBinding#onTick / 26.2 KeyboardHandler#keyPress 按键 Hook
|
||||
@@ -299,16 +300,20 @@ OrangeX/src/main/java/cn/xiaozhou233/orangex/
|
||||
|
||||
行为:
|
||||
|
||||
- M 键在**世界内**打开空 GUI;再次按下关闭。
|
||||
- RSHIFT 是 `ClickGUI` 模块的默认 keybind。
|
||||
- `ModuleManager` 收到 RSHIFT 的 `EventKey` 后 toggle `ClickGUI`:
|
||||
- 启用:`ClickGUI.onEnable` → `ClientInput.requestOpen()`
|
||||
- 禁用:`ClickGUI.onDisable` → `ClientInput.requestClose()`
|
||||
- 如果界面被 ESC 等原版逻辑关闭,`ClickGUI.onTick` 会在下一 tick 自动禁用模块,保证状态同步。
|
||||
- 所有 `EventKey#getKey()` 都使用 1.8.9 / LWJGL 2 键码,26.2 的 GLFW 键码在投递前通过 `KeyCodes.fromGlfw` 转换。
|
||||
- 按键统一走 EventBus:
|
||||
- 1.8.9 打开:`KeyBinding#onTick(int)` → `InputEvents.onKeyPressed` → `KeyEvents.fire` → `EventBus.post(EventKey)` → `InputController.onKey` → `ClientInput.requestOpen()`
|
||||
- 1.8.9 打开:`KeyBinding#onTick(int)` → `InputEvents.onKeyPressed` → `KeyEvents.fire` → `EventBus.post(EventKey)` → `ModuleManager.onKey` → `ClickGUI.toggle()` → `ClientInput.requestOpen()`
|
||||
- 1.8.9 关闭:`GuiScreen#keyTyped(char, int)` → `InputEvents.onKeyTyped` → 同一条 EventBus 链路 → `requestClose()`
|
||||
- 26.2:`KeyboardHandler#keyPress(long, int, KeyEvent)` 全局 Hook → `InputEvents.onGlfwKeyPressed` → 键码转换 → 同一条 EventBus 链路。行走、无界面时也能收到按键,不再依赖 tick 轮询。
|
||||
- 其他功能可以直接 `@Subscribe` `EventKey` 读取按键,不需要再改注入代码。
|
||||
- 其他模块可以直接 `@Subscribe` `EventKey` 读取按键,不需要再改注入代码。
|
||||
- 打开 / 关闭都只在 tick 末尾(`EventTickPost` → `ClientInput.applyPending`)真正执行。
|
||||
- 原因:如果在键盘循环里直接打开 Screen,同一个 M 事件会立刻被 `currentScreen.handleKeyboardInput()` 再处理一次,导致刚打开就关闭。
|
||||
- 自动重复事件:1.8.9 通过 `Keyboard.isRepeatEvent()` 过滤,26.2 只处理 GLFW action == 1(press),按住 M 不会反复开关。
|
||||
- 原因:如果在键盘循环里直接打开 Screen,同一个 RSHIFT 事件会立刻被 `currentScreen.handleKeyboardInput()` 再处理一次,导致刚打开就关闭。
|
||||
- 自动重复事件:1.8.9 通过 `Keyboard.isRepeatEvent()` 过滤,26.2 只处理 GLFW action == 1(press),按住 RSHIFT 不会反复开关。
|
||||
- 打开时:
|
||||
- 1.8.9:运行时生成 `GuiScreen` 具体子类,再 `Minecraft#displayGuiScreen(...)`;`doesGuiPauseGame()` 对自己的空壳返回 `false`。
|
||||
- 26.2:`Gui#setScreen(new V26_2InputScreen())`,`isPauseScreen()` 返回 `false`。
|
||||
@@ -377,8 +382,8 @@ int y = scaledHeight - Mouse.getY() * scaledHeight / mc.displayHeight - 1;
|
||||
| 1.8.9 注入报 `no such class: cn$...` | 注入代码写了全限定 `cn.*`,应使用简单类名 + `getInjectedClassNames()` |
|
||||
| 空 GUI 打开后玩家还能动 | 1.8.9 / 26.2 都必须真正打开 Screen;只 ungrab 不够 |
|
||||
| 1.8.9 空 GUI 导致单人暂停 | 已 Hook `GuiScreen#doesGuiPauseGame`,对自己的空壳返回 false |
|
||||
| 1.8.9 短按 M 没反应 | 已改为 `KeyBinding#onTick` 事件路径;可用 `-Dorangex.debugInput=true` 查看按键日志 |
|
||||
| 聊天 / 背包界面里按 M 被劫持 | 打开前检查 `isScreenOpen()`,任何原版 Screen 存在时都不响应 |
|
||||
| 1.8.9 短按 RSHIFT 没反应 | 已改为 `KeyBinding#onTick` 事件路径;可用 `-Dorangex.debugInput=true` 查看按键日志 |
|
||||
| 聊天 / 背包界面里按 RSHIFT 被劫持 | 打开前检查 `isScreenOpen()`,任何原版 Screen 存在时都不响应 |
|
||||
|
||||
---
|
||||
|
||||
|
||||
Reference in new issue
Block a user