Compare commits

...
11 Commits
Author SHA1 Message Date
xiaozhou233 30fde895b6 Docs: README.md 2026-11-10 15:00:21 +08:00
xiaozhou233 ed7fa13e7f Fix: Interpolate world positions with the frame's partial tick
- Pass the 1.8.9 HUD method's partial tick through the render hook into
  EventRender2D instead of reading Timer.renderPartialTicks reflectively
- Let WorldView.snapshot() take that value so ESP projection matches the
  rendered world and no longer advances in 20 Hz steps
- Keep the reflected timer read as a fallback and warn once when it cannot
  be resolved instead of silently interpolating with 0
2026-11-10 13:47:55 +08:00
xiaozhou233 d8a46a1b70 Feat: Show module settings as a page in the ClickGUI content area
- Replace the floating SettingsWindow with an inline settings page
- Return to the module list via the back button or a category click
- Scroll the module list and the settings page with the mouse wheel
- Share module row geometry through ContentList and add a scrollbar
  helper
- Bail out of scroll input when the content fits
2026-11-10 13:26:19 +08:00
xiaozhou233 09de736269 Feat: Add mouse wheel scrolling to client input
- Queue wheel notches in ClientInput for the next frame
- Forward wheel deltas from the 1.8.9 screen and 26.2 input screen
- Hook GuiScreen#handleMouseInput after vanilla, guarded so a
  missing method never disables the other input injections
- Shrink HUD module font size to 10
2026-11-10 13:12:22 +08:00
xiaozhou233 d9075831e3 Feat: Add entity kind and invisibility filters to ESP
- WorldView now captures every entity instead of players only and no longer applies gameplay filtering.

- Add EntityKind (player/monster/animal/villager/other) and local-player/invisible flags to EntityTarget.

- Move target filtering into ESP and add Players, Local Player, Monsters, Animals, Villagers, Others and Invisible options.

- Invisible entities are an independent filter and can be used as a standalone invisible-only ESP.
2026-11-09 15:38:48 +08:00
xiaozhou233 51a232d7ac Feat: Add 2D ESP module and cross-version world wrapper
- Add ESP render module drawing 2D boxes, corner brackets, fill, health
  bar, name and distance for nearby players.
- Add WorldView capability backed by per-version implementations:
  1.8.9 reconstructs the camera from renderViewEntity, Timer partial
  ticks and EntityRenderer#getFOVModifier, including third-person and
  front-view offsets; 26.2 reads GameRenderer#mainCamera directly.
- Add version-independent value objects (WorldSnapshot, EntityTarget,
  ScreenPoint) and Projection math shared by every version.
- Wire the new capability through WrapperProvider, WrapperRegistry and
  MinecraftFactory, and create the world view in OrangeX.start().
- Skip local, dead, invisible and spectator players, and drop targets
  behind the camera.

Verified with :OrangeX:shadowJar, mapping checks for both 1.8.9 mapping
files, member checks against the 1.8.8 obf jar, and fake-world tests for
both version implementations.
2026-11-08 18:11:11 +08:00
xiaozhou233 29eb7609e9 Feat: Add ClickGUI interface and stabilise 26.2 font rendering
- Split the window into style, layout, sidebar, content and settings renderers

- Remove the ACTIVE counter and footer hint; open module settings in a draggable popup on right click

- Use Montserrat for the ClickGUI and snap the window to whole pixels while dragging

- Fix 26.2 glyph snapping: shared baseline, thin-stroke visibility and even horizontal spacing
2026-11-08 15:24:42 +08:00
xiaozhou233 8183eae9d1 Fix: Restore correct rounded-rect corners on 26.2
- V26_2TextureHelper.create now takes raw RGBA again, so V26_2ShapeCache's quarter-circle corner textures are uploaded intact instead of being read as one-byte coverage and appearing grey

- Add an explicit createFromCoverage entry point for font atlases, which still expands directly into the NativeImage buffer

- Point V26_2FontBackend at createFromCoverage so the font texture optimisation is kept
2026-11-08 01:55:41 +08:00
xiaozhou233 6a045fd46f 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
2026-11-08 01:50:22 +08:00
xiaozhou233 524d540c1a Feat: Add Jello and Montserrat font families
- Register Jello Light/Regular/Medium and Montserrat Light/Regular/Medium/Bold, with weights lacking a bold file reusing a heavier face

- Add Render2D.getFont(FontFamily, size[, bold]) so features can pick a family, implemented by both the 1.8.9 and 26.2 backends

- Allow overriding the default family with -Dorangex.font.family (display name, constant name or font file name); Proxima stays the fallback

- Resolve CJK glyphs missing from the new Latin-only faces through the existing Noto fallback
2026-11-08 01:24:29 +08:00
xiaozhou233 5f3721c294 Feat: Add ClickGUI module bound to RSHIFT
- Add modules/impl/render/ClickGUI with default keybind RSHIFT

- Let the module open/close the input screen via requestOpen/requestClose

- Sync module state when the screen is closed by vanilla handling

- Remove the hard-coded GUI toggle from ClientInput/InputController
2026-11-08 00:50:05 +08:00
74 changed files with 4474 additions and 286 deletions

No files matched your search

@@ -13,6 +13,7 @@ import cn.xiaozhou233.orangex.runtime.RuntimeDetector;
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
import cn.xiaozhou233.orangex.wrapper.MinecraftFactory;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import lombok.Getter;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
@@ -35,6 +36,8 @@ public class OrangeX {
private ModuleManager moduleManager = new ModuleManager();
@Getter
private Minecraft minecraft;
@Getter
private WorldView worldView;
public OrangeX() {
System.out.println("OrangeX <init> start!");
@@ -52,6 +55,17 @@ public class OrangeX {
this.minecraft = minecraft;
System.out.println(minecraft.getMinecraft());
try {
this.worldView = MinecraftFactory.createWorld(
runtimeInfo, MappingManager.getResolver(), minecraft);
} catch (Throwable throwable) {
// The client must keep running even when a version cannot expose
// world data; world-dependent modules simply stay inactive.
System.err.println("[OrangeX] World wrapper unavailable: "
+ throwable.getMessage());
throwable.printStackTrace();
}
render2DManager = new Render2DManager(
runtimeInfo, MappingManager.getResolver(), minecraft.getMinecraft());
System.out.println("[OrangeX] Font backend: " + render2DManager.getBackendName());
@@ -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) {
@@ -17,10 +17,19 @@ public final class Render2DEvents {
* screen too, so the hook must pass this through.
*/
public static void fire(Object platformContext, boolean inWorld) {
fire(platformContext, inWorld, Float.NaN);
}
/**
* @param partialTicks the partial tick the game rendered this frame with.
* {@link Float#NaN} when the hook cannot supply it.
*/
public static void fire(Object platformContext, boolean inWorld,
float partialTicks) {
try {
Render2DManager manager = OrangeX.getInstance().getRender2DManager();
if (manager != null) {
manager.fire(platformContext, inWorld);
manager.fire(platformContext, inWorld, partialTicks);
}
} catch (Throwable throwable) {
if (!failureLogged) {
@@ -15,10 +15,16 @@ public class EventRender2D {
private final Render2D render2D;
private final boolean inWorld;
private final float partialTicks;
public EventRender2D(Render2D render2D, boolean inWorld) {
this(render2D, inWorld, Float.NaN);
}
public EventRender2D(Render2D render2D, boolean inWorld, float partialTicks) {
this.render2D = render2D;
this.inWorld = inWorld;
this.partialTicks = partialTicks;
}
public Render2D getRender2D() {
@@ -31,4 +37,16 @@ public class EventRender2D {
public boolean isInWorld() {
return inWorld;
}
/**
* The partial tick the game used for this frame's world render, i.e. the
* interpolation factor between the previous and the current tick.
*
* <p>Feature code must use this value instead of reading a timer of its own
* so projected world positions line up with the rendered world. It is
* {@link Float#NaN} when the hook could not supply one.</p>
*/
public float getPartialTicks() {
return partialTicks;
}
}
@@ -67,6 +67,16 @@ public final class GuiInputHook extends ClassHook {
// The empty screen is an overlay: it must not pause singleplayer.
injectAfter(ctClass, "doesGuiPauseGame", "()Z",
"if (orangexbridge.Hooks.isOurScreen($0)) { $_ = false; }");
// Wheel scrolling for the ClickGUI. Injecting after vanilla keeps its
// mouse-button dispatch intact; the wheel event is still readable.
try {
injectAfter(ctClass, "handleMouseInput", "()V",
"orangexbridge.Legacy.forwardScroll($0);");
} catch (Throwable ignored) {
// Scrolling is optional: never let it disable the input hooks
// above on a runtime where this method cannot be resolved.
}
}
private void injectBefore(CtClass ctClass, String name,
@@ -101,7 +101,8 @@ public final class Render2DHook extends ClassHook {
throw new IllegalStateException(
"No (F)V HUD method found in " + ctClass.getName());
}
method.insertAfter("orangexbridge.Hooks.render2d(null, true);");
method.insertAfter(
"orangexbridge.Hooks.render2d(null, true, $1);");
return;
} else {
MappingMethod target = resolver.mapMethod(
@@ -112,7 +113,10 @@ public final class Render2DHook extends ClassHook {
methodDescriptor = target.getTargetDescriptor();
}
CtMethod method = ctClass.getMethod(methodName, methodDescriptor);
method.insertAfter("orangexbridge.Hooks.render2d(null, true);");
// $1 is the frame's partial tick: pass it through so features
// interpolate world positions exactly like the world render.
method.insertAfter(
"orangexbridge.Hooks.render2d(null, true, $1);");
break;
}
case V26_2: {
@@ -15,17 +15,13 @@ 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;
private static volatile boolean leftDown;
private static volatile boolean rightDown;
private static volatile boolean middleDown;
private static double scrollAmount;
private static boolean started;
private static boolean pendingOpen;
@@ -82,23 +78,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;
@@ -133,6 +112,29 @@ public final class ClientInput {
}
}
/**
* Queues a wheel notch for the next frame. Positive is one notch up.
*/
public static synchronized void onMouseScroll(double amount) {
if (amount != 0.0) {
scrollAmount += amount;
}
}
public static void onMouseScroll(double x, double y, double amount) {
onMouseMove(x, y);
onMouseScroll(amount);
}
/**
* @return the wheel amount accumulated since the previous call.
*/
public static synchronized double consumeScroll() {
double amount = scrollAmount;
scrollAmount = 0.0;
return amount;
}
public static void reset() {
if (open) {
System.out.println("[OrangeX] Input screen closed");
@@ -141,6 +143,7 @@ public final class ClientInput {
leftDown = false;
rightDown = false;
middleDown = false;
scrollAmount = 0.0;
}
public static boolean isOpen() {
@@ -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}.
@@ -1,5 +1,6 @@
package cn.xiaozhou233.orangex.input.internal.v1_8_9;
import cn.xiaozhou233.orangex.event.facade.InputEvents;
import cn.xiaozhou233.orangex.hook.ClassPoolUtils;
import cn.xiaozhou233.orangex.hook.HookManager;
import cn.xiaozhou233.orangex.hook.JuiceAgentBridge;
@@ -272,13 +273,29 @@ public final class V1_8_9Input implements VersionInput {
}
/**
* Used by injected {@code GuiScreen}/{@code KeyBinding} code to ignore
* LWJGL auto-repeat events.
* Used by injected {@code GuiScreen} code to ignore LWJGL auto-repeat
* events.
*/
public static boolean isRepeatEvent() {
return Keyboard.isRepeatEvent();
}
/**
* Called after {@code GuiScreen#handleMouseInput} ran. The wheel event is
* still readable at this point and must not consume the vanilla mouse
* button dispatch.
*/
public static void forwardScroll(Object screen) {
if (!InputEvents.isOurInputScreen(screen)) {
return;
}
int wheel = Mouse.getEventDWheel();
if (wheel != 0) {
ClientInput.onMouseScroll(wheel > 0 ? 1.0 : -1.0);
}
}
@Override
public double getGuiMouseX() {
Object screen = shellScreen;
@@ -63,7 +63,7 @@ public final class V26_2InputScreen extends Screen {
@Override
public boolean mouseScrolled(double x, double y,
double scrollX, double scrollY) {
ClientInput.onMouseMove(x, y);
ClientInput.onMouseScroll(x, y, scrollY);
return true;
}
}
@@ -2,6 +2,8 @@ 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.ESP;
import cn.xiaozhou233.orangex.modules.impl.render.HUD;
import org.greenrobot.eventbus.Subscribe;
@@ -24,6 +26,8 @@ public class ModuleManager {
public void registerAll() {
register(new HUD());
register(new ClickGUI());
register(new ESP());
}
public void register(Module module) {
@@ -0,0 +1,73 @@
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 cn.xiaozhou233.orangex.ui.clickgui.ClickGuiRender;
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;
ClickGuiRender.reset();
// 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;
ClickGuiRender.reset();
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;
}
ClickGuiRender.render(event);
}
}
@@ -0,0 +1,288 @@
package cn.xiaozhou233.orangex.modules.impl.render;
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 cn.xiaozhou233.orangex.render.api.Render2D;
import cn.xiaozhou233.orangex.value.BooleanValue;
import cn.xiaozhou233.orangex.value.ModeValue;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import cn.xiaozhou233.orangex.wrapper.common.EntityTarget;
import cn.xiaozhou233.orangex.wrapper.common.ScreenPoint;
import cn.xiaozhou233.orangex.wrapper.common.Vec3;
import cn.xiaozhou233.orangex.wrapper.common.WorldSnapshot;
import org.greenrobot.eventbus.Subscribe;
import java.awt.Color;
import java.util.List;
import java.util.Locale;
/**
* 2D ESP: projects entities to the screen and draws a box, name, distance and
* health bar around each one.
*
* <p>All drawing happens in GUI pixel space through {@link Render2D}, so it
* works with both the 1.8.9 and the modern font backends. World data comes
* from the cross-version {@link WorldView} wrapper, never from game classes
* directly. The wrapper reports every entity; the target-type filters below
* decide which kinds are drawn.</p>
*/
public class ESP extends Module {
private static final float NAME_FONT_SIZE = 9.0F;
private static final double NAME_GAP = 2.0D;
private static final double BOX_PADDING = 0.5D;
private static final double CORNER_LENGTH = 4.0D;
private static final double HEALTH_BAR_WIDTH = 2.0D;
private static final double HEALTH_BAR_GAP = 2.0D;
private static final double MIN_BOX_HEIGHT = 2.0D;
private static final double MIN_BOX_WIDTH = 2.0D;
private static final int ORANGE = 0xFFFF8A00;
private static final int FILL_ALPHA = 32;
private static final int HEALTH_BACKGROUND = 0x80000000;
private final BooleanValue players = addBoolean("Players", true);
private final BooleanValue localPlayer = addBoolean("Local Player", false);
private final BooleanValue monsters = addBoolean("Monsters", false);
private final BooleanValue animals = addBoolean("Animals", false);
private final BooleanValue villagers = addBoolean("Villagers", false);
private final BooleanValue others = addBoolean("Others", false);
private final BooleanValue invisible = addBoolean("Invisible", false);
private final BooleanValue box = addBoolean("Box", true);
private final BooleanValue fill = addBoolean("Fill", true);
private final BooleanValue health = addBoolean("Health", true);
private final BooleanValue name = addBoolean("Name", true);
private final BooleanValue distance = addBoolean("Distance", true);
private final ModeValue style = addMode("Style", "Box", "Box", "Corners");
private final ModeValue colorMode = addMode("Color", "Orange", "Orange", "Health", "Rainbow");
public ESP() {
super("ESP", ModuleCategory.RENDER);
}
@Subscribe
public void onRender2D(EventRender2D event) {
if (!event.isInWorld()) {
return;
}
WorldView world = OrangeX.getInstance().getWorldView();
if (world == null) {
return;
}
WorldSnapshot snapshot;
try {
snapshot = world.snapshot(event.getPartialTicks());
} catch (Throwable throwable) {
// A broken wrapper must not kill the whole HUD frame.
System.err.println("[ESP] Failed to read world snapshot: "
+ throwable.getMessage());
return;
}
if (snapshot == null) {
return;
}
Render2D graphics = event.getRender2D();
int screenWidth = graphics.getWidth();
int screenHeight = graphics.getHeight();
FontRenderer font = graphics.getFont(NAME_FONT_SIZE);
double fontHeight = font.getStringHeight();
List<EntityTarget> targets = snapshot.getTargets();
for (int index = 0; index < targets.size(); index++) {
EntityTarget target = targets.get(index);
if (!isTargetEnabled(target)) {
continue;
}
renderTarget(graphics, font, fontHeight, snapshot, target, index,
screenWidth, screenHeight);
}
}
/**
* Target filters live here rather than in the world wrapper so the same
* snapshot can feed future features (tracers, nametags, ...) without each
* of them re-implementing the rules.
*/
private boolean isTargetEnabled(EntityTarget target) {
// Invisible entities are their own category: they are drawn only when
// "Invisible" is enabled, no matter which kind filters are on. Turn
// every kind filter off and keep only this one on for an invisible-only
// ESP.
if (target.isLocalPlayer()) {
return localPlayer.isEnabled()
&& (!target.isInvisible() || invisible.isEnabled());
}
if (target.isInvisible()) {
return invisible.isEnabled();
}
switch (target.getKind()) {
case PLAYER:
return players.isEnabled();
case MONSTER:
return monsters.isEnabled();
case ANIMAL:
return animals.isEnabled();
case VILLAGER:
return villagers.isEnabled();
case OTHER:
default:
return others.isEnabled();
}
}
private void renderTarget(Render2D graphics,
FontRenderer font,
double fontHeight,
WorldSnapshot snapshot,
EntityTarget target,
int index,
int screenWidth,
int screenHeight) {
if (target.getHeight() <= 0.0D) {
return;
}
Vec3 feet = target.getPosition();
Vec3 head = new Vec3(feet.getX(), feet.getY() + target.getHeight(), feet.getZ());
ScreenPoint feetPoint = snapshot.project(feet, screenWidth, screenHeight);
ScreenPoint headPoint = snapshot.project(head, screenWidth, screenHeight);
if (!feetPoint.isVisible() || !headPoint.isVisible()) {
return;
}
double boxHeight = feetPoint.getY() - headPoint.getY();
if (boxHeight < MIN_BOX_HEIGHT) {
return;
}
double boxWidth = Math.max(MIN_BOX_WIDTH,
boxHeight * (target.getWidth() / target.getHeight()));
double centerX = (feetPoint.getX() + headPoint.getX()) * 0.5D;
double left = centerX - boxWidth * 0.5D;
double top = headPoint.getY();
int color = color(target, index);
if (fill.isEnabled()) {
graphics.fillRect(left, top, boxWidth, boxHeight,
(color & 0x00FFFFFF) | (FILL_ALPHA << 24));
}
if (box.isEnabled()) {
if (style.is("Corners")) {
drawCorners(graphics, left, top, boxWidth, boxHeight, color);
} else {
graphics.drawRect(left - BOX_PADDING, top - BOX_PADDING,
boxWidth + BOX_PADDING * 2.0D,
boxHeight + BOX_PADDING * 2.0D,
1.0D, color);
}
}
if (health.isEnabled()) {
drawHealthBar(graphics, target, left - HEALTH_BAR_GAP, top, boxHeight);
}
String label = label(target);
if (label == null) {
return;
}
double textWidth = font.getStringWidth(label);
double textY = top - fontHeight - NAME_GAP;
font.drawStringWithShadow(label, centerX - textWidth * 0.5D, textY, color);
}
private void drawCorners(Render2D graphics, double left, double top,
double width, double height, int color) {
double length = Math.min(CORNER_LENGTH, Math.min(width, height) * 0.5D);
if (length <= 0.0D) {
return;
}
double right = left + width;
double bottom = top + height;
// Top-left
graphics.fillRect(left, top, length, 1.0D, color);
graphics.fillRect(left, top, 1.0D, length, color);
// Top-right
graphics.fillRect(right - length, top, length, 1.0D, color);
graphics.fillRect(right - 1.0D, top, 1.0D, length, color);
// Bottom-left
graphics.fillRect(left, bottom - 1.0D, length, 1.0D, color);
graphics.fillRect(left, bottom - length, 1.0D, length, color);
// Bottom-right
graphics.fillRect(right - length, bottom - 1.0D, length, 1.0D, color);
graphics.fillRect(right - 1.0D, bottom - length, 1.0D, length, color);
}
private void drawHealthBar(Render2D graphics, EntityTarget target,
double x, double top, double height) {
if (target.getMaxHealth() <= 0.0F) {
return;
}
float fraction = target.getHealth() / target.getMaxHealth();
fraction = Math.max(0.0F, Math.min(1.0F, fraction));
double filled = height * fraction;
graphics.fillRect(x, top, HEALTH_BAR_WIDTH, height, HEALTH_BACKGROUND);
graphics.fillRect(x, top + height - filled, HEALTH_BAR_WIDTH, filled,
healthColor(fraction));
}
private String label(EntityTarget target) {
String nameText = name.isEnabled() ? target.getName() : null;
String distanceText = distance.isEnabled()
? String.format(Locale.ROOT, "%.1fm", target.getDistance())
: null;
if (nameText == null) {
return distanceText;
}
if (distanceText == null) {
return nameText;
}
return nameText + " " + distanceText;
}
private int color(EntityTarget target, int index) {
if (colorMode.is("Health")) {
float fraction = target.getMaxHealth() <= 0.0F
? 1.0F
: target.getHealth() / target.getMaxHealth();
return healthColor(Math.max(0.0F, Math.min(1.0F, fraction)));
}
if (colorMode.is("Rainbow")) {
float hue = ((System.currentTimeMillis() % 4000L) / 4000.0F)
+ index * 0.05F;
return Color.HSBtoRGB(hue - (float) Math.floor(hue), 0.85F, 1.0F);
}
return ORANGE;
}
private int healthColor(float fraction) {
return Color.HSBtoRGB(0.33F * fraction, 0.85F, 1.0F);
}
}
@@ -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;
@@ -17,7 +18,7 @@ public class HUD extends Module {
private static final float RAINBOW_CYCLE = 6000f;
private static final int LOGO_FONT_SIZE = 22;
private static final int MODULE_FONT_SIZE = 14;
private static final int MODULE_FONT_SIZE = 10;
private static final int LOGO_START_X = 5;
private static final int LOGO_START_Y = 5;
@@ -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.
@@ -36,7 +36,7 @@ public final class Render2DManager {
}
public void fire(Object platformContext) {
fire(platformContext, true);
fire(platformContext, true, Float.NaN);
}
/**
@@ -45,6 +45,15 @@ public final class Render2DManager {
* event is dropped unless {@link #isRenderInMenus()} is on.
*/
public void fire(Object platformContext, boolean inWorld) {
fire(platformContext, inWorld, Float.NaN);
}
/**
* @param partialTicks the partial tick the game rendered this frame with,
* or {@link Float#NaN} when the caller has none.
*/
public void fire(Object platformContext, boolean inWorld,
float partialTicks) {
if (!inWorld && !renderInMenus) {
return;
}
@@ -54,9 +63,13 @@ 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));
eventBus.post(new EventRender2D(context, inWorld, partialTicks));
} finally {
context.flush();
}
@@ -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();
@@ -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);
@@ -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;
@@ -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);
}
@@ -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);
@@ -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,6 +11,18 @@ import java.lang.reflect.Method;
*/
final class V26_2GlyphDrawer implements GlyphDrawer {
/**
* Maximum distance (in logical pixels) that still counts as "sitting on the
* baseline" rather than being a descender or a raised glyph.
*
* <p>The atlas is packed with 2x oversampling, so a normal glyph's baked
* bottom is 0.25/0.75px away from the baseline. 26.2 blits use integer
* coordinates, and rounding those offsets per glyph made some letters drop
* onto the next pixel while their neighbours stayed put. Snapping
* near-baseline bottoms to one shared value keeps a line visually level.</p>
*/
private static final double BASELINE_SNAP = 0.9;
private final Object extractor;
private final Method innerBlit;
private final Object guiPipeline;
@@ -28,12 +40,36 @@ final class V26_2GlyphDrawer implements GlyphDrawer {
return;
}
int x0 = (int) Math.round(penX + glyph.getX0() * scale);
int y0 = (int) Math.round(baseline + glyph.getY0() * scale);
int x1 = (int) Math.round(penX + glyph.getX1() * scale);
int y1 = (int) Math.round(baseline + glyph.getY1() * scale);
if (x1 <= x0 || y1 <= y0) {
return;
// Snap both horizontal edges the same way (downwards). Rounding each
// edge independently made neighbouring glyphs drift apart or together
// by one pixel, which is most visible around narrow letters such as I.
int x0 = (int) Math.floor(penX + glyph.getX0() * scale + 0.0001);
int x1 = (int) Math.floor(penX + glyph.getX1() * scale + 0.0001);
// Anchor both edges to one rounded baseline so every glyph in a line
// shares the same pixel origin.
int base = (int) Math.round(baseline);
// Round the top down: curved letters (C, G, o...) overshoot the flat
// cap/x-height by half a pixel in the atlas. Rounding split them onto
// different rows, which made "CLICK GUI" look uneven.
int y0 = base + (int) Math.floor(glyph.getY0() * scale + 0.0001);
double bottomOffset = glyph.getY1() * scale;
int y1;
if (bottomOffset >= 0.0 && bottomOffset < BASELINE_SNAP) {
// Normal letter/punctuation: sit exactly on the baseline.
y1 = base;
} else {
// Descenders (g, p, y...) and raised glyphs keep their offset.
y1 = base + (int) Math.round(bottomOffset);
}
// Thin strokes (l, I, | ...) can be narrower than one GUI pixel at high
// GUI scales. Keep them visible with at least one pixel.
if (x1 <= x0) {
x1 = x0 + 1;
}
if (y1 <= y0) {
y1 = y0 + 1;
}
V26_2FontTexture fontTexture = (V26_2FontTexture) texture;
@@ -49,3 +85,4 @@ final class V26_2GlyphDrawer implements GlyphDrawer {
}
}
}
@@ -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);
}
@@ -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() {
}
}
@@ -0,0 +1,53 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* Smooths hover and toggle values for ClickGUI elements.
*
* <p>Keys are compared by identity so equal-but-distinct modules or values do
* not share an animation.</p>
*/
public final class ClickGuiAnimator {
private static final float HOVER_SPEED = 14.0f;
private static final float STATE_SPEED = 16.0f;
private final Map<Object, Float> hoverAnimations =
new IdentityHashMap<Object, Float>();
private final Map<Object, Float> stateAnimations =
new IdentityHashMap<Object, Float>();
public float hover(Object key, boolean hovered, float delta) {
if (!hoverAnimations.containsKey(key)) {
hoverAnimations.put(key, 0.0f);
}
return animate(hoverAnimations, key, hovered ? 1.0f : 0.0f,
delta, HOVER_SPEED);
}
public float state(Object key, boolean state, float delta) {
return animate(stateAnimations, key, state ? 1.0f : 0.0f,
delta, STATE_SPEED);
}
private static float animate(Map<Object, Float> animations, Object key,
float target, float delta, float speed) {
Float stored = animations.get(key);
float current = stored == null ? target : stored.floatValue();
if (Math.abs(target - current) < 0.001f) {
animations.put(key, target);
return target;
}
float factor = 1.0f - (float) Math.exp(-speed * delta);
float next = current + (target - current) * factor;
if (Math.abs(target - next) < 0.002f) {
next = target;
}
animations.put(key, next);
return next;
}
}
@@ -0,0 +1,87 @@
package cn.xiaozhou233.orangex.ui.clickgui;
/**
* Immutable geometry for one ClickGUI frame.
*
* <p>The panel keeps its own bounds and category-row height; this class turns
* them into the positions and sizes used by the individual renderers.</p>
*/
public final class ClickGuiLayout {
private final float x;
private final float y;
private final float width;
private final float height;
private final float categoryRowHeight;
private final int screenWidth;
private final int screenHeight;
public ClickGuiLayout(float x, float y, float width, float height,
float categoryRowHeight, int screenWidth,
int screenHeight) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.categoryRowHeight = categoryRowHeight;
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
}
public float x() {
return x;
}
public float y() {
return y;
}
public float width() {
return width;
}
public float height() {
return height;
}
public float categoryRowHeight() {
return categoryRowHeight;
}
public int screenWidth() {
return screenWidth;
}
public int screenHeight() {
return screenHeight;
}
public float contentX() {
return x + ClickGuiStyle.SIDEBAR_CARD_X
+ ClickGuiStyle.SIDEBAR_WIDTH + 14.0f;
}
public float contentWidth() {
return x + width - 12.0f - contentX();
}
public float listTop() {
return y + ClickGuiStyle.HEADER_HEIGHT + 38.0f;
}
public float listBottom() {
return y + height - 8.0f;
}
public float categoryRowX() {
return x + ClickGuiStyle.SIDEBAR_CARD_X + 6.0f;
}
public float categoryRowWidth() {
return ClickGuiStyle.SIDEBAR_WIDTH - 12.0f;
}
public float categoryRowTop() {
return y + ClickGuiStyle.SIDEBAR_CARD_Y + 9.0f;
}
}
@@ -0,0 +1,48 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.modules.ModuleCategory;
import cn.xiaozhou233.orangex.value.KeybindValue;
import cn.xiaozhou233.orangex.value.Value;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Module and category helpers shared by the ClickGUI renderers.
*/
public final class ClickGuiModules {
private ClickGuiModules() {
}
public static List<Value<?>> settingsOf(Module module) {
List<Value<?>> settings = new ArrayList<Value<?>>();
for (Value<?> value : module.getVisibleValues()) {
// The module keybind is shown on the collapsed row instead.
if (!(value instanceof KeybindValue)) {
settings.add(value);
}
}
return settings;
}
/**
* Allocation-free variant of {@link #settingsOf(Module)} for rows that only
* need to know whether a settings page can be opened.
*/
public static boolean hasSettings(Module module) {
for (Value<?> value : module.getVisibleValues()) {
if (!(value instanceof KeybindValue)) {
return true;
}
}
return false;
}
public static String displayName(ModuleCategory category) {
String name = category.name();
return name.substring(0, 1) + name.substring(1).toLowerCase(Locale.ROOT);
}
}
@@ -0,0 +1,65 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
import cn.xiaozhou233.orangex.input.ClientInput;
/**
* Renders and drives the ClickGUI while the empty input screen is open.
*
* <p>The input screen only records the raw mouse state in
* {@link ClientInput}; this class turns button transitions into component
* callbacks and then renders {@link MainPanel}.</p>
*/
public final class ClickGuiRender {
private static final MainPanel MAIN_PANEL = new MainPanel();
private static boolean lastLeftDown;
private static boolean lastRightDown;
private ClickGuiRender() {
}
public static void render(EventRender2D event) {
if (!ClientInput.isOpen()) {
reset();
return;
}
float mouseX = (float) ClientInput.getMouseX();
float mouseY = (float) ClientInput.getMouseY();
boolean leftDown = ClientInput.isLeftDown();
boolean rightDown = ClientInput.isRightDown();
if (leftDown && !lastLeftDown) {
MAIN_PANEL.mouseClicked(mouseX, mouseY, 0);
}
if (rightDown && !lastRightDown) {
MAIN_PANEL.mouseClicked(mouseX, mouseY, 1);
}
if (leftDown && lastLeftDown) {
MAIN_PANEL.mouseDragged(mouseX, mouseY, 0);
}
if (!leftDown && lastLeftDown) {
MAIN_PANEL.mouseReleased(mouseX, mouseY, 0);
}
if (!rightDown && lastRightDown) {
MAIN_PANEL.mouseReleased(mouseX, mouseY, 1);
}
MAIN_PANEL.render(event);
lastLeftDown = leftDown;
lastRightDown = rightDown;
}
/**
* Drops transient input state. Called when the GUI closes or reopens so a
* button held across screens does not produce a stale drag.
*/
public static void reset() {
MAIN_PANEL.resetInteraction();
lastLeftDown = false;
lastRightDown = false;
}
}
@@ -0,0 +1,137 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.render.api.FontRenderer;
import cn.xiaozhou233.orangex.render.api.Render2D;
import cn.xiaozhou233.orangex.render.font.FontFamily;
/**
* Shared colours, metrics and drawing primitives for the ClickGUI.
*
* <p>All colours are ARGB and all coordinates are Minecraft GUI pixels.</p>
*/
public final class ClickGuiStyle {
/**
* Font family used only by the ClickGUI. Other screens keep using the
* globally configured default family.
*/
public static final FontFamily FONT_FAMILY = FontFamily.MONTSERRAT;
public static final float DESIGN_WIDTH = 448f;
public static final float DESIGN_HEIGHT = 306f;
public static final float MARGIN = 12f;
public static final float PANEL_RADIUS = 9f;
public static final float HEADER_HEIGHT = 46f;
public static final float SIDEBAR_WIDTH = 112f;
public static final float SIDEBAR_CARD_X = 10f;
public static final float SIDEBAR_CARD_Y = HEADER_HEIGHT + 8f;
public static final float CATEGORY_HEIGHT = 26f;
public static final float CATEGORY_GAP = 2f;
public static final float MODULE_HEIGHT = 27f;
public static final float MODULE_GAP = 3f;
public static final float TOGGLE_WIDTH = 26f;
public static final float TOGGLE_HEIGHT = 12f;
public static final float SMALL_TOGGLE_WIDTH = 20f;
public static final float SMALL_TOGGLE_HEIGHT = 9f;
public static final int COLOR_PANEL = 0xF218181D;
public static final int COLOR_BORDER = 0xFF2C2C37;
public static final int COLOR_TEXT = 0xFFEDEDF2;
public static final int COLOR_TEXT_DIM = 0xFF9A9AA8;
public static final int COLOR_TEXT_MUTED = 0xFF61616F;
public static final int COLOR_ACCENT = 0xFFFF8A3D;
public static final int COLOR_ACCENT_RGB = 0x00FF8A3D;
public static final int COLOR_DIVIDER = 0xFF272730;
public static final int COLOR_SIDEBAR_BG = 0xFF15151A;
public static final int COLOR_SIDEBAR_BORDER = 0xFF24242C;
public static final int COLOR_SWITCH_OFF = 0xFF34343F;
public static final int COLOR_KNOB_OFF = 0xFF9A9AA8;
public static final int COLOR_SCROLLBAR = 0x40FFFFFF;
private ClickGuiStyle() {
}
public static FontRenderer font(Render2D graphics, float size) {
return graphics.getFont(FONT_FAMILY, size);
}
public static FontRenderer font(Render2D graphics, float size, boolean bold) {
return graphics.getFont(FONT_FAMILY, size, bold);
}
public static void drawSwitch(Render2D graphics, float switchX, float switchY,
float switchWidth, float switchHeight,
float progress) {
int track = lerpColor(COLOR_SWITCH_OFF, COLOR_ACCENT, progress);
graphics.fillRoundedRect(switchX, switchY, switchWidth, switchHeight,
switchHeight / 2.0f, track);
float knobSize = switchHeight - 4.0f;
float knobX = switchX + 2.0f
+ (switchWidth - knobSize - 4.0f) * progress;
int knob = lerpColor(COLOR_KNOB_OFF, 0xFFFFFFFF, progress);
graphics.fillRoundedRect(knobX, switchY + 2.0f, knobSize, knobSize,
knobSize / 2.0f, knob);
}
public static double centeredY(FontRenderer font, float top, float height) {
return top + (height - font.getStringHeight()) / 2.0;
}
/**
* Draws a thin scrollbar for a scrollable list. Nothing is drawn while the
* content fits, so short lists look unchanged.
*/
public static void drawScrollbar(Render2D graphics, double x, double top,
double viewHeight, double contentHeight,
double scroll) {
if (contentHeight <= viewHeight + 0.5) {
return;
}
double thumbHeight = Math.max(18.0,
viewHeight * (viewHeight / contentHeight));
double maxScroll = contentHeight - viewHeight;
double progress = maxScroll <= 0.0 ? 0.0
: clamp((float) (scroll / maxScroll), 0.0f, 1.0f);
double thumbY = top + (viewHeight - thumbHeight) * progress;
graphics.fillRoundedRect(x, thumbY, 2.0, thumbHeight, 1.0,
COLOR_SCROLLBAR);
}
public static boolean isInside(double mouseX, double mouseY,
double x, double y,
double width, double height) {
return mouseX >= x && mouseX <= x + width
&& mouseY >= y && mouseY <= y + height;
}
public static float clamp(float value, float min, float max) {
return Math.max(min, Math.min(max, value));
}
public static int argb(int alpha, int rgb) {
int clamped = Math.max(0, Math.min(255, alpha));
return (clamped << 24) | (rgb & 0x00FFFFFF);
}
public static int lerpColor(int from, int to, float progress) {
float t = clamp(progress, 0.0f, 1.0f);
int a = lerpChannel(from >>> 24, to >>> 24, t);
int r = lerpChannel(from >> 16, to >> 16, t);
int g = lerpChannel(from >> 8, to >> 8, t);
int b = lerpChannel(from, to, t);
return (a << 24) | (r << 16) | (g << 8) | b;
}
private static int lerpChannel(int from, int to, float t) {
int fromChannel = from & 0xFF;
int toChannel = to & 0xFF;
return Math.round(fromChannel + (toChannel - fromChannel) * t);
}
}
@@ -0,0 +1,78 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.modules.Module;
import java.util.List;
/**
* Row geometry for the module list.
*
* <p>Module rows are evenly sized, so a row's position is just its index times
* the row stride minus the scroll offset. The renderer and the input code share
* this class so both always agree on where a row is.</p>
*/
public final class ContentList {
private final ClickGuiLayout layout;
private final List<Module> modules;
private float scroll;
public ContentList(ClickGuiLayout layout, List<Module> modules,
float scroll) {
this.layout = layout;
this.modules = modules;
this.scroll = scroll;
}
public List<Module> modules() {
return modules;
}
public float scroll() {
return scroll;
}
public void scrollBy(float amount) {
scroll += amount;
}
/**
* Clamps the scroll offset to the current content, so switching category
* never leaves the list overscrolled.
*/
public void clampScroll() {
scroll = ClickGuiStyle.clamp(scroll, 0.0f, maxScroll());
}
public float rowStride() {
return ClickGuiStyle.MODULE_HEIGHT + ClickGuiStyle.MODULE_GAP;
}
public float rowTop(int index) {
return layout.listTop() + index * rowStride() - scroll;
}
public float contentHeight() {
return modules.isEmpty() ? 0.0f
: modules.size() * rowStride() - ClickGuiStyle.MODULE_GAP;
}
public float maxScroll() {
return Math.max(0.0f,
contentHeight() - (layout.listBottom() - layout.listTop()));
}
/**
* @return the index of the module row under {@code mouseY}, or {@code -1}.
*/
public int moduleIndexAt(float mouseY) {
for (int i = 0; i < modules.size(); i++) {
float top = rowTop(i);
if (mouseY >= top && mouseY <= top + ClickGuiStyle.MODULE_HEIGHT) {
return i;
}
}
return -1;
}
}
@@ -0,0 +1,133 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.modules.ModuleCategory;
import cn.xiaozhou233.orangex.render.api.FontRenderer;
import cn.xiaozhou233.orangex.render.api.Render2D;
import cn.xiaozhou233.orangex.value.KeybindValue;
import java.util.List;
/**
* Draws the module list for the selected category.
*
* <p>Right-clicking a module opens its settings page in this same content area
* (see {@link SettingsSection}). The list scrolls with the wheel and shows a
* scrollbar when it does not fit.</p>
*/
public final class ContentRenderer {
private ContentRenderer() {
}
public static void draw(Render2D graphics, ClickGuiLayout layout,
ContentList rows, ModuleCategory category,
ClickGuiAnimator animator, float delta,
double mouseX, double mouseY) {
float y = layout.y();
float contentX = layout.contentX();
float contentWidth = layout.contentWidth();
List<Module> modules = rows.modules();
FontRenderer title = ClickGuiStyle.font(graphics, 13.0f, true);
title.drawString(ClickGuiModules.displayName(category), contentX,
y + ClickGuiStyle.HEADER_HEIGHT + 10,
ClickGuiStyle.COLOR_TEXT);
FontRenderer meta = ClickGuiStyle.font(graphics, 8.0f);
String metaText = modules.size()
+ (modules.size() == 1 ? " MODULE" : " MODULES");
meta.drawString(metaText,
contentX + contentWidth - meta.getStringWidth(metaText),
y + ClickGuiStyle.HEADER_HEIGHT + 14,
ClickGuiStyle.COLOR_TEXT_MUTED);
graphics.fillRect(contentX, y + ClickGuiStyle.HEADER_HEIGHT + 30,
contentWidth, 1, ClickGuiStyle.COLOR_DIVIDER);
float listTop = layout.listTop();
float listBottom = layout.listBottom();
graphics.enableScissor(contentX - 2, listTop - 2,
contentWidth + 4, listBottom - listTop + 4);
if (modules.isEmpty()) {
FontRenderer empty = ClickGuiStyle.font(graphics, 9.0f);
String text = "No modules here yet";
empty.drawString(text,
contentX + (contentWidth - empty.getStringWidth(text)) / 2.0,
listTop + 14, ClickGuiStyle.COLOR_TEXT_MUTED);
} else {
for (int i = 0; i < modules.size(); i++) {
Module module = modules.get(i);
float rowY = rows.rowTop(i);
if (rowY > listBottom
|| rowY + ClickGuiStyle.MODULE_HEIGHT < listTop) {
continue;
}
boolean hovered = mouseY >= listTop && mouseY <= listBottom
&& ClickGuiStyle.isInside(mouseX, mouseY, contentX,
rowY, contentWidth, ClickGuiStyle.MODULE_HEIGHT);
float hover = animator.hover(module, hovered, delta);
drawModuleRow(graphics, layout, module, rowY, hover, animator,
delta);
}
}
graphics.disableScissor();
ClickGuiStyle.drawScrollbar(graphics, contentX + contentWidth - 3,
listTop, listBottom - listTop, rows.contentHeight(),
rows.scroll());
}
private static void drawModuleRow(Render2D graphics, ClickGuiLayout layout,
Module module, float rowY, float hover,
ClickGuiAnimator animator, float delta) {
float contentX = layout.contentX();
float contentWidth = layout.contentWidth();
float rowRight = contentX + contentWidth;
float moduleHeight = ClickGuiStyle.MODULE_HEIGHT;
int background = module.isEnabled()
? ClickGuiStyle.argb((int) (14.0f + 14.0f * hover),
ClickGuiStyle.COLOR_ACCENT_RGB)
: ClickGuiStyle.argb((int) (6.0f + 10.0f * hover),
0x00FFFFFF);
graphics.fillRoundedRect(contentX, rowY, contentWidth, moduleHeight,
5, background);
if (module.isEnabled()) {
graphics.fillRoundedRect(contentX + 2, rowY + 8, 2.0f,
moduleHeight - 16, 1.0f, ClickGuiStyle.COLOR_ACCENT);
}
FontRenderer name = ClickGuiStyle.font(graphics, 10.0f,
module.isEnabled());
name.drawString(module.getName(), contentX + 10,
ClickGuiStyle.centeredY(name, rowY, moduleHeight),
module.isEnabled() ? ClickGuiStyle.COLOR_TEXT
: ClickGuiStyle.COLOR_TEXT_DIM);
KeybindValue keybind = module.getKeybind();
if (keybind.isBound()) {
FontRenderer keyFont = ClickGuiStyle.font(graphics, 8.0f);
String key = KeyNames.keyName(keybind.getKey());
keyFont.drawString(key,
rowRight - ClickGuiStyle.TOGGLE_WIDTH - 18
- keyFont.getStringWidth(key),
ClickGuiStyle.centeredY(keyFont, rowY, moduleHeight),
ClickGuiStyle.COLOR_TEXT_MUTED);
}
float toggleX = rowRight - ClickGuiStyle.TOGGLE_WIDTH - 10;
float toggleY = rowY + (moduleHeight - ClickGuiStyle.TOGGLE_HEIGHT)
/ 2.0f;
ClickGuiStyle.drawSwitch(graphics, toggleX, toggleY,
ClickGuiStyle.TOGGLE_WIDTH, ClickGuiStyle.TOGGLE_HEIGHT,
animator.state(module, module.isEnabled(), delta));
}
}
@@ -0,0 +1,114 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.input.KeyCodes;
/**
* Maps raw GLFW-style key codes to the short labels shown in the ClickGUI.
*/
public final class KeyNames {
private KeyNames() {
}
public static String keyName(int key) {
if (key == KeyCodes.NONE) {
return "NONE";
}
switch (key) {
case 1: return "ESC";
case 2: return "1";
case 3: return "2";
case 4: return "3";
case 5: return "4";
case 6: return "5";
case 7: return "6";
case 8: return "7";
case 9: return "8";
case 10: return "9";
case 11: return "0";
case 12: return "MINUS";
case 13: return "EQUAL";
case 14: return "BACKSPACE";
case 15: return "TAB";
case 16: return "Q";
case 17: return "W";
case 18: return "E";
case 19: return "R";
case 20: return "T";
case 21: return "Y";
case 22: return "U";
case 23: return "I";
case 24: return "O";
case 25: return "P";
case 26: return "[";
case 27: return "]";
case 28: return "ENTER";
case 29: return "LCTRL";
case 30: return "A";
case 31: return "S";
case 32: return "D";
case 33: return "F";
case 34: return "G";
case 35: return "H";
case 36: return "J";
case 37: return "K";
case 38: return "L";
case 39: return ";";
case 40: return "'";
case 41: return "`";
case 42: return "LSHIFT";
case 43: return "\\";
case 44: return "Z";
case 45: return "X";
case 46: return "C";
case 47: return "V";
case 48: return "B";
case 49: return "N";
case 50: return "M";
case 51: return ",";
case 52: return ".";
case 53: return "/";
case 54: return "RSHIFT";
case 55: return "NUMPAD*";
case 56: return "LALT";
case 57: return "SPACE";
case 58: return "CAPS";
case 69: return "NUMLOCK";
case 70: return "SCROLL";
case 74: return "NUMPAD-";
case 78: return "NUMPAD+";
case 82: return "NUMPAD0";
case 79: return "NUMPAD1";
case 80: return "NUMPAD2";
case 81: return "NUMPAD3";
case 75: return "NUMPAD4";
case 76: return "NUMPAD5";
case 77: return "NUMPAD6";
case 71: return "NUMPAD7";
case 72: return "NUMPAD8";
case 73: return "NUMPAD9";
case 87: return "F11";
case 88: return "F12";
case 157: return "RCTRL";
case 184: return "RALT";
case 200: return "UP";
case 203: return "LEFT";
case 208: return "DOWN";
case 205: return "RIGHT";
case 210: return "INSERT";
case 211: return "DELETE";
case 199: return "HOME";
case 207: return "END";
case 201: return "PAGE UP";
case 209: return "PAGE DOWN";
default:
break;
}
if (key >= 59 && key <= 68) {
return "F" + (key - 58);
}
return "KEY " + key;
}
}
@@ -0,0 +1,314 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
import cn.xiaozhou233.orangex.input.ClientInput;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.modules.ModuleCategory;
import cn.xiaozhou233.orangex.modules.ModuleManager;
import cn.xiaozhou233.orangex.render.api.Render2D;
import cn.xiaozhou233.orangex.ui.clickgui.component.Component;
import cn.xiaozhou233.orangex.value.Value;
import java.util.Collections;
import java.util.List;
/**
* The main ClickGUI window.
*
* <p>A single rounded window with a category sidebar on the left and the
* selected category's modules on the right. Left-clicking a module toggles it;
* right-clicking a module swaps the content area to its settings page, which is
* left with the back button next to the module name. The window itself can be
* dragged by its header.</p>
*
* <p>All coordinates are Minecraft GUI pixels. Input is polled from
* {@link ClientInput} because the empty input screen does not forward
* callbacks to this class directly. This class owns the window state and input
* routing; drawing is delegated to the renderer classes in this package.</p>
*/
public final class MainPanel extends Component {
private static final ModuleCategory[] CATEGORIES = ModuleCategory.values();
/** Pixels scrolled per wheel notch. */
private static final float SCROLL_STEP = 24.0f;
private final ModuleManager moduleManager =
OrangeX.getInstance().getModuleManager();
private final ClickGuiAnimator animator = new ClickGuiAnimator();
private ModuleCategory selectedCategory = ModuleCategory.RENDER;
/** Module whose settings page replaces the list, or {@code null}. */
private Module settingsModule;
private float scrollOffset;
private boolean hasPosition;
private boolean dragging;
private float dragOffsetX;
private float dragOffsetY;
private int screenWidth = 854;
private int screenHeight = 480;
private float categoryRowHeight = ClickGuiStyle.CATEGORY_HEIGHT;
private long lastFrameNanos;
@Override
public void render(EventRender2D event) {
Render2D graphics = event.getRender2D();
updateBounds(graphics);
ClickGuiLayout layout = layout();
applyScroll(layout);
float delta = updateDelta();
double mouseX = ClientInput.getMouseX();
double mouseY = ClientInput.getMouseY();
PanelChrome.drawShadow(graphics, layout);
graphics.fillRoundedRect(layout.x(), layout.y(), layout.width(),
layout.height(), ClickGuiStyle.PANEL_RADIUS, 1.0,
ClickGuiStyle.COLOR_PANEL, ClickGuiStyle.COLOR_BORDER);
PanelChrome.drawHeader(graphics, layout);
SidebarRenderer.draw(graphics, layout, selectedCategory,
moduleManager.getAllModules(), animator, delta, mouseX, mouseY);
if (settingsModule == null) {
ContentRenderer.draw(graphics, layout, contentList(layout),
selectedCategory, animator, delta, mouseX, mouseY);
} else {
SettingsSection.draw(graphics, layout, settingsModule,
settingsOf(), scrollOffset, animator, delta, mouseX, mouseY);
}
}
@Override
public void mouseClicked(float mouseX, float mouseY, int button) {
if (!ClickGuiStyle.isInside(mouseX, mouseY, x, y, width, height)) {
return;
}
if (ClickGuiStyle.isInside(mouseX, mouseY, x, y, width,
ClickGuiStyle.HEADER_HEIGHT)) {
if (button == 0) {
dragging = true;
dragOffsetX = mouseX - x;
dragOffsetY = mouseY - y;
}
return;
}
ClickGuiLayout layout = layout();
ModuleCategory category = categoryAt(layout, mouseX, mouseY);
if (category != null) {
if (category != selectedCategory) {
selectedCategory = category;
}
closeSettings();
return;
}
if (settingsModule != null) {
handleSettingsClick(layout, mouseX, mouseY, button);
return;
}
handleContentClick(layout, mouseX, mouseY, button);
}
@Override
public void mouseDragged(float mouseX, float mouseY, int button) {
if (!dragging || button != 0) {
return;
}
float maxX = Math.max(4.0f, screenWidth - width - 4.0f);
float maxY = Math.max(4.0f, screenHeight - height - 4.0f);
x = ClickGuiStyle.clamp(mouseX - dragOffsetX, 4.0f, maxX);
y = ClickGuiStyle.clamp(mouseY - dragOffsetY, 4.0f, maxY);
// 26.2 glyph blits snap to whole pixels; a fractional panel origin
// makes every glyph round independently while dragging. Keep the
// window on the pixel grid so text moves as one stable block.
x = Math.round(x);
y = Math.round(y);
hasPosition = true;
}
@Override
public void mouseReleased(float mouseX, float mouseY, int button) {
if (button == 0) {
dragging = false;
}
}
public void resetInteraction() {
dragging = false;
closeSettings();
}
/* ------------------------------------------------------------------ */
/* Interaction */
/* ------------------------------------------------------------------ */
private boolean handleContentClick(ClickGuiLayout layout, float mouseX,
float mouseY, int button) {
if (mouseY < layout.listTop() || mouseY > layout.listBottom()) {
return false;
}
if (mouseX < layout.contentX()
|| mouseX > layout.contentX() + layout.contentWidth()) {
return false;
}
ContentList rows = contentList(layout);
int moduleIndex = rows.moduleIndexAt(mouseY);
if (moduleIndex < 0) {
return false;
}
Module module = rows.modules().get(moduleIndex);
if (button == 0) {
module.toggle();
} else if (button == 1 && ClickGuiModules.hasSettings(module)) {
settingsModule = module;
scrollOffset = 0.0f;
}
return true;
}
private boolean handleSettingsClick(ClickGuiLayout layout, float mouseX,
float mouseY, int button) {
if (button == 0 && SettingsSection.isBackButton(layout, mouseX,
mouseY)) {
closeSettings();
return true;
}
List<Value<?>> settings = settingsOf();
int index = SettingsSection.rowIndexAt(layout, settings, scrollOffset,
mouseY);
if (index >= 0) {
SettingsSection.click(settings, index, button);
return true;
}
return false;
}
private void closeSettings() {
settingsModule = null;
scrollOffset = 0.0f;
}
private ModuleCategory categoryAt(ClickGuiLayout layout, float mouseX,
float mouseY) {
float rowX = layout.categoryRowX();
float rowWidth = layout.categoryRowWidth();
float rowY = layout.categoryRowTop();
float rowHeight = layout.categoryRowHeight();
for (ModuleCategory category : CATEGORIES) {
if (ClickGuiStyle.isInside(mouseX, mouseY, rowX, rowY,
rowWidth, rowHeight)) {
return category;
}
rowY += rowHeight + ClickGuiStyle.CATEGORY_GAP;
}
return null;
}
/* ------------------------------------------------------------------ */
/* Layout helpers */
/* ------------------------------------------------------------------ */
private ClickGuiLayout layout() {
return new ClickGuiLayout(x, y, width, height, categoryRowHeight,
screenWidth, screenHeight);
}
private ContentList contentList(ClickGuiLayout layout) {
return new ContentList(layout, modulesOf(selectedCategory),
scrollOffset);
}
private List<Value<?>> settingsOf() {
return settingsModule == null
? Collections.<Value<?>>emptyList()
: ClickGuiModules.settingsOf(settingsModule);
}
/**
* Applies this frame's wheel input to whichever list is visible and keeps
* its offset inside the content.
*/
private void applyScroll(ClickGuiLayout layout) {
double wheel = ClientInput.consumeScroll();
float step = (float) -wheel * SCROLL_STEP;
if (settingsModule != null) {
scrollOffset = ClickGuiStyle.clamp(scrollOffset + step, 0.0f,
SettingsSection.maxScroll(layout, settingsOf()));
return;
}
ContentList rows = contentList(layout);
if (wheel != 0.0) {
rows.scrollBy(step);
}
rows.clampScroll();
scrollOffset = rows.scroll();
}
private void updateBounds(Render2D graphics) {
screenWidth = graphics.getWidth();
screenHeight = graphics.getHeight();
width = Math.min(ClickGuiStyle.DESIGN_WIDTH,
Math.max(280.0f, screenWidth - ClickGuiStyle.MARGIN * 2.0f));
height = Math.min(ClickGuiStyle.DESIGN_HEIGHT,
Math.max(220.0f, screenHeight - ClickGuiStyle.MARGIN * 2.0f));
// Keep all seven category rows inside the sidebar card even when the
// panel is compressed by a small GUI-scaled screen.
float cardHeight = height - ClickGuiStyle.HEADER_HEIGHT - 16.0f;
float availableRows = cardHeight - 18.0f;
float rowHeight = (availableRows
- (CATEGORIES.length - 1) * ClickGuiStyle.CATEGORY_GAP)
/ CATEGORIES.length;
categoryRowHeight = Math.max(12.0f,
Math.min(ClickGuiStyle.CATEGORY_HEIGHT, rowHeight));
if (!hasPosition) {
x = (screenWidth - width) / 2.0f;
y = (screenHeight - height) / 2.0f;
hasPosition = true;
}
x = ClickGuiStyle.clamp(x, 4.0f,
Math.max(4.0f, screenWidth - width - 4.0f));
y = ClickGuiStyle.clamp(y, 4.0f,
Math.max(4.0f, screenHeight - height - 4.0f));
x = Math.round(x);
y = Math.round(y);
}
private float updateDelta() {
long now = System.nanoTime();
if (lastFrameNanos == 0L) {
lastFrameNanos = now;
return 0.016f;
}
float delta = (now - lastFrameNanos) / 1_000_000_000.0f;
lastFrameNanos = now;
return ClickGuiStyle.clamp(delta, 0.0f, 0.1f);
}
private List<Module> modulesOf(ModuleCategory category) {
return moduleManager.getModulesByCategory(category);
}
}
@@ -0,0 +1,48 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.render.api.FontRenderer;
import cn.xiaozhou233.orangex.render.api.Render2D;
/**
* Draws the parts of the window that never change with the selected category:
* the drop shadow and the header.
*/
public final class PanelChrome {
private PanelChrome() {
}
public static void drawShadow(Render2D graphics, ClickGuiLayout layout) {
float x = layout.x();
float y = layout.y();
float width = layout.width();
float height = layout.height();
graphics.fillRoundedRect(x - 4, y + 3, width + 8, height + 6,
ClickGuiStyle.PANEL_RADIUS + 4, 0x1C000000);
graphics.fillRoundedRect(x - 2, y + 1, width + 4, height + 3,
ClickGuiStyle.PANEL_RADIUS + 2, 0x26000000);
}
public static void drawHeader(Render2D graphics, ClickGuiLayout layout) {
float x = layout.x();
float y = layout.y();
float width = layout.width();
FontRenderer logo = ClickGuiStyle.font(graphics, 16.0f, true);
String brand = "Orange";
double brandX = x + 16;
double brandY = y + 9;
logo.drawString(brand, brandX, brandY, ClickGuiStyle.COLOR_TEXT);
logo.drawString("X", brandX + logo.getStringWidth(brand), brandY,
ClickGuiStyle.COLOR_ACCENT);
FontRenderer subtitle = ClickGuiStyle.font(graphics, 7.5f, true);
subtitle.drawString("CLICK GUI", x + 17, y + 28,
ClickGuiStyle.COLOR_TEXT_MUTED);
graphics.fillRect(x + 14, y + ClickGuiStyle.HEADER_HEIGHT - 1,
width - 28, 1, ClickGuiStyle.COLOR_DIVIDER);
}
}
@@ -0,0 +1,217 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.render.api.FontRenderer;
import cn.xiaozhou233.orangex.render.api.Render2D;
import cn.xiaozhou233.orangex.value.BooleanValue;
import cn.xiaozhou233.orangex.value.ModeValue;
import cn.xiaozhou233.orangex.value.Value;
import java.util.List;
/**
* The settings page shown in the content area of {@link MainPanel}.
*
* <p>Opening a module's settings replaces the module list instead of spawning a
* separate window. The page keeps the list's scroll viewport and is left with
* the back button drawn next to the module name.</p>
*/
public final class SettingsSection {
/** Height of one settings row. */
public static final float ROW_HEIGHT = 22f;
private static final float BACK_SIZE = 16f;
private static final float BACK_GAP = 6f;
private static final Object BACK_HOVER_KEY = new Object();
private SettingsSection() {
}
/**
* @return the total height of the rows, which may exceed the visible list.
*/
public static float contentHeight(List<Value<?>> settings) {
return settings.size() * ROW_HEIGHT;
}
public static float maxScroll(ClickGuiLayout layout, List<Value<?>> settings) {
return Math.max(0.0f,
contentHeight(settings)
- (layout.listBottom() - layout.listTop()));
}
public static void draw(Render2D graphics, ClickGuiLayout layout,
Module module, List<Value<?>> settings, float scroll,
ClickGuiAnimator animator, float delta,
double mouseX, double mouseY) {
float contentX = layout.contentX();
float contentWidth = layout.contentWidth();
float headerY = layout.y() + ClickGuiStyle.HEADER_HEIGHT;
drawBackButton(graphics, layout, animator, delta, mouseX, mouseY);
FontRenderer title = ClickGuiStyle.font(graphics, 13.0f, true);
title.drawString(module.getName(),
contentX + BACK_SIZE + BACK_GAP + 4,
headerY + 10, ClickGuiStyle.COLOR_TEXT);
FontRenderer meta = ClickGuiStyle.font(graphics, 8.0f);
String metaText = "SETTINGS";
meta.drawString(metaText,
contentX + contentWidth - meta.getStringWidth(metaText),
headerY + 14, ClickGuiStyle.COLOR_TEXT_MUTED);
graphics.fillRect(contentX, headerY + 30, contentWidth, 1,
ClickGuiStyle.COLOR_DIVIDER);
float listTop = layout.listTop();
float listBottom = layout.listBottom();
graphics.enableScissor(contentX - 2, listTop - 2,
contentWidth + 4, listBottom - listTop + 4);
float rowY = listTop - scroll;
for (Value<?> value : settings) {
if (rowY + ROW_HEIGHT >= listTop && rowY <= listBottom) {
drawRow(graphics, layout, value, rowY, animator, delta,
mouseX, mouseY);
}
rowY += ROW_HEIGHT;
}
graphics.disableScissor();
ClickGuiStyle.drawScrollbar(graphics, contentX + contentWidth - 3,
listTop, listBottom - listTop, contentHeight(settings), scroll);
}
private static void drawBackButton(Render2D graphics, ClickGuiLayout layout,
ClickGuiAnimator animator, float delta,
double mouseX, double mouseY) {
float backX = layout.contentX();
float backY = backTop(layout);
boolean hovered = ClickGuiStyle.isInside(mouseX, mouseY, backX, backY,
BACK_SIZE, BACK_SIZE);
float hover = animator.hover(BACK_HOVER_KEY, hovered, delta);
if (hover > 0.01f) {
graphics.fillRoundedRect(backX, backY, BACK_SIZE, BACK_SIZE, 4,
ClickGuiStyle.argb((int) (22.0f * hover),
ClickGuiStyle.COLOR_ACCENT_RGB));
}
FontRenderer arrow = ClickGuiStyle.font(graphics, 9.0f, true);
arrow.drawCenteredString("<", backX + BACK_SIZE / 2.0,
ClickGuiStyle.centeredY(arrow, backY, BACK_SIZE),
hovered ? ClickGuiStyle.COLOR_ACCENT
: ClickGuiStyle.COLOR_TEXT_MUTED);
}
private static void drawRow(Render2D graphics, ClickGuiLayout layout,
Value<?> value, float rowY,
ClickGuiAnimator animator, float delta,
double mouseX, double mouseY) {
float rowLeft = layout.contentX();
float rowWidth = layout.contentWidth();
boolean hovered = mouseY >= layout.listTop()
&& mouseY <= layout.listBottom()
&& ClickGuiStyle.isInside(mouseX, mouseY, rowLeft, rowY,
rowWidth, ROW_HEIGHT);
float hover = animator.hover(value, hovered, delta);
if (hover > 0.01f) {
graphics.fillRoundedRect(rowLeft, rowY, rowWidth, ROW_HEIGHT, 4,
ClickGuiStyle.argb((int) (10.0f * hover), 0x00FFFFFF));
}
FontRenderer label = ClickGuiStyle.font(graphics, 9.0f);
label.drawString(value.getName(), rowLeft + 8,
ClickGuiStyle.centeredY(label, rowY, ROW_HEIGHT),
ClickGuiStyle.COLOR_TEXT_DIM);
float right = rowLeft + rowWidth - 8;
if (value instanceof BooleanValue) {
BooleanValue booleanValue = (BooleanValue) value;
float toggleWidth = ClickGuiStyle.SMALL_TOGGLE_WIDTH;
float toggleHeight = ClickGuiStyle.SMALL_TOGGLE_HEIGHT;
ClickGuiStyle.drawSwitch(graphics,
right - toggleWidth,
rowY + (ROW_HEIGHT - toggleHeight) / 2.0f,
toggleWidth, toggleHeight,
animator.state(value, booleanValue.isEnabled(), delta));
} else if (value instanceof ModeValue) {
ModeValue modeValue = (ModeValue) value;
FontRenderer modeFont = ClickGuiStyle.font(graphics, 9.0f);
String text = "< " + modeValue.getMode() + " >";
double pillWidth = modeFont.getStringWidth(text) + 10;
double pillX = right - pillWidth;
graphics.fillRoundedRect(pillX, rowY + 4, pillWidth,
ROW_HEIGHT - 8, 4,
ClickGuiStyle.argb(16, 0x00FFFFFF));
modeFont.drawString(text, pillX + 5,
ClickGuiStyle.centeredY(modeFont, rowY, ROW_HEIGHT),
ClickGuiStyle.COLOR_ACCENT);
} else {
FontRenderer valueFont = ClickGuiStyle.font(graphics, 9.0f);
String text = String.valueOf(value.getValue());
valueFont.drawString(text, right - valueFont.getStringWidth(text),
ClickGuiStyle.centeredY(valueFont, rowY, ROW_HEIGHT),
ClickGuiStyle.COLOR_TEXT_MUTED);
}
}
public static boolean isBackButton(ClickGuiLayout layout, double mouseX,
double mouseY) {
return ClickGuiStyle.isInside(mouseX, mouseY, layout.contentX(),
backTop(layout), BACK_SIZE, BACK_SIZE);
}
/**
* @return the index of the settings row under {@code mouseY}, or {@code -1}
* when the pointer is between rows.
*/
public static int rowIndexAt(ClickGuiLayout layout,
List<Value<?>> settings, float scroll,
float mouseY) {
if (mouseY < layout.listTop() || mouseY > layout.listBottom()) {
return -1;
}
float local = mouseY - (layout.listTop() - scroll);
int index = (int) Math.floor(local / ROW_HEIGHT);
return index >= 0 && index < settings.size() ? index : -1;
}
/**
* Applies a click to one settings row. Left-click toggles or advances,
* right-click steps a mode back; other value types are display-only.
*/
public static void click(List<Value<?>> settings, int index, int button) {
if (index < 0 || index >= settings.size()) {
return;
}
if (button != 0 && button != 1) {
return;
}
Value<?> value = settings.get(index);
if (value instanceof BooleanValue) {
if (button == 0) {
((BooleanValue) value).toggle();
}
} else if (value instanceof ModeValue) {
if (button == 0) {
((ModeValue) value).next();
} else {
((ModeValue) value).previous();
}
}
}
private static float backTop(ClickGuiLayout layout) {
return layout.y() + ClickGuiStyle.HEADER_HEIGHT + 8.0f;
}
}
@@ -0,0 +1,86 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.modules.ModuleCategory;
import cn.xiaozhou233.orangex.render.api.FontRenderer;
import cn.xiaozhou233.orangex.render.api.Render2D;
import java.util.List;
/**
* Draws the category card on the left of the ClickGUI window.
*/
public final class SidebarRenderer {
private static final ModuleCategory[] CATEGORIES = ModuleCategory.values();
private SidebarRenderer() {
}
public static void draw(Render2D graphics, ClickGuiLayout layout,
ModuleCategory selectedCategory, List<Module> modules,
ClickGuiAnimator animator, float delta,
double mouseX, double mouseY) {
float x = layout.x();
float y = layout.y();
float cardX = x + ClickGuiStyle.SIDEBAR_CARD_X;
float cardY = y + ClickGuiStyle.SIDEBAR_CARD_Y;
float cardWidth = ClickGuiStyle.SIDEBAR_WIDTH;
float cardHeight = layout.height() - ClickGuiStyle.HEADER_HEIGHT
- 16;
graphics.fillRoundedRect(cardX, cardY, cardWidth, cardHeight, 6,
1.0, ClickGuiStyle.COLOR_SIDEBAR_BG,
ClickGuiStyle.COLOR_SIDEBAR_BORDER);
int[] counts = new int[CATEGORIES.length];
for (Module module : modules) {
counts[module.getCategory().ordinal()]++;
}
float rowX = layout.categoryRowX();
float rowWidth = layout.categoryRowWidth();
float rowY = layout.categoryRowTop();
float rowHeight = layout.categoryRowHeight();
for (ModuleCategory category : CATEGORIES) {
boolean selected = category == selectedCategory;
boolean hovered = ClickGuiStyle.isInside(mouseX, mouseY, rowX, rowY,
rowWidth, rowHeight);
float hover = animator.hover(category, hovered, delta);
if (selected || hover > 0.01f) {
int alpha = selected
? (int) (22.0f + 10.0f * hover)
: (int) (10.0f * hover);
graphics.fillRoundedRect(rowX, rowY, rowWidth, rowHeight, 5,
ClickGuiStyle.argb(alpha,
ClickGuiStyle.COLOR_ACCENT_RGB));
}
if (selected) {
float barHeight = Math.max(4.0f, rowHeight - 12.0f);
graphics.fillRoundedRect(rowX + 3,
rowY + (rowHeight - barHeight) / 2.0f,
2.5f, barHeight, 1.25f, ClickGuiStyle.COLOR_ACCENT);
}
FontRenderer label = ClickGuiStyle.font(graphics, 10.0f, selected);
label.drawString(ClickGuiModules.displayName(category), rowX + 12,
ClickGuiStyle.centeredY(label, rowY, rowHeight),
selected ? ClickGuiStyle.COLOR_TEXT
: ClickGuiStyle.COLOR_TEXT_DIM);
String count = String.valueOf(counts[category.ordinal()]);
FontRenderer countFont = ClickGuiStyle.font(graphics, 8.0f);
countFont.drawString(count,
rowX + rowWidth - 10 - countFont.getStringWidth(count),
ClickGuiStyle.centeredY(countFont, rowY, rowHeight),
selected ? ClickGuiStyle.COLOR_ACCENT
: ClickGuiStyle.COLOR_TEXT_MUTED);
rowY += rowHeight + ClickGuiStyle.CATEGORY_GAP;
}
}
}
@@ -0,0 +1,51 @@
package cn.xiaozhou233.orangex.ui.clickgui.component;
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
public abstract class Component {
protected float x;
protected float y;
protected float width;
protected float height;
protected boolean visible = true;
protected boolean enabled = true;
public abstract void render(EventRender2D event);
public void update() {
}
public void mouseClicked(float mouseX, float mouseY, int button) {
}
public void mouseReleased(float mouseX, float mouseY, int button) {
}
public void mouseDragged(float mouseX, float mouseY, int button) {
}
public void keyTyped(char character, int keyCode) {
}
public void setBounds(
float x,
float y,
float width,
float height
) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public boolean contains(float mouseX, float mouseY) {
return mouseX >= x
&& mouseX <= x + width
&& mouseY >= y
&& mouseY <= y + height;
}
}
@@ -3,6 +3,7 @@ package cn.xiaozhou233.orangex.wrapper;
import cn.xiaozhou233.orangex.mapping.MappingResolver;
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import cn.xiaozhou233.orangex.wrapper.internal.WrapperContext;
import cn.xiaozhou233.orangex.wrapper.internal.WrapperRegistry;
@@ -19,6 +20,17 @@ public final class MinecraftFactory {
new WrapperContext(runtimeInfo, mappingResolver));
}
/**
* Creates the world/camera view that goes with an already created
* {@link Minecraft} wrapper.
*/
public static WorldView createWorld(RuntimeInfo runtimeInfo,
MappingResolver mappingResolver,
Minecraft minecraft) {
return WrapperRegistry.createWorld(
new WrapperContext(runtimeInfo, mappingResolver), minecraft);
}
private MinecraftFactory() {
}
}
@@ -0,0 +1,36 @@
package cn.xiaozhou233.orangex.wrapper.api;
import cn.xiaozhou233.orangex.wrapper.common.WorldSnapshot;
/**
* Cross-version view of the rendered world: camera state and nearby entities.
*
* <p>Implementations read the game every time {@link #snapshot()} is called,
* so the result must only be used for the frame that produced it. Feature
* code (ESP, tracers, ...) should depend on this interface and on the
* {@code wrapper.common} value objects only. The snapshot is intentionally
* unfiltered; features decide which entity kinds they want to use.</p>
*/
public interface WorldView {
/**
* Captures the camera and entity list for the current frame.
*
* @param partialTicks the partial tick the game rendered this frame with,
* taken from {@code EventRender2D}. This is the only
* value that keeps projections aligned with the
* rendered world; {@link Float#NaN} lets the
* implementation resolve one itself.
* @return {@code null} while no level is loaded (title screen, loading).
*/
WorldSnapshot snapshot(float partialTicks);
/**
* @return whether a caller-supplied frame partial tick can be used. NaN and
* out-of-range values are rejected so a misbehaving hook never
* freezes entity interpolation.
*/
static boolean isUsablePartialTick(float partialTicks) {
return partialTicks >= 0.0F && partialTicks <= 1.0F;
}
}
@@ -0,0 +1,37 @@
package cn.xiaozhou233.orangex.wrapper.common;
/**
* Version-independent classification of an entity target.
*
* <p>The wrapper only reports what the game considers the entity to be;
* feature code decides which kinds it wants to render.</p>
*/
public enum EntityKind {
/**
* A player. Use {@link EntityTarget#isLocalPlayer()} to tell the local
* player apart from everyone else.
*/
PLAYER,
/**
* Hostile mobs such as zombies, skeletons, slimes and ghasts.
*/
MONSTER,
/**
* Passive creatures: animals, ambient creatures (bats), water creatures
* and golems.
*/
ANIMAL,
/**
* Villagers and wandering traders.
*/
VILLAGER,
/**
* Anything else: items, projectiles, paintings, experience orbs, ...
*/
OTHER
}
@@ -0,0 +1,104 @@
package cn.xiaozhou233.orangex.wrapper.common;
/**
* Version-independent snapshot of one entity that feature code can render
* (for example an ESP target).
*/
public final class EntityTarget {
private final String name;
private final Vec3 position;
private final double width;
private final double height;
private final float health;
private final float maxHealth;
private final double distance;
private final EntityKind kind;
private final boolean localPlayer;
private final boolean invisible;
public EntityTarget(String name,
Vec3 position,
double width,
double height,
float health,
float maxHealth,
double distance,
EntityKind kind,
boolean localPlayer,
boolean invisible) {
this.name = name;
this.position = position;
this.width = width;
this.height = height;
this.health = health;
this.maxHealth = maxHealth;
this.distance = distance;
this.kind = kind;
this.localPlayer = localPlayer;
this.invisible = invisible;
}
public String getName() {
return name;
}
/**
* Interpolated feet position of the entity.
*/
public Vec3 getPosition() {
return position;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
public float getHealth() {
return health;
}
public float getMaxHealth() {
return maxHealth;
}
/**
* Distance between the entity feet and the camera.
*/
public double getDistance() {
return distance;
}
public EntityKind getKind() {
return kind;
}
/**
* {@code true} when this target is the entity the camera belongs to.
*/
public boolean isLocalPlayer() {
return localPlayer;
}
/**
* {@code true} when the game reports the entity as invisible (invisibility
* potion, spectator, invisible armor stands, ...).
*/
public boolean isInvisible() {
return invisible;
}
@Override
public String toString() {
return "EntityTarget{name='" + name + "', kind=" + kind
+ ", localPlayer=" + localPlayer
+ ", invisible=" + invisible
+ ", position=" + position
+ ", health=" + health + "/" + maxHealth
+ ", distance=" + distance + "}";
}
}
@@ -0,0 +1,81 @@
package cn.xiaozhou233.orangex.wrapper.common;
/**
* Camera-independent perspective projection.
*
* <p>Minecraft treats the perspective FOV as a <em>vertical</em> angle in
* degrees and uses a conventional right-handed view: yaw {@code 0} looks
* towards {@code +Z}, positive yaw turns towards {@code -X}, and positive
* pitch looks down. Both the 1.8.9 and the modern clients share these
* conventions, so the same math works on every version.</p>
*/
public final class Projection {
/**
* Points closer than this are treated as behind the camera. It matches the
* near plane Minecraft uses for its perspective projection.
*/
private static final double NEAR_PLANE = 0.05D;
private static final float DEFAULT_FOV = 70.0F;
public static ScreenPoint project(Vec3 camera,
float yawDegrees,
float pitchDegrees,
float fovDegrees,
int screenWidth,
int screenHeight,
Vec3 point) {
if (camera == null || point == null
|| screenWidth <= 0 || screenHeight <= 0) {
return ScreenPoint.behind();
}
double yaw = Math.toRadians(yawDegrees);
double pitch = Math.toRadians(pitchDegrees);
double sinYaw = Math.sin(yaw);
double cosYaw = Math.cos(yaw);
double sinPitch = Math.sin(pitch);
double cosPitch = Math.cos(pitch);
// Camera basis (camera looks along -forward, forwards is +Z at yaw 0).
double forwardX = -sinYaw * cosPitch;
double forwardY = -sinPitch;
double forwardZ = cosYaw * cosPitch;
double rightX = -cosYaw;
double rightZ = -sinYaw;
double upX = -sinYaw * sinPitch;
double upY = cosPitch;
double upZ = cosYaw * sinPitch;
double dx = point.getX() - camera.getX();
double dy = point.getY() - camera.getY();
double dz = point.getZ() - camera.getZ();
double depth = dx * forwardX + dy * forwardY + dz * forwardZ;
if (depth <= NEAR_PLANE) {
return ScreenPoint.behind();
}
double x = dx * rightX + dz * rightZ;
double y = dx * upX + dy * upY + dz * upZ;
float fov = fovDegrees > 1.0F ? fovDegrees : DEFAULT_FOV;
double tanHalfFov = Math.tan(Math.toRadians(fov) * 0.5D);
double aspect = (double) screenWidth / (double) screenHeight;
double ndcX = x / (depth * tanHalfFov * aspect);
double ndcY = y / (depth * tanHalfFov);
double screenX = (ndcX + 1.0D) * 0.5D * screenWidth;
double screenY = (1.0D - ndcY) * 0.5D * screenHeight;
return new ScreenPoint(screenX, screenY, depth, true);
}
private Projection() {
}
}
@@ -0,0 +1,51 @@
package cn.xiaozhou233.orangex.wrapper.common;
/**
* A world position projected into 2D GUI pixel space.
*
* <p>{@link #isVisible()} is {@code false} when the point is behind the
* camera (or outside the near plane); callers must not draw such a point.</p>
*/
public final class ScreenPoint {
private final double x;
private final double y;
private final double depth;
private final boolean visible;
public ScreenPoint(double x, double y, double depth, boolean visible) {
this.x = x;
this.y = y;
this.depth = depth;
this.visible = visible;
}
public static ScreenPoint behind() {
return new ScreenPoint(0.0D, 0.0D, -1.0D, false);
}
public double getX() {
return x;
}
public double getY() {
return y;
}
/**
* Distance along the camera forward axis.
*/
public double getDepth() {
return depth;
}
public boolean isVisible() {
return visible;
}
@Override
public String toString() {
return "ScreenPoint{x=" + x + ", y=" + y + ", depth=" + depth
+ ", visible=" + visible + "}";
}
}
@@ -0,0 +1,62 @@
package cn.xiaozhou233.orangex.wrapper.common;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* One frame of world data: camera state plus the entity list.
*
* <p>Snapshots are immutable and are produced on the render thread, so the
* partial tick is read only once and every position in this object belongs to
* the same frame. Entries are not filtered by gameplay rules.</p>
*/
public final class WorldSnapshot {
private final Vec3 cameraPosition;
private final float cameraYaw;
private final float cameraPitch;
private final float fieldOfView;
private final List<EntityTarget> targets;
public WorldSnapshot(Vec3 cameraPosition,
float cameraYaw,
float cameraPitch,
float fieldOfView,
List<EntityTarget> targets) {
this.cameraPosition = cameraPosition;
this.cameraYaw = cameraYaw;
this.cameraPitch = cameraPitch;
this.fieldOfView = fieldOfView;
this.targets = Collections.unmodifiableList(
new ArrayList<EntityTarget>(targets));
}
public Vec3 getCameraPosition() {
return cameraPosition;
}
public float getCameraYaw() {
return cameraYaw;
}
public float getCameraPitch() {
return cameraPitch;
}
/**
* Vertical field of view in degrees.
*/
public float getFieldOfView() {
return fieldOfView;
}
public List<EntityTarget> getTargets() {
return targets;
}
public ScreenPoint project(Vec3 worldPoint, int screenWidth, int screenHeight) {
return Projection.project(cameraPosition, cameraYaw, cameraPitch,
fieldOfView, screenWidth, screenHeight, worldPoint);
}
}
@@ -0,0 +1,156 @@
package cn.xiaozhou233.orangex.wrapper.internal;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* Reflective lookup helpers shared by the version-specific wrappers.
*
* <p>This class intentionally knows nothing about Minecraft: version packages
* pass the resolved member names in. Lookups walk the class hierarchy because
* Minecraft frequently declares a member on a base class and stores an
* instance of a subclass.</p>
*/
public final class ReflectionSupport {
public static Field findField(Class<?> type, String name) {
if (type == null || name == null) {
return null;
}
for (Class<?> current = type; current != null; current = current.getSuperclass()) {
try {
Field field = current.getDeclaredField(name);
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
field.setAccessible(true);
return field;
} catch (NoSuchFieldException ignored) {
// Keep walking the superclass chain.
}
}
return null;
}
public static Field requireField(Class<?> type, String name, String ownerName) {
Field field = findField(type, name);
if (field == null) {
throw new IllegalStateException(
"Cannot find field '" + name + "' on " + ownerName);
}
return field;
}
public static Method findMethod(Class<?> type,
String name,
Class<?> returnType,
Class<?>... parameterTypes) {
if (type == null || name == null) {
return null;
}
for (Class<?> current = type; current != null; current = current.getSuperclass()) {
Method[] methods = current.getDeclaredMethods();
for (Method method : methods) {
if (!method.getName().equals(name)
|| Modifier.isStatic(method.getModifiers())
|| !sameParameters(method, parameterTypes)) {
continue;
}
if (returnType != null && !returnType.equals(method.getReturnType())) {
continue;
}
method.setAccessible(true);
return method;
}
}
return null;
}
public static Method requireMethod(Class<?> type,
String name,
Class<?> returnType,
String ownerName,
Class<?>... parameterTypes) {
Method method = findMethod(type, name, returnType, parameterTypes);
if (method == null) {
throw new IllegalStateException(
"Cannot find method '" + name + "' on " + ownerName);
}
return method;
}
public static Object get(Field field, Object target) {
try {
return field.get(target);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Cannot read field '" + field.getName() + "'", e);
}
}
public static double getDouble(Field field, Object target) {
try {
return field.getDouble(target);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Cannot read field '" + field.getName() + "'", e);
}
}
public static float getFloat(Field field, Object target) {
try {
return field.getFloat(target);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Cannot read field '" + field.getName() + "'", e);
}
}
public static int getInt(Field field, Object target) {
try {
return field.getInt(target);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Cannot read field '" + field.getName() + "'", e);
}
}
public static boolean getBoolean(Field field, Object target) {
try {
return field.getBoolean(target);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Cannot read field '" + field.getName() + "'", e);
}
}
public static Object invoke(Method method, Object target, Object... arguments) {
try {
return method.invoke(target, arguments);
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(
"Cannot invoke method '" + method.getName() + "'", e);
}
}
private static boolean sameParameters(Method method, Class<?>[] parameterTypes) {
Class<?>[] actual = method.getParameterTypes();
if (actual.length != parameterTypes.length) {
return false;
}
for (int i = 0; i < actual.length; i++) {
if (!actual[i].equals(parameterTypes[i])) {
return false;
}
}
return true;
}
private ReflectionSupport() {
}
}
@@ -1,6 +1,7 @@
package cn.xiaozhou233.orangex.wrapper.internal;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
/**
* Creates the wrappers for one Minecraft version.
@@ -18,4 +19,9 @@ public interface WrapperProvider {
* Creates the wrapper for {@code net.minecraft.client.Minecraft}.
*/
Minecraft createMinecraft(WrapperContext context);
/**
* Creates the world/camera view backed by the given client instance.
*/
WorldView createWorld(WrapperContext context, Minecraft minecraft);
}
@@ -2,6 +2,7 @@ package cn.xiaozhou233.orangex.wrapper.internal;
import cn.xiaozhou233.orangex.runtime.version.MinecraftVersion;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import cn.xiaozhou233.orangex.wrapper.internal.v1_8_9.V1_8_9WrapperProvider;
import cn.xiaozhou233.orangex.wrapper.internal.v26_2.V26_2WrapperProvider;
@@ -45,6 +46,14 @@ public final class WrapperRegistry {
}
public static Minecraft createMinecraft(WrapperContext context) {
return provider(context).createMinecraft(context);
}
public static WorldView createWorld(WrapperContext context, Minecraft minecraft) {
return provider(context).createWorld(context, minecraft);
}
private static WrapperProvider provider(WrapperContext context) {
MinecraftVersion version = context.getRuntimeInfo().getMinecraftVersion();
WrapperProvider provider = PROVIDERS.get(version);
@@ -53,7 +62,7 @@ public final class WrapperRegistry {
"Unsupported Minecraft version: " + version);
}
return provider.createMinecraft(context);
return provider;
}
private WrapperRegistry() {
@@ -0,0 +1,569 @@
package cn.xiaozhou233.orangex.wrapper.internal.v1_8_9;
import cn.xiaozhou233.orangex.mapping.MappingClass;
import cn.xiaozhou233.orangex.mapping.MappingField;
import cn.xiaozhou233.orangex.mapping.MappingMethod;
import cn.xiaozhou233.orangex.mapping.MappingResolver;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import cn.xiaozhou233.orangex.wrapper.common.EntityKind;
import cn.xiaozhou233.orangex.wrapper.common.EntityTarget;
import cn.xiaozhou233.orangex.wrapper.common.Vec3;
import cn.xiaozhou233.orangex.wrapper.common.WorldSnapshot;
import cn.xiaozhou233.orangex.wrapper.internal.ReflectionSupport;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 1.8.9 implementation of {@link WorldView}.
*
* <p>All names below are MCP (named) names and are translated through the
* active {@link MappingResolver}. The camera math mirrors
* {@code EntityRenderer#orientCamera}: the eye position of the render view
* entity plus an optional third-person offset along the camera forward
* vector.</p>
*/
public final class V1_8_9WorldView implements WorldView {
private static final String MINECRAFT = "net/minecraft/client/Minecraft";
private static final String GAME_SETTINGS = "net/minecraft/client/settings/GameSettings";
private static final String TIMER = "net/minecraft/util/Timer";
private static final String WORLD = "net/minecraft/world/World";
private static final String ENTITY = "net/minecraft/entity/Entity";
private static final String ENTITY_LIVING = "net/minecraft/entity/EntityLivingBase";
private static final String ENTITY_PLAYER = "net/minecraft/entity/player/EntityPlayer";
private static final String ENTITY_MONSTER = "net/minecraft/entity/monster/IMob";
private static final String ENTITY_ANIMAL = "net/minecraft/entity/passive/EntityAnimal";
private static final String ENTITY_AMBIENT = "net/minecraft/entity/passive/EntityAmbientCreature";
private static final String ENTITY_WATER = "net/minecraft/entity/passive/EntityWaterMob";
private static final String ENTITY_GOLEM = "net/minecraft/entity/monster/EntityGolem";
private static final String ENTITY_VILLAGER = "net/minecraft/entity/passive/EntityVillager";
private static final String ENTITY_RENDERER = "net/minecraft/client/renderer/EntityRenderer";
private static final float DEFAULT_FOV = 70.0F;
private static final float DEFAULT_THIRD_PERSON_DISTANCE = 4.0F;
private static final double FIRST_PERSON_OFFSET = 0.1D;
private final MappingResolver resolver;
private final Object minecraft;
private final Field worldField;
private final Field playerField;
private final Field viewEntityField;
private final Field timerField;
private final Field gameSettingsField;
private final Field entityRendererField;
private final String partialTicksName;
private final String loadedEntitiesName;
private final String thirdPersonViewName;
private final String fovSettingName;
private final String fovModifierMethodName;
private final String thirdPersonDistanceName;
private final String thirdPersonDistanceTempName;
private final String[] playerClassNames;
private final String[] monsterClassNames;
private final String[] animalClassNames;
private final String[] villagerClassNames;
private Field partialTicksField;
private boolean partialTicksWarningLogged;
private Field loadedEntitiesField;
private Field thirdPersonViewField;
private Field fovSettingField;
private Field thirdPersonDistanceField;
private Field thirdPersonDistanceTempField;
private Method fovModifierMethod;
private boolean optionalCameraFieldsResolved;
private final Map<Class<?>, EntityAccess> accessCache =
new HashMap<Class<?>, EntityAccess>();
public V1_8_9WorldView(MappingResolver resolver, Minecraft minecraft) {
this.resolver = resolver;
this.minecraft = minecraft.getMinecraft();
Class<?> minecraftClass = this.minecraft.getClass();
MappingClass minecraftMapping = resolver.mapClass(MINECRAFT);
this.worldField = resolveField(minecraftMapping, "theWorld", minecraftClass);
this.playerField = resolveField(minecraftMapping, "thePlayer", minecraftClass);
this.viewEntityField = resolveField(minecraftMapping, "renderViewEntity", minecraftClass);
this.timerField = resolveField(minecraftMapping, "timer", minecraftClass);
this.gameSettingsField = resolveField(minecraftMapping, "gameSettings", minecraftClass);
this.entityRendererField = resolveField(minecraftMapping, "entityRenderer", minecraftClass);
this.partialTicksName = fieldName(TIMER, "renderPartialTicks");
this.loadedEntitiesName = fieldName(WORLD, "loadedEntityList");
this.thirdPersonViewName = fieldName(GAME_SETTINGS, "thirdPersonView");
this.fovSettingName = fieldName(GAME_SETTINGS, "fovSetting");
this.fovModifierMethodName = methodName(
ENTITY_RENDERER, "getFOVModifier", "(FZ)F");
this.thirdPersonDistanceName = optionalFieldName(
ENTITY_RENDERER, "thirdPersonDistance");
this.thirdPersonDistanceTempName = optionalFieldName(
ENTITY_RENDERER, "thirdPersonDistanceTemp");
this.playerClassNames = classNames(ENTITY_PLAYER);
this.monsterClassNames = classNames(ENTITY_MONSTER);
this.animalClassNames = classNames(
ENTITY_ANIMAL, ENTITY_AMBIENT, ENTITY_WATER, ENTITY_GOLEM);
this.villagerClassNames = classNames(ENTITY_VILLAGER);
}
@Override
public WorldSnapshot snapshot(float partialTicks) {
Object world = ReflectionSupport.get(worldField, minecraft);
Object viewEntity = ReflectionSupport.get(viewEntityField, minecraft);
Object localPlayer = ReflectionSupport.get(playerField, minecraft);
if (world == null || viewEntity == null) {
return null;
}
// The render hook hands us the exact value the frame was rendered
// with. Only fall back to the timer when the caller has none, because a
// partial tick of 0 (or a stale one) makes every interpolated position
// advance in 20 Hz steps while the world renders smoothly.
float frameTicks = WorldView.isUsablePartialTick(partialTicks)
? partialTicks : partialTicks();
EntityAccess view = accessFor(viewEntity.getClass());
double eyeX = interpolate(view.posX, view.lastTickPosX, viewEntity, frameTicks);
double eyeY = interpolate(view.posY, view.lastTickPosY, viewEntity, frameTicks)
+ invokeFloat(view.eyeHeight, viewEntity);
double eyeZ = interpolate(view.posZ, view.lastTickPosZ, viewEntity, frameTicks);
float yaw = interpolateAngle(view.rotationYaw, view.prevRotationYaw,
viewEntity, frameTicks);
float pitch = interpolateAngle(view.rotationPitch, view.prevRotationPitch,
viewEntity, frameTicks);
int thirdPerson = thirdPersonView();
float cameraYaw = yaw;
float cameraPitch = pitch;
if (thirdPerson == 2) {
// Front view: the camera sits in front of the player and looks
// back, so both axes are mirrored.
cameraYaw = yaw + 180.0F;
cameraPitch = -pitch;
}
// Third person moves the camera back by the configured distance;
// first person sits 0.1 blocks behind the eye (EntityRenderer).
double cameraOffset = thirdPerson > 0
? thirdPersonDistance(frameTicks)
: FIRST_PERSON_OFFSET;
double yawRadians = Math.toRadians(cameraYaw);
double pitchRadians = Math.toRadians(cameraPitch);
double forwardX = -Math.sin(yawRadians) * Math.cos(pitchRadians);
double forwardY = -Math.sin(pitchRadians);
double forwardZ = Math.cos(yawRadians) * Math.cos(pitchRadians);
double cameraX = eyeX - forwardX * cameraOffset;
double cameraY = eyeY - forwardY * cameraOffset;
double cameraZ = eyeZ - forwardZ * cameraOffset;
float fov = fieldOfView(frameTicks);
List<EntityTarget> targets = collectTargets(
world, localPlayer, cameraX, cameraY, cameraZ, frameTicks);
return new WorldSnapshot(new Vec3(cameraX, cameraY, cameraZ),
cameraYaw, cameraPitch, fov, targets);
}
/**
* Captures every entity in the loaded entity list. No gameplay filtering
* happens here: feature code (for example the ESP module) decides which
* kinds it wants to show.
*/
private List<EntityTarget> collectTargets(Object world,
Object localPlayer,
double cameraX,
double cameraY,
double cameraZ,
float partialTicks) {
List<EntityTarget> targets = new ArrayList<EntityTarget>();
Field entitiesField = loadedEntitiesField(world.getClass());
if (entitiesField == null) {
return targets;
}
Object value = ReflectionSupport.get(entitiesField, world);
if (!(value instanceof List)) {
return targets;
}
for (Object entity : (List<?>) value) {
if (entity == null) {
continue;
}
EntityAccess access = accessFor(entity.getClass());
double x = interpolate(access.posX, access.lastTickPosX, entity, partialTicks);
double y = interpolate(access.posY, access.lastTickPosY, entity, partialTicks);
double z = interpolate(access.posZ, access.lastTickPosZ, entity, partialTicks);
double width = access.width == null ? 0.6D
: ReflectionSupport.getFloat(access.width, entity);
double height = access.height == null ? 1.8D
: ReflectionSupport.getFloat(access.height, entity);
double distance = distance(cameraX, cameraY, cameraZ, x, y, z);
boolean local = entity == localPlayer;
targets.add(new EntityTarget(
String.valueOf(ReflectionSupport.invoke(access.getName, entity)),
new Vec3(x, y, z),
width,
height,
access.getHealth == null ? 0.0F : invokeFloat(access.getHealth, entity),
access.getMaxHealth == null ? 0.0F : invokeFloat(access.getMaxHealth, entity),
distance,
classify(entity.getClass()),
local,
invokeBoolean(access.isInvisible, entity)));
}
return targets;
}
private EntityKind classify(Class<?> entityClass) {
if (matches(entityClass, playerClassNames)) {
return EntityKind.PLAYER;
}
if (matches(entityClass, villagerClassNames)) {
return EntityKind.VILLAGER;
}
if (matches(entityClass, monsterClassNames)) {
return EntityKind.MONSTER;
}
if (matches(entityClass, animalClassNames)) {
return EntityKind.ANIMAL;
}
return EntityKind.OTHER;
}
/**
* Checks the runtime class hierarchy (including interfaces) against a set
* of mapped class names. This avoids loading optional entity classes that
* may not exist on every runtime.
*/
private static boolean matches(Class<?> type, String[] classNames) {
if (type == null) {
return false;
}
String name = type.getName();
for (String className : classNames) {
if (name.equals(className)) {
return true;
}
}
for (Class<?> implemented : type.getInterfaces()) {
if (matches(implemented, classNames)) {
return true;
}
}
return matches(type.getSuperclass(), classNames);
}
private String[] classNames(String... sourceNames) {
String[] names = new String[sourceNames.length];
for (int index = 0; index < sourceNames.length; index++) {
names[index] = resolver.mapClass(sourceNames[index])
.getTargetName().replace('/', '.');
}
return names;
}
private float partialTicks() {
Object timer = ReflectionSupport.get(timerField, minecraft);
if (timer == null) {
return 0.0F;
}
if (partialTicksField == null) {
partialTicksField = ReflectionSupport.findField(
timer.getClass(), partialTicksName);
if (partialTicksField == null && !partialTicksWarningLogged) {
partialTicksWarningLogged = true;
System.err.println("[OrangeX] Cannot read "
+ partialTicksName + " from " + timer.getClass().getName()
+ ": world positions will not interpolate");
}
}
return partialTicksField == null
? 0.0F
: ReflectionSupport.getFloat(partialTicksField, timer);
}
private int thirdPersonView() {
Object settings = ReflectionSupport.get(gameSettingsField, minecraft);
if (settings == null) {
return 0;
}
if (thirdPersonViewField == null) {
thirdPersonViewField = ReflectionSupport.findField(
settings.getClass(), thirdPersonViewName);
}
if (thirdPersonViewField == null) {
return 0;
}
// 1.8.9 stores an int (0/1/2); some 1.8 builds use a boolean flag.
if (thirdPersonViewField.getType() == boolean.class) {
return ReflectionSupport.getBoolean(thirdPersonViewField, settings) ? 1 : 0;
}
return ReflectionSupport.getInt(thirdPersonViewField, settings);
}
private float fieldOfView(float partialTicks) {
Object renderer = ReflectionSupport.get(entityRendererField, minecraft);
if (renderer != null && fovModifierMethod == null) {
fovModifierMethod = ReflectionSupport.findMethod(
renderer.getClass(), fovModifierMethodName,
float.class, float.class, boolean.class);
}
if (fovModifierMethod != null) {
return ((Number) ReflectionSupport.invoke(
fovModifierMethod, renderer, partialTicks, Boolean.TRUE))
.floatValue();
}
Object settings = ReflectionSupport.get(gameSettingsField, minecraft);
if (settings != null) {
if (fovSettingField == null) {
fovSettingField = ReflectionSupport.findField(
settings.getClass(), fovSettingName);
}
if (fovSettingField != null) {
return ReflectionSupport.getFloat(fovSettingField, settings);
}
}
return DEFAULT_FOV;
}
private double thirdPersonDistance(float partialTicks) {
Object renderer = ReflectionSupport.get(entityRendererField, minecraft);
if (renderer == null || !resolveOptionalCameraFields(renderer.getClass())) {
return DEFAULT_THIRD_PERSON_DISTANCE;
}
float previous = thirdPersonDistanceTempField == null
? DEFAULT_THIRD_PERSON_DISTANCE
: ReflectionSupport.getFloat(thirdPersonDistanceTempField, renderer);
float current = thirdPersonDistanceField == null
? DEFAULT_THIRD_PERSON_DISTANCE
: ReflectionSupport.getFloat(thirdPersonDistanceField, renderer);
return previous + (current - previous) * partialTicks;
}
private boolean resolveOptionalCameraFields(Class<?> rendererClass) {
if (optionalCameraFieldsResolved) {
return true;
}
optionalCameraFieldsResolved = true;
if (thirdPersonDistanceName != null) {
thirdPersonDistanceField = ReflectionSupport.findField(
rendererClass, thirdPersonDistanceName);
}
if (thirdPersonDistanceTempName != null) {
thirdPersonDistanceTempField = ReflectionSupport.findField(
rendererClass, thirdPersonDistanceTempName);
}
return thirdPersonDistanceField != null
|| thirdPersonDistanceTempField != null;
}
private Field loadedEntitiesField(Class<?> worldClass) {
if (loadedEntitiesField == null) {
loadedEntitiesField = ReflectionSupport.findField(
worldClass, loadedEntitiesName);
}
return loadedEntitiesField;
}
private EntityAccess accessFor(Class<?> entityClass) {
EntityAccess access = accessCache.get(entityClass);
if (access == null) {
access = new EntityAccess(entityClass);
accessCache.put(entityClass, access);
}
return access;
}
private Field resolveField(MappingClass owner, String name, Class<?> runtimeOwner) {
MappingField mapping = owner.getField(name);
if (mapping == null) {
throw new IllegalStateException(
"No mapping for field '" + name + "' on " + owner.getSourceName());
}
return ReflectionSupport.requireField(
runtimeOwner, mapping.getTargetName(), owner.getSourceName());
}
private String fieldName(String ownerClass, String name) {
MappingClass owner = resolver.mapClass(ownerClass);
MappingField mapping = owner.getField(name);
if (mapping == null) {
throw new IllegalStateException(
"No mapping for field '" + name + "' on " + ownerClass);
}
return mapping.getTargetName();
}
private String optionalFieldName(String ownerClass, String name) {
MappingClass owner = resolver.mapClass(ownerClass);
MappingField mapping = owner.getField(name);
return mapping == null ? null : mapping.getTargetName();
}
private String methodName(String ownerClass, String name, String descriptor) {
MappingClass owner = resolver.mapClass(ownerClass);
MappingMethod mapping = owner.getMethod(name, descriptor);
if (mapping == null) {
throw new IllegalStateException(
"No mapping for method '" + name + descriptor + "' on " + ownerClass);
}
return mapping.getTargetName();
}
private String optionalMethodName(String ownerClass, String name, String descriptor) {
MappingClass owner = resolver.mapClass(ownerClass);
MappingMethod mapping = owner.getMethod(name, descriptor);
return mapping == null ? null : mapping.getTargetName();
}
private static double interpolate(Field current, Field previous,
Object entity, float partialTicks) {
double previousValue = ReflectionSupport.getDouble(previous, entity);
double currentValue = ReflectionSupport.getDouble(current, entity);
return previousValue + (currentValue - previousValue) * partialTicks;
}
private static float interpolateAngle(Field current, Field previous,
Object entity, float partialTicks) {
float previousValue = ReflectionSupport.getFloat(previous, entity);
float currentValue = ReflectionSupport.getFloat(current, entity);
return previousValue + (currentValue - previousValue) * partialTicks;
}
private static float invokeFloat(Method method, Object target) {
return ((Number) ReflectionSupport.invoke(method, target)).floatValue();
}
private static boolean invokeBoolean(Method method, Object target) {
return ((Boolean) ReflectionSupport.invoke(method, target)).booleanValue();
}
private static double distance(double x1, double y1, double z1,
double x2, double y2, double z2) {
double dx = x1 - x2;
double dy = y1 - y2;
double dz = z1 - z2;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
/**
* Per-class reflective member cache for entities. Resolving methods on
* every frame for every player would be needlessly slow.
*/
private final class EntityAccess {
private final Field posX;
private final Field posY;
private final Field posZ;
private final Field lastTickPosX;
private final Field lastTickPosY;
private final Field lastTickPosZ;
private final Field width;
private final Field height;
private final Field rotationYaw;
private final Field rotationPitch;
private final Field prevRotationYaw;
private final Field prevRotationPitch;
private final Method eyeHeight;
private final Method getName;
private final Method getHealth;
private final Method getMaxHealth;
private final Method isInvisible;
private EntityAccess(Class<?> entityClass) {
MappingClass entity = resolver.mapClass(ENTITY);
MappingClass living = resolver.mapClass(ENTITY_LIVING);
this.posX = mappedField(entity, "posX", entityClass);
this.posY = mappedField(entity, "posY", entityClass);
this.posZ = mappedField(entity, "posZ", entityClass);
this.lastTickPosX = mappedField(entity, "lastTickPosX", entityClass);
this.lastTickPosY = mappedField(entity, "lastTickPosY", entityClass);
this.lastTickPosZ = mappedField(entity, "lastTickPosZ", entityClass);
this.rotationYaw = mappedField(entity, "rotationYaw", entityClass);
this.rotationPitch = mappedField(entity, "rotationPitch", entityClass);
this.prevRotationYaw = mappedField(entity, "prevRotationYaw", entityClass);
this.prevRotationPitch = mappedField(entity, "prevRotationPitch", entityClass);
this.width = mappedField(entity, "width", entityClass);
this.height = mappedField(entity, "height", entityClass);
this.eyeHeight = mappedMethod(entity, "getEyeHeight", "()F",
float.class, entityClass);
this.getName = mappedMethod(entity, "getName", "()Ljava/lang/String;",
String.class, entityClass);
this.getHealth = optionalMappedMethod(living, "getHealth", "()F",
float.class, entityClass);
this.getMaxHealth = optionalMappedMethod(living, "getMaxHealth", "()F",
float.class, entityClass);
this.isInvisible = mappedMethod(entity, "isInvisible", "()Z",
boolean.class, entityClass);
}
private Field mappedField(MappingClass owner, String name, Class<?> type) {
MappingField mapping = owner.getField(name);
if (mapping == null) {
throw new IllegalStateException("No mapping for field '" + name
+ "' on " + owner.getSourceName());
}
return ReflectionSupport.requireField(
type, mapping.getTargetName(), owner.getSourceName());
}
private Method mappedMethod(MappingClass owner, String name,
String descriptor, Class<?> returnType,
Class<?> type) {
String target = methodName(owner.getSourceName(), name, descriptor);
return ReflectionSupport.requireMethod(type, target, returnType,
owner.getSourceName(), new Class<?>[0]);
}
private Method optionalMappedMethod(MappingClass owner, String name,
String descriptor, Class<?> returnType,
Class<?> type) {
String target = optionalMethodName(owner.getSourceName(), name, descriptor);
if (target == null) {
return null;
}
return ReflectionSupport.findMethod(type, target, returnType,
new Class<?>[0]);
}
}
}
@@ -1,6 +1,7 @@
package cn.xiaozhou233.orangex.wrapper.internal.v1_8_9;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import cn.xiaozhou233.orangex.wrapper.internal.WrapperContext;
import cn.xiaozhou233.orangex.wrapper.internal.WrapperProvider;
@@ -15,4 +16,9 @@ public final class V1_8_9WrapperProvider implements WrapperProvider {
context.getRuntimeInfo(),
context.getMappingResolver());
}
@Override
public WorldView createWorld(WrapperContext context, Minecraft minecraft) {
return new V1_8_9WorldView(context.getMappingResolver(), minecraft);
}
}
@@ -0,0 +1,405 @@
package cn.xiaozhou233.orangex.wrapper.internal.v26_2;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import cn.xiaozhou233.orangex.wrapper.common.EntityKind;
import cn.xiaozhou233.orangex.wrapper.common.EntityTarget;
import cn.xiaozhou233.orangex.wrapper.common.Vec3;
import cn.xiaozhou233.orangex.wrapper.common.WorldSnapshot;
import cn.xiaozhou233.orangex.wrapper.internal.ReflectionSupport;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 26.2 implementation of {@link WorldView}.
*
* <p>The modern client already exposes an interpolated camera
* ({@code GameRenderer#mainCamera}) and its FOV, so no third-person math is
* needed here. Member names are the Mojang names the runtime uses.</p>
*/
public final class V26_2WorldView implements WorldView {
private static final float DEFAULT_FOV = 70.0F;
private static final String ENTITY_PLAYER =
"net.minecraft.world.entity.player.Player";
private static final String ENTITY_MONSTER =
"net.minecraft.world.entity.monster.Enemy";
private static final String ENTITY_ANIMAL =
"net.minecraft.world.entity.animal.Animal";
private static final String ENTITY_WATER_ANIMAL =
"net.minecraft.world.entity.animal.fish.WaterAnimal";
private static final String ENTITY_AMBIENT =
"net.minecraft.world.entity.ambient.AmbientCreature";
private static final String ENTITY_GOLEM =
"net.minecraft.world.entity.animal.golem.AbstractGolem";
private static final String ENTITY_VILLAGER =
"net.minecraft.world.entity.npc.villager.AbstractVillager";
private static final String[] PLAYER_CLASSES = {ENTITY_PLAYER};
private static final String[] MONSTER_CLASSES = {ENTITY_MONSTER};
private static final String[] ANIMAL_CLASSES = {
ENTITY_ANIMAL, ENTITY_WATER_ANIMAL, ENTITY_AMBIENT, ENTITY_GOLEM
};
private static final String[] VILLAGER_CLASSES = {ENTITY_VILLAGER};
private final Object minecraft;
private final Field levelField;
private final Field playerField;
private final Field gameRendererField;
private Method deltaTrackerMethod;
private Method deltaPartialTickMethod;
private Method mainCameraMethod;
private Method cameraPositionMethod;
private Method cameraXRotMethod;
private Method cameraYRotMethod;
private Method cameraFovMethod;
private boolean entitySourceResolved;
private Method entitiesForRenderingMethod;
private Method getEntitiesMethod;
private Method getAllMethod;
private Method playersMethod;
private final Map<Class<?>, EntityAccess> accessCache =
new HashMap<Class<?>, EntityAccess>();
private final Map<Class<?>, Field[]> vectorFields =
new HashMap<Class<?>, Field[]>();
public V26_2WorldView(Minecraft minecraft) {
this.minecraft = minecraft.getMinecraft();
Class<?> minecraftClass = this.minecraft.getClass();
this.levelField = ReflectionSupport.requireField(
minecraftClass, "level", "net.minecraft.client.Minecraft");
this.playerField = ReflectionSupport.requireField(
minecraftClass, "player", "net.minecraft.client.Minecraft");
this.gameRendererField = ReflectionSupport.requireField(
minecraftClass, "gameRenderer", "net.minecraft.client.Minecraft");
}
@Override
public WorldSnapshot snapshot(float partialTicks) {
Object level = ReflectionSupport.get(levelField, minecraft);
Object localPlayer = ReflectionSupport.get(playerField, minecraft);
Object gameRenderer = ReflectionSupport.get(gameRendererField, minecraft);
if (level == null || gameRenderer == null) {
return null;
}
Object camera = camera(gameRenderer);
if (camera == null) {
return null;
}
// The 26.2 hook extracts the GUI from the game's delta tracker, so it
// supplies no partial tick and the tracker is the authoritative value.
if (!WorldView.isUsablePartialTick(partialTicks)) {
partialTicks = partialTicks();
}
Vec3 cameraPosition = readVec3(
ReflectionSupport.invoke(cameraPositionMethod, camera));
float yaw = invokeFloat(cameraYRotMethod, camera);
float pitch = invokeFloat(cameraXRotMethod, camera);
float fov = invokeFloat(cameraFovMethod, camera);
List<EntityTarget> targets = collectTargets(
level, localPlayer, cameraPosition, partialTicks);
return new WorldSnapshot(cameraPosition, yaw, pitch,
fov > 1.0F ? fov : DEFAULT_FOV, targets);
}
private Object camera(Object gameRenderer) {
if (mainCameraMethod == null) {
mainCameraMethod = ReflectionSupport.findMethod(
gameRenderer.getClass(), "mainCamera", null);
}
if (mainCameraMethod == null) {
return null;
}
Object camera = ReflectionSupport.invoke(mainCameraMethod, gameRenderer);
if (camera == null) {
return null;
}
Class<?> cameraClass = camera.getClass();
if (cameraPositionMethod == null) {
cameraPositionMethod = ReflectionSupport.requireMethod(
cameraClass, "position", null, "net.minecraft.client.Camera");
cameraXRotMethod = ReflectionSupport.requireMethod(
cameraClass, "xRot", float.class, "net.minecraft.client.Camera");
cameraYRotMethod = ReflectionSupport.requireMethod(
cameraClass, "yRot", float.class, "net.minecraft.client.Camera");
cameraFovMethod = ReflectionSupport.requireMethod(
cameraClass, "getFov", float.class, "net.minecraft.client.Camera");
}
return camera;
}
/**
* Captures every entity the level exposes for rendering. No gameplay
* filtering happens here: feature code (for example the ESP module)
* decides which kinds it wants to show.
*/
private List<EntityTarget> collectTargets(Object level,
Object localPlayer,
Vec3 cameraPosition,
float partialTicks) {
List<EntityTarget> targets = new ArrayList<EntityTarget>();
Iterable<?> entities = entities(level);
if (entities == null) {
return targets;
}
for (Object entity : entities) {
if (entity == null) {
continue;
}
EntityAccess access = accessFor(entity.getClass());
Vec3 position = readVec3(ReflectionSupport.invoke(
access.getPosition, entity, Float.valueOf(partialTicks)));
if (position == null) {
continue;
}
boolean local = entity == localPlayer;
targets.add(new EntityTarget(
invokeString(access.getName, entity),
position,
invokeFloat(access.getBbWidth, entity),
invokeFloat(access.getBbHeight, entity),
access.getHealth == null ? 0.0F : invokeFloat(access.getHealth, entity),
access.getMaxHealth == null ? 0.0F : invokeFloat(access.getMaxHealth, entity),
distance(cameraPosition, position),
classify(entity.getClass()),
local,
invokeBoolean(access.isInvisible, entity)));
}
return targets;
}
/**
* Resolves the all-entity source once. Modern clients expose
* {@code Level#entitiesForRendering()}; older/newer builds may instead
* expose {@code Level#getEntities()#getAll()}. {@code players()} stays as
* a last-resort fallback so the overlay keeps working if the level API
* changes again.
*/
private Iterable<?> entities(Object level) {
if (!entitySourceResolved) {
entitySourceResolved = true;
entitiesForRenderingMethod = ReflectionSupport.findMethod(
level.getClass(), "entitiesForRendering", null);
if (entitiesForRenderingMethod == null) {
getEntitiesMethod = ReflectionSupport.findMethod(
level.getClass(), "getEntities", null);
}
if (entitiesForRenderingMethod == null && getEntitiesMethod == null) {
playersMethod = ReflectionSupport.findMethod(
level.getClass(), "players", null);
}
}
if (entitiesForRenderingMethod != null) {
Object value = ReflectionSupport.invoke(entitiesForRenderingMethod, level);
return value instanceof Iterable ? (Iterable<?>) value : null;
}
if (getEntitiesMethod != null) {
Object getter = ReflectionSupport.invoke(getEntitiesMethod, level);
if (getter == null) {
return null;
}
if (getAllMethod == null) {
getAllMethod = ReflectionSupport.findMethod(
getter.getClass(), "getAll", null);
}
if (getAllMethod != null) {
Object value = ReflectionSupport.invoke(getAllMethod, getter);
return value instanceof Iterable ? (Iterable<?>) value : null;
}
return null;
}
if (playersMethod != null) {
Object value = ReflectionSupport.invoke(playersMethod, level);
return value instanceof Iterable ? (Iterable<?>) value : null;
}
return null;
}
private static EntityKind classify(Class<?> entityClass) {
if (matches(entityClass, PLAYER_CLASSES)) {
return EntityKind.PLAYER;
}
if (matches(entityClass, VILLAGER_CLASSES)) {
return EntityKind.VILLAGER;
}
if (matches(entityClass, MONSTER_CLASSES)) {
return EntityKind.MONSTER;
}
if (matches(entityClass, ANIMAL_CLASSES)) {
return EntityKind.ANIMAL;
}
return EntityKind.OTHER;
}
private static boolean matches(Class<?> type, String[] classNames) {
if (type == null) {
return false;
}
String name = type.getName();
for (String className : classNames) {
if (name.equals(className)) {
return true;
}
}
for (Class<?> implemented : type.getInterfaces()) {
if (matches(implemented, classNames)) {
return true;
}
}
return matches(type.getSuperclass(), classNames);
}
private float partialTicks() {
if (deltaTrackerMethod == null) {
deltaTrackerMethod = ReflectionSupport.findMethod(
minecraft.getClass(), "getDeltaTracker", null);
}
if (deltaTrackerMethod == null) {
return 0.0F;
}
Object tracker = ReflectionSupport.invoke(deltaTrackerMethod, minecraft);
if (tracker == null) {
return 0.0F;
}
if (deltaPartialTickMethod == null) {
deltaPartialTickMethod = ReflectionSupport.findMethod(
tracker.getClass(), "getGameTimeDeltaPartialTick", null,
boolean.class);
}
if (deltaPartialTickMethod == null) {
return 0.0F;
}
return invokeFloat(deltaPartialTickMethod, tracker, Boolean.FALSE);
}
private EntityAccess accessFor(Class<?> entityClass) {
EntityAccess access = accessCache.get(entityClass);
if (access == null) {
access = new EntityAccess(entityClass);
accessCache.put(entityClass, access);
}
return access;
}
private Vec3 readVec3(Object nativeVec) {
if (nativeVec == null) {
return null;
}
Class<?> type = nativeVec.getClass();
Field[] fields = vectorFields.get(type);
if (fields == null) {
fields = new Field[]{
ReflectionSupport.requireField(type, "x", type.getName()),
ReflectionSupport.requireField(type, "y", type.getName()),
ReflectionSupport.requireField(type, "z", type.getName())
};
vectorFields.put(type, fields);
}
return new Vec3(
ReflectionSupport.getDouble(fields[0], nativeVec),
ReflectionSupport.getDouble(fields[1], nativeVec),
ReflectionSupport.getDouble(fields[2], nativeVec));
}
private static String invokeString(Method method, Object target) {
Object value = ReflectionSupport.invoke(method, target);
if (value == null) {
return "";
}
Method getString = ReflectionSupport.findMethod(
value.getClass(), "getString", String.class);
if (getString == null) {
return String.valueOf(value);
}
Object text = ReflectionSupport.invoke(getString, value);
return text == null ? "" : String.valueOf(text);
}
private static float invokeFloat(Method method, Object target, Object... arguments) {
return ((Number) ReflectionSupport.invoke(method, target, arguments))
.floatValue();
}
private static boolean invokeBoolean(Method method, Object target) {
return ((Boolean) ReflectionSupport.invoke(method, target)).booleanValue();
}
private static double distance(Vec3 first, Vec3 second) {
return first.distanceTo(second);
}
/**
* Per-class reflective member cache for entities.
*/
private static final class EntityAccess {
private final Method getPosition;
private final Method getName;
private final Method getHealth;
private final Method getMaxHealth;
private final Method getBbWidth;
private final Method getBbHeight;
private final Method isInvisible;
private EntityAccess(Class<?> entityClass) {
this.getPosition = ReflectionSupport.requireMethod(
entityClass, "getPosition", null, entityClass.getName(),
float.class);
this.getName = ReflectionSupport.requireMethod(
entityClass, "getName", null, entityClass.getName());
// Health only exists on LivingEntity, so non-living entities
// (items, arrows, ...) leave these null.
this.getHealth = ReflectionSupport.findMethod(
entityClass, "getHealth", float.class);
this.getMaxHealth = ReflectionSupport.findMethod(
entityClass, "getMaxHealth", float.class);
this.getBbWidth = ReflectionSupport.requireMethod(
entityClass, "getBbWidth", float.class, entityClass.getName());
this.getBbHeight = ReflectionSupport.requireMethod(
entityClass, "getBbHeight", float.class, entityClass.getName());
this.isInvisible = ReflectionSupport.requireMethod(
entityClass, "isInvisible", boolean.class, entityClass.getName());
}
}
}
@@ -1,6 +1,7 @@
package cn.xiaozhou233.orangex.wrapper.internal.v26_2;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import cn.xiaozhou233.orangex.wrapper.internal.WrapperContext;
import cn.xiaozhou233.orangex.wrapper.internal.WrapperProvider;
@@ -12,4 +13,9 @@ public final class V26_2WrapperProvider implements WrapperProvider {
context.getRuntimeInfo(),
context.getMappingResolver());
}
@Override
public WorldView createWorld(WrapperContext context, Minecraft minecraft) {
return new V26_2WorldView(minecraft);
}
}
@@ -30,6 +30,15 @@ public final class Hooks {
Render2DEvents.fire(context, inWorld);
}
/**
* 1.8.9 entry point: the HUD method receives the frame's partial tick, so
* injected code passes it straight through as {@code $1}.
*/
public static void render2d(Object context, boolean inWorld,
float partialTicks) {
Render2DEvents.fire(context, inWorld, partialTicks);
}
public static void render2d(Object context) {
Render2DEvents.fire(context);
}
@@ -14,6 +14,10 @@ public final class Legacy {
return V1_8_9Input.isRepeatEvent();
}
public static void forwardScroll(Object screen) {
V1_8_9Input.forwardScroll(screen);
}
private Legacy() {
}
}
+158 -7
View File
@@ -1,10 +1,161 @@
# OrangeX Client
## 项目重构中, Legacy版本请移步 [OrangeX-Client-Legacy](https://github.com/xiaozhou233/OrangeX-Client-Legacy)
## Project is being refactored, Legacy version please refer to [OrangeX-Client-Legacy](https://github.com/xiaozhou233/OrangeX-Client-Legacy)
![Banner](docs/img/banner2.png)
## 支持注入的版本
| Minecraft Version | Vanilla | Forge | Fabric | Badlion Client | MCP |
|:-----------------:|:-------:|:-----:|:------:|:--------------:|:---:|
| 1.8.9 | ✓ | ✓ | — | ✓ | ✓ |
| 26.2 | ✓ | ✗ | ✓ | — | — |
> [!WARNING]
> **项目重构中 / Under Refactoring**
>
> 当前 `main` 分支为重构版本,项目架构、API 和功能仍在持续调整中,暂不保证向后兼容。
>
> The `main` branch contains the rewritten client. Its architecture, APIs, and features are still evolving and may change without notice.
>
> 旧版本请访问:[OrangeX-Client-Legacy](https://github.com/xiaozhou233/OrangeX-Client-Legacy)
## 项目介绍 | Introduction
OrangeX Client 是一个面向 Minecraft 的注入式辅助客户端
OrangeX Client is an injection-based Minecraft utility client
## 支持的版本 | Compatibility
以下表格列出了目前已验证的 Minecraft 版本与运行环境组合。
| Minecraft Version | Vanilla | Forge | Fabric | Badlion Client | Lunar Client | MCP |
|:-----------------:|:-------:|:-----:|:------:|:--------------:|:------------:|:---:|
| 1.8.9 | ✓ | ✓ | — | ✓ | ✓ | ✓ |
| 26.2 | ✓ | ✗ | ✓ | — | — | — |
**状态说明:**
- ✓ Supported:已支持并验证
- ✗ Unsupported:已验证不支持
- — N/A / Untested:环境不存在或尚未完成测试
> 兼容性信息仅反映已经验证的组合,不代表其他未列出的环境一定不兼容。
## 下载 | Downloads
### Stable Releases
正式发布版本可从 GitHub Releases 获取:
[OrangeX Client Releases](https://github.com/xiaozhou233/OrangeX-Client/releases)
### Development Builds
开发版本由 Jenkins 自动构建并发布:
[Jenkins - OrangeX Client](https://jenkins.xiaozhou233.cn/job/OrangeX-Client/)
> [!NOTE]
> 开发版本可能包含未完成的功能、实验性接口或尚未修复的问题,不建议在生产环境中使用。
## 构建 | Building
### 环境要求 | Requirements
| 环境 | 要求 |
|---|---|
| Java | 25 |
| Network | 需要网络连接以下载构建依赖 |
| Build Tool | Gradle Wrapper(项目自带) |
### 开始构建 | Build
克隆项目后,在项目根目录执行:
```bash
./gradlew packageAll
```
Windows 环境:
```bat
gradlew.bat packageAll
```
> [!IMPORTANT]
> `build` 任务被有意禁用。请使用 `packageAll` 进行完整构建。
>
> The `build` task is intentionally disabled. Use `packageAll` instead.
### 构建产物 | Artifacts
构建完成后,产物将输出到 `out/` 目录。
| 路径 | 说明 |
|---|---|
| `out/injection.zip` | 完整注入包,包含 Loader、OrangeX、原生 DLL 和配置文件 |
| `out/injector.jar` | 图形化注入器,内置 FlatLaf |
| `out/tmp/` | 打包过程中生成的临时文件 |
首次构建时,Gradle 会自动下载所需依赖并保存到 `libraries/` 目录。
如果依赖下载失败,请检查网络连接及代理配置。
## 使用指南 | Usage
### 1. 获取程序
选择以下任意一种方式获取 OrangeX Client:
- [GitHub Releases](https://github.com/xiaozhou233/OrangeX-Client/releases)
- [Jenkins Development Builds](https://jenkins.xiaozhou233.cn/job/OrangeX-Client/)
- 自行构建,参见 [构建指南](#构建--building)
### 2. 启动注入器
```bash
java -jar injector.jar
```
### 4. 执行注入
在图形化注入器中选择目标 Minecraft 进程,并按照界面提示完成注入。
## 开发指南 | Development
### 开发环境 | Requirements
| 环境 | 要求 |
|---------|-------------------------------------------|
| Java | 25 |
| IDE | IntelliJ IDEA 2026.2.3 或更高版本(推荐) |
| Git | 用于版本控制 |
| Network | 需要网络连接 |
### 初始化项目 | Setup
**1. 克隆仓库**
```bash
git clone https://github.com/xiaozhou233/OrangeX-Client.git
cd OrangeX-Client
```
**2. 使用 IntelliJ IDEA 打开项目**
等待 Gradle 同步及依赖下载完成。
**3. 准备 Minecraft 开发环境**
加入项目 QQ 群 1103504356,从群文件下载 `Minecraft1.8.8.zip`。
将压缩包解压到`Minecraft1.8.8/`目录,确保目录中有`src/`和`runtime/`
**4. 开始开发**
根据需要修改对应模块的代码。
**5. 运行客户端**
使用 IntelliJ IDEA 中配置好的运行配置启动 Minecraft 客户端。
![Start Client](docs/img/start-client.png)
## 其他 | Others
- 项目仍处于积极重构阶段,部分功能和接口可能发生变化。
- 欢迎提交 Issue 和 Pull Request。
- 使用过程中遇到问题,可以通过项目 Issue 或 QQ 群反馈。
Binary file not shown.

After

Width:  |  Height:  |  Size: 277 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

+72 -23
View File
@@ -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. 已验证环境
+14 -9
View File
@@ -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 存在时都不响应 |
---