Feat: Add world-only rendering and empty input GUI

Gate EventRender2D on shouldRenderLevel; add cross-version empty input screens toggled with M (1.8.9 generated GuiScreen subclass, 26.2 Screen), ClientInput state and debug overlay; add 26.2 compile stubs; move LWJGL2 jar to libraries.
This commit is contained in:
xiaozhou233 committed 2026-11-07 13:34:52 +08:00
1 parent 715cb0755f
commit cfb0ba4a48
41 files changed
+1974 -19

No files matched your search

+1
View File
@@ -11,6 +11,7 @@
<option value="$PROJECT_DIR$/Injector" />
<option value="$PROJECT_DIR$/Loader" />
<option value="$PROJECT_DIR$/Minecraft1.8.8" />
<option value="$PROJECT_DIR$/Minecraft262Stubs" />
<option value="$PROJECT_DIR$/OrangeX" />
</set>
</option>
+1 -1
View File
@@ -4,7 +4,7 @@
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
<option name="MAIN_CLASS_NAME" value="Start" />
<module name="OrangeX-Client.Minecraft1_8_8.main" />
<option name="VM_PARAMETERS" value="-Djava.library.path=versions\1.8.8\1.8.8-natives -Dorangex.dev=true" />
<option name="VM_PARAMETERS" value="-Djava.library.path=versions\1.8.8\1.8.8-natives -Dorangex.dev=true -Dorangex.debugInput=true" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/Minecraft1.8.8/runtime" />
<method v="2">
<option name="Make" enabled="true" />
+6
View File
@@ -0,0 +1,6 @@
plugins {
id 'java-library'
}
group = 'cn.xiaozhou233.orangex'
version = 'unspecified'
@@ -0,0 +1,11 @@
package com.mojang.blaze3d.platform;
/**
* Compile-time stub only.
*/
public class InputConstants {
public static boolean isKeyDown(Window window, int key) {
return false;
}
}
@@ -0,0 +1,7 @@
package com.mojang.blaze3d.platform;
/**
* Compile-time stub only.
*/
public class Window {
}
@@ -0,0 +1,24 @@
package net.minecraft.client;
import com.mojang.blaze3d.platform.Window;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.multiplayer.ClientLevel;
/**
* Compile-time stub only. Field types matter: they determine the descriptors
* emitted into OrangeX bytecode.
*/
public class Minecraft {
public final Gui gui = null;
public final MouseHandler mouseHandler = null;
public ClientLevel level;
public static Minecraft getInstance() {
return null;
}
public Window getWindow() {
return null;
}
}
@@ -0,0 +1,17 @@
package net.minecraft.client;
import com.mojang.blaze3d.platform.Window;
/**
* Compile-time stub only.
*/
public class MouseHandler {
public double getScaledXPos(Window window) {
return 0.0;
}
public double getScaledYPos(Window window) {
return 0.0;
}
}
@@ -0,0 +1,16 @@
package net.minecraft.client.gui;
import net.minecraft.client.gui.screens.Screen;
/**
* Compile-time stub only.
*/
public class Gui {
public Screen screen() {
return null;
}
public void setScreen(Screen screen) {
}
}
@@ -0,0 +1,7 @@
package net.minecraft.client.gui;
/**
* Compile-time stub only.
*/
public class GuiGraphicsExtractor {
}
@@ -0,0 +1,48 @@
package net.minecraft.client.gui.screens;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.network.chat.Component;
/**
* Compile-time stub only. Declares exactly the members OrangeX overrides or
* calls; the real class comes from the game at runtime.
*/
public abstract class Screen {
protected Screen(Component title) {
}
public void extractBackground(GuiGraphicsExtractor graphics,
int mouseX, int mouseY, float partialTick) {
}
public void extractRenderState(GuiGraphicsExtractor graphics,
int mouseX, int mouseY, float partialTick) {
}
public boolean isPauseScreen() {
return true;
}
public void mouseMoved(double x, double y) {
}
public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
return false;
}
public boolean mouseReleased(MouseButtonEvent event) {
return false;
}
public boolean mouseDragged(MouseButtonEvent event,
double dragX, double dragY) {
return false;
}
public boolean mouseScrolled(double x, double y,
double scrollX, double scrollY) {
return false;
}
}
@@ -0,0 +1,19 @@
package net.minecraft.client.input;
/**
* Compile-time stub only. Mirrors the record accessors used by OrangeX.
*/
public class MouseButtonEvent {
public double x() {
return 0.0;
}
public double y() {
return 0.0;
}
public int button() {
return 0;
}
}
@@ -0,0 +1,8 @@
package net.minecraft.client.multiplayer;
/**
* Compile-time stub only. Used as the type of Minecraft#level so the generated
* field descriptor matches the real client.
*/
public class ClientLevel {
}
@@ -0,0 +1,12 @@
package net.minecraft.network.chat;
/**
* Compile-time stub only. Never packaged; the real 26.2 class is provided by
* the game at runtime.
*/
public interface Component {
static MutableComponent empty() {
return null;
}
}
@@ -0,0 +1,7 @@
package net.minecraft.network.chat;
/**
* Compile-time stub only.
*/
public interface MutableComponent extends Component {
}
+6 -1
View File
@@ -27,7 +27,12 @@ dependencies {
// Legacy OpenGL entry points for the 1.8.9 font backend. This is compile
// only: the 1.8.9 runtime provides its own LWJGL 2, and the 26.2 backend
// never loads these classes.
compileOnly files('../Minecraft1.8.8/runtime/libraries/org/lwjgl/lwjgl/lwjgl/2.9.4-nightly-20150209/lwjgl-2.9.4-nightly-20150209.jar')
compileOnly files('../libraries/lwjgl-2.9.4-nightly-20150209.jar')
// The real 26.2 client jar is Java 25 bytecode and cannot be read by the
// JDK 17 used for this build. These compile-time stubs mirror only the
// members OrangeX touches; the real jar is still the runtime reference.
compileOnly project(':Minecraft262Stubs')
// JuiceAgent is provided at runtime by the agent (see JuiceAgentBridge).
// Do NOT bundle it: Fabric's KnotClassLoader would load a second copy of
@@ -2,6 +2,7 @@ package cn.xiaozhou233.orangex;
import cn.xiaozhou233.orangex.event.impl.EventTickPre;
import cn.xiaozhou233.orangex.hook.HookManager;
import cn.xiaozhou233.orangex.input.InputController;
import cn.xiaozhou233.orangex.mapping.MappingManager;
import cn.xiaozhou233.orangex.render.FontDebugOverlay;
import cn.xiaozhou233.orangex.render.Render2DManager;
@@ -27,6 +28,8 @@ public class OrangeX {
private RuntimeInfo runtimeInfo;
@Getter
private Render2DManager render2DManager;
@Getter
private Minecraft minecraft;
public OrangeX() {
System.out.println("OrangeX <init> start!");
@@ -41,15 +44,15 @@ public class OrangeX {
MappingManager.init(runtimeInfo);
Minecraft minecraft = MinecraftFactory.create(runtimeInfo, MappingManager.getResolver());
this.minecraft = minecraft;
System.out.println(minecraft.getMinecraft());
render2DManager = new Render2DManager(
runtimeInfo, MappingManager.getResolver(), minecraft.getMinecraft());
System.out.println("[OrangeX] Font backend: " + render2DManager.getBackendName());
if (Boolean.getBoolean("orangex.debugFont")) {
eventBus.register(new FontDebugOverlay());
}
eventBus.register(new FontDebugOverlay());
eventBus.register(new InputController(minecraft));
HookManager.getINSTANCE().applyAll();
}
@@ -0,0 +1,124 @@
package cn.xiaozhou233.orangex.event.facade;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.input.ClientInput;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
/**
* Entry point used by injected 1.8.9 {@code GuiScreen} / {@code KeyBinding}
* code.
*
* <p>Every vanilla screen goes through these methods, so each callback first
* checks whether the instance is the empty input screen created by OrangeX.</p>
*/
public final class InputEvents {
/** LWJGL 2 {@code Keyboard.KEY_M}. */
private static final int KEY_M = 50;
private static final boolean DEBUG = Boolean.getBoolean("orangex.debugInput");
private static boolean failureLogged;
private static Minecraft minecraft() {
return OrangeX.getInstance().getMinecraft();
}
private static boolean isOurs(Object screen) {
try {
Minecraft minecraft = minecraft();
return minecraft != null && minecraft.isInputScreenInstance(screen);
} catch (Throwable throwable) {
logFailure(throwable);
return false;
}
}
/**
* Called from {@code KeyBinding#onTick(int)} for every key press while no
* screen is open. This queues the 1.8.9 open; it is applied at the end of
* the tick so the same key event is not also delivered to the new screen.
*/
public static void onKeyPressed(int keyCode) {
if (keyCode != KEY_M) {
return;
}
try {
Minecraft minecraft = minecraft();
if (minecraft == null || minecraft.isScreenOpen()) {
return;
}
boolean inWorld = minecraft.isInWorld();
if (DEBUG) {
System.out.println("[OrangeX] M pressed: inWorld=" + inWorld);
}
if (inWorld) {
ClientInput.requestOpen();
}
} catch (Throwable throwable) {
logFailure(throwable);
}
}
/**
* Called from {@code GuiScreen#keyTyped(char, int)}. This queues the
* 1.8.9 close; it is applied at the end of the tick.
*/
public static boolean onKeyTyped(Object screen, int keyCode) {
if (!isOurs(screen) || keyCode != KEY_M) {
return false;
}
try {
ClientInput.requestClose();
} catch (Throwable throwable) {
logFailure(throwable);
}
return true;
}
public static void onDrawScreen(Object screen, int mouseX, int mouseY) {
if (isOurs(screen)) {
ClientInput.onMouseMove(mouseX, mouseY);
}
}
public static boolean onMouseClicked(Object screen, int mouseX,
int mouseY, int button) {
if (!isOurs(screen)) {
return false;
}
ClientInput.onMouseButton(mouseX, mouseY, button, true);
return true;
}
public static boolean onMouseReleased(Object screen, int mouseX,
int mouseY, int button) {
if (!isOurs(screen)) {
return false;
}
ClientInput.onMouseButton(mouseX, mouseY, button, false);
return true;
}
public static void onMouseDragged(Object screen, int mouseX,
int mouseY, int button) {
if (isOurs(screen)) {
ClientInput.onMouseMove(mouseX, mouseY);
}
}
public static boolean isOurInputScreen(Object screen) {
return isOurs(screen);
}
private static void logFailure(Throwable throwable) {
if (!failureLogged) {
failureLogged = true;
System.err.println("[OrangeX] Input callback failed");
throwable.printStackTrace();
}
}
private InputEvents() {
}
}
@@ -11,11 +11,16 @@ public final class Render2DEvents {
private static boolean failureLogged;
public static void fire(Object platformContext) {
/**
* @param inWorld whether the game is currently rendering a loaded level.
* Modern versions call the GUI extraction on the title
* screen too, so the hook must pass this through.
*/
public static void fire(Object platformContext, boolean inWorld) {
try {
Render2DManager manager = OrangeX.getInstance().getRender2DManager();
if (manager != null) {
manager.fire(platformContext);
manager.fire(platformContext, inWorld);
}
} catch (Throwable throwable) {
if (!failureLogged) {
@@ -26,6 +31,13 @@ public final class Render2DEvents {
}
}
/**
* Legacy entry point for hooks that only run in world (1.8.9 HUD).
*/
public static void fire(Object platformContext) {
fire(platformContext, true);
}
private Render2DEvents() {
}
}
@@ -5,16 +5,30 @@ import cn.xiaozhou233.orangex.render.api.Render2D;
/**
* Fired once per frame while the game collects its GUI. Listeners can queue
* text through {@link #getRender2D()}.
*
* <p>{@link #isInWorld()} mirrors the game's own "should render level" flag.
* 1.8.9 only runs the HUD hook while a world is loaded, but modern versions
* also extract the GUI on the title screen, so listeners must not assume that
* receiving this event means the player is in game.</p>
*/
public class EventRender2D {
private final Render2D render2D;
private final boolean inWorld;
public EventRender2D(Render2D render2D) {
public EventRender2D(Render2D render2D, boolean inWorld) {
this.render2D = render2D;
this.inWorld = inWorld;
}
public Render2D getRender2D() {
return render2D;
}
/**
* {@code true} when the frame is rendered while a level is loaded.
*/
public boolean isInWorld() {
return inWorld;
}
}
@@ -17,6 +17,8 @@ public final class HookManager {
private HookManager() {
register(new TickHook());
register(new Render2DHook());
register(new GuiInputHook());
register(new KeyPressHook());
}
public void register(ClassHook hook) {
@@ -12,14 +12,15 @@ import java.lang.reflect.Method;
* Looking the class up through the system class loader always reaches the
* registered copy.</p>
*/
final class JuiceAgentBridge {
public final class JuiceAgentBridge {
private static final String API_CLASS = "cn.xiaozhou233.juiceagent.api.JuiceAgent";
private static Method getClassBytesByName;
private static Method retransformClassByName;
private static Method defineClass;
static byte[] getClassBytesByName(String className) {
public static byte[] getClassBytesByName(String className) {
init();
try {
@@ -30,7 +31,7 @@ final class JuiceAgentBridge {
}
}
static void retransformClassByName(String className, byte[] bytes) {
public static void retransformClassByName(String className, byte[] bytes) {
init();
try {
@@ -41,6 +42,23 @@ final class JuiceAgentBridge {
}
}
/**
* Defines a new class in {@code loader} through the agent.
*
* <p>{@code ClassLoader#defineClass} is protected and cannot be called
* through reflection on modern JDKs; the native agent invokes it through
* JNI instead.</p>
*/
public static Class<?> defineClass(ClassLoader loader, byte[] bytes) {
init();
try {
return (Class<?>) defineClass.invoke(null, loader, bytes);
} catch (Throwable t) {
throw new IllegalStateException("JuiceAgent.defineClass failed", t);
}
}
private static synchronized void init() {
if (getClassBytesByName != null) {
return;
@@ -51,6 +69,8 @@ final class JuiceAgentBridge {
getClassBytesByName = api.getMethod("getClassBytesByName", String.class);
retransformClassByName = api.getMethod(
"retransformClassByName", String.class, byte[].class, int.class);
defineClass = api.getMethod(
"defineClass", ClassLoader.class, byte[].class);
} catch (Throwable t) {
throw new IllegalStateException("JuiceAgent API is not available", t);
}
@@ -0,0 +1,98 @@
package cn.xiaozhou233.orangex.hook.impl;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.hook.ClassHook;
import cn.xiaozhou233.orangex.mapping.MappingManager;
import cn.xiaozhou233.orangex.mapping.MappingMethod;
import cn.xiaozhou233.orangex.mapping.MappingResolver;
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
import cn.xiaozhou233.orangex.runtime.version.MinecraftVersion;
import javassist.CtClass;
import javassist.CtMethod;
/**
* Forwards 1.8.9 {@code GuiScreen} input to the OrangeX empty input screen.
*
* <p>1.8.9 has no {@code mouseMoved} callback, so the cursor position is
* sampled from {@code drawScreen(int, int, float)} every frame. Clicks are
* taken from the screen's normal mouse pipeline.</p>
*
* <p>26.2 does not need this hook: its input screen overrides the
* {@code Screen} callbacks directly.</p>
*/
public final class GuiInputHook extends ClassHook {
private static final String GUI_SCREEN = "net/minecraft/client/gui/GuiScreen";
private static final RuntimeInfo runtimeInfo =
OrangeX.getInstance().getRuntimeInfo();
private static final MappingResolver resolver = MappingManager.getResolver();
@Override
protected String[] getInjectedClassNames() {
return new String[]{
"cn.xiaozhou233.orangex.event.facade.InputEvents",
"cn.xiaozhou233.orangex.input.internal.v1_8_9.V1_8_9Input"
};
}
@Override
protected String getTargetClass() {
switch (runtimeInfo.getMinecraftVersion()) {
case V1_8_9:
return resolver.mapClass(GUI_SCREEN)
.getTargetName().replace("/", ".");
default:
return null;
}
}
@Override
protected void transform(CtClass ctClass) throws Exception {
if (runtimeInfo.getMinecraftVersion() != MinecraftVersion.V1_8_9) {
return;
}
injectBefore(ctClass, "drawScreen", "(IIF)V",
"InputEvents.onDrawScreen($0, $1, $2);");
injectBefore(ctClass, "mouseClicked", "(III)V",
"if (InputEvents.onMouseClicked($0, $1, $2, $3)) return;");
injectBefore(ctClass, "mouseReleased", "(III)V",
"if (InputEvents.onMouseReleased($0, $1, $2, $3)) return;");
injectBefore(ctClass, "mouseClickMove", "(IIIJ)V",
"InputEvents.onMouseDragged($0, $1, $2, $3);");
// Close with M while the empty screen is open. Repeat events are
// ignored so holding the key does not bounce the screen.
injectBefore(ctClass, "keyTyped", "(CI)V",
"if ($2 == V1_8_9Input.TOGGLE_KEY"
+ " && !V1_8_9Input.isRepeatEvent()"
+ " && InputEvents.onKeyTyped($0, $2)) return;");
// The empty screen is an overlay: it must not pause singleplayer.
injectAfter(ctClass, "doesGuiPauseGame", "()Z",
"if (InputEvents.isOurInputScreen($0)) { $_ = false; }");
}
private void injectBefore(CtClass ctClass, String name,
String descriptor, String code) throws Exception {
CtMethod method = find(ctClass, name, descriptor);
method.insertBefore(code);
}
private void injectAfter(CtClass ctClass, String name,
String descriptor, String code) throws Exception {
CtMethod method = find(ctClass, name, descriptor);
method.insertAfter(code);
}
private CtMethod find(CtClass ctClass, String name, String descriptor)
throws Exception {
MappingMethod mapping = resolver.mapMethod(GUI_SCREEN, name, descriptor);
return ctClass.getMethod(
mapping.getTargetName(), mapping.getTargetDescriptor());
}
}
@@ -0,0 +1,65 @@
package cn.xiaozhou233.orangex.hook.impl;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.hook.ClassHook;
import cn.xiaozhou233.orangex.mapping.MappingManager;
import cn.xiaozhou233.orangex.mapping.MappingMethod;
import cn.xiaozhou233.orangex.mapping.MappingResolver;
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
import cn.xiaozhou233.orangex.runtime.version.MinecraftVersion;
import javassist.CtClass;
import javassist.CtMethod;
/**
* 1.8.9 key-press hook.
*
* <p>{@code KeyBinding#onTick(int)} is called for every key press while no
* screen is open. Using it for the GUI toggle avoids missing a short tap
* between two 20 Hz client ticks.</p>
*/
public final class KeyPressHook extends ClassHook {
private static final String KEY_BINDING =
"net/minecraft/client/settings/KeyBinding";
private static final RuntimeInfo runtimeInfo =
OrangeX.getInstance().getRuntimeInfo();
private static final MappingResolver resolver = MappingManager.getResolver();
@Override
protected String[] getInjectedClassNames() {
return new String[]{
"cn.xiaozhou233.orangex.event.facade.InputEvents",
"cn.xiaozhou233.orangex.input.internal.v1_8_9.V1_8_9Input"
};
}
@Override
protected String getTargetClass() {
switch (runtimeInfo.getMinecraftVersion()) {
case V1_8_9:
return resolver.mapClass(KEY_BINDING)
.getTargetName().replace("/", ".");
default:
return null;
}
}
@Override
protected void transform(CtClass ctClass) throws Exception {
if (runtimeInfo.getMinecraftVersion() != MinecraftVersion.V1_8_9) {
return;
}
MappingMethod mapping = resolver.mapMethod(
KEY_BINDING, "onTick", "(I)V");
CtMethod method = ctClass.getMethod(
mapping.getTargetName(), mapping.getTargetDescriptor());
// Static method: $1 is the key code. Ignore auto-repeat so holding
// M does not toggle repeatedly.
method.insertBefore(
"if ($1 == V1_8_9Input.TOGGLE_KEY"
+ " && !V1_8_9Input.isRepeatEvent())"
+ " { InputEvents.onKeyPressed($1); }");
}
}
@@ -16,10 +16,14 @@ import java.lang.reflect.Modifier;
* Fires {@link cn.xiaozhou233.orangex.event.impl.EventRender2D} once per frame.
*
* <ul>
* <li>1.8.9: tail of {@code GuiIngame#renderGameOverlay(float)}.</li>
* <li>1.8.9: tail of {@code GuiIngame#renderGameOverlay(float)}. This method
* is only called while a level is loaded, so the overlay is world-only
* by construction.</li>
* <li>26.2: tail of {@code Gui#extractRenderState(DeltaTracker, boolean,
* boolean)}. The {@code Gui} instance is passed to the facade so the
* font backend can reach its {@code GuiRenderState}.</li>
* font backend can reach its {@code GuiRenderState}; the second
* argument ({@code shouldRenderLevel}) tells the manager whether a
* level is loaded, because this method also runs on the title screen.</li>
* </ul>
*/
public final class Render2DHook extends ClassHook {
@@ -104,7 +108,7 @@ public final class Render2DHook extends ClassHook {
throw new IllegalStateException(
"No (F)V HUD method found in " + ctClass.getName());
}
method.insertAfter("Render2DEvents.fire(null);");
method.insertAfter("Render2DEvents.fire(null, true);");
return;
} else {
MappingMethod target = resolver.mapMethod(
@@ -115,7 +119,7 @@ public final class Render2DHook extends ClassHook {
methodDescriptor = target.getTargetDescriptor();
}
CtMethod method = ctClass.getMethod(methodName, methodDescriptor);
method.insertAfter("Render2DEvents.fire(null);");
method.insertAfter("Render2DEvents.fire(null, true);");
break;
}
case V26_2: {
@@ -125,7 +129,10 @@ public final class Render2DHook extends ClassHook {
"(Lnet/minecraft/client/DeltaTracker;ZZ)V");
CtMethod method = ctClass.getMethod(
target.getTargetName(), target.getTargetDescriptor());
method.insertAfter("Render2DEvents.fire($0);");
// $0 is this, $1 is the DeltaTracker, $2 is shouldRenderLevel:
// false on the title screen, true while a level (including its
// pause/ClickGUI screens) exists.
method.insertAfter("Render2DEvents.fire($0, $2);");
break;
}
default:
@@ -0,0 +1,176 @@
package cn.xiaozhou233.orangex.input;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
/**
* Cross-version GUI input state.
*
* <p>While the empty screen is open the game stops sending mouse and keyboard
* input to the player. The screen itself forwards cursor and button events
* here, and feature code can poll this class from {@code EventRender2D} to
* draw hover effects, cursors, ClickGUI panels, etc.</p>
*
* <p>Coordinates are Minecraft GUI pixels (the same space as
* {@code Render2D}).</p>
*/
public final class ClientInput {
/**
* GUI toggle key. The actual key code is version-specific and is handled
* by {@code VersionInput}; this is only for documentation.
*/
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 boolean toggleWasDown;
private static boolean started;
private static boolean pendingOpen;
private static boolean pendingClose;
private ClientInput() {
}
/**
* Called once per client tick by {@link InputController}.
*/
public static void tick(Minecraft minecraft) {
if (!started) {
started = true;
System.out.println("[OrangeX] Input controller active");
}
boolean screenOpen = minecraft.isInputScreenOpen();
if (open && !screenOpen) {
reset();
} else if (!open && screenOpen) {
onScreenOpened(minecraft.getGuiMouseX(), minecraft.getGuiMouseY());
}
boolean down = minecraft.isToggleKeyDown();
if (minecraft.isToggleEventDriven()) {
// 1.8.9 opens from KeyBinding#onTick (pendingOpen). Closing is
// polled here and applied at the end of the tick so the same key
// event is not also delivered to the freshly opened screen.
if (open && down && !toggleWasDown) {
pendingClose = true;
}
} else if (down && !toggleWasDown) {
// 26.2: no injected Screen subclass key handling, so opening /
// closing here cannot bounce.
if (open) {
minecraft.closeInputScreen();
} else if (minecraft.isInWorld() && !minecraft.isScreenOpen()) {
minecraft.openInputScreen();
}
}
toggleWasDown = down;
}
/**
* Applies a queued 1.8.9 toggle after the tick's keyboard/mouse handling.
*/
public static void applyPending(Minecraft minecraft) {
if (pendingOpen) {
pendingOpen = false;
if (!open && minecraft.isInWorld() && !minecraft.isScreenOpen()) {
minecraft.openInputScreen();
// The key event that opened the screen is still held down.
toggleWasDown = true;
}
}
if (pendingClose) {
pendingClose = false;
if (open) {
minecraft.closeInputScreen();
toggleWasDown = true;
}
}
}
public static void requestOpen() {
pendingOpen = true;
}
public static void requestClose() {
pendingClose = true;
}
public static void onMouseMove(double x, double y) {
mouseX = x;
mouseY = y;
}
/**
* Marks the GUI as open immediately, without waiting for the next tick.
*/
public static void onScreenOpened(double x, double y) {
open = true;
mouseX = x;
mouseY = y;
toggleWasDown = true;
System.out.println("[OrangeX] Input screen opened");
}
public static void onMouseButton(double x, double y, int button, boolean pressed) {
mouseX = x;
mouseY = y;
switch (button) {
case 0:
leftDown = pressed;
break;
case 1:
rightDown = pressed;
break;
case 2:
middleDown = pressed;
break;
default:
break;
}
}
public static void reset() {
if (open) {
System.out.println("[OrangeX] Input screen closed");
}
open = false;
leftDown = false;
rightDown = false;
middleDown = false;
}
public static boolean isOpen() {
return open;
}
public static double getMouseX() {
return mouseX;
}
public static double getMouseY() {
return mouseY;
}
public static boolean isLeftDown() {
return leftDown;
}
public static boolean isRightDown() {
return rightDown;
}
public static boolean isMiddleDown() {
return middleDown;
}
}
@@ -0,0 +1,46 @@
package cn.xiaozhou233.orangex.input;
import cn.xiaozhou233.orangex.event.impl.EventTickPost;
import cn.xiaozhou233.orangex.event.impl.EventTickPre;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
/**
* Drives {@link ClientInput} from the game tick.
*/
public final class InputController {
private final Minecraft minecraft;
private boolean failureLogged;
public InputController(Minecraft minecraft) {
this.minecraft = minecraft;
}
@Subscribe(threadMode = ThreadMode.POSTING)
public void onTick(EventTickPre event) {
try {
ClientInput.tick(minecraft);
} catch (Throwable throwable) {
logFailure(throwable);
}
}
@Subscribe(threadMode = ThreadMode.POSTING)
public void onTickPost(EventTickPost event) {
try {
ClientInput.applyPending(minecraft);
} catch (Throwable throwable) {
logFailure(throwable);
}
}
private void logFailure(Throwable throwable) {
if (!failureLogged) {
failureLogged = true;
System.err.println("[OrangeX] Input tick failed");
throwable.printStackTrace();
}
}
}
@@ -0,0 +1,54 @@
package cn.xiaozhou233.orangex.input.internal;
/**
* Version-specific implementation of the input screen and the cursor helpers.
*
* <p>Implementations live in version packages and may reference that
* version's classes directly. They are loaded lazily through
* {@link cn.xiaozhou233.orangex.wrapper.api.Minecraft} so that a 1.8.9 runtime
* never loads 26.2 classes and vice versa.</p>
*/
public interface VersionInput {
boolean isInWorld();
/**
* {@code true} when our own empty screen is the current Minecraft screen.
*/
boolean isInputScreenOpen();
/**
* {@code true} when any Minecraft screen is open, including vanilla ones.
*/
boolean isScreenOpen();
/**
* Identity check used by injected 1.8.9 code, which runs for every
* {@code GuiScreen} instance.
*/
boolean isInputScreenInstance(Object screen);
/**
* Opens the empty screen. On both versions this releases the mouse and
* stops keyboard / mouse input from reaching the player.
*/
void openInputScreen();
void closeInputScreen();
/**
* M: {@code Keyboard.KEY_M} on 1.8.9, GLFW 77 on 26.2.
*/
boolean isToggleKeyDown();
/**
* {@code true} when opening/closing is driven by injected key events
* instead of polling {@link #isToggleKeyDown()} once per tick. 1.8.9 uses
* this so a very short key tap is not missed between ticks.
*/
boolean isToggleEventDriven();
double getGuiMouseX();
double getGuiMouseY();
}
@@ -0,0 +1,315 @@
package cn.xiaozhou233.orangex.input.internal.v1_8_9;
import cn.xiaozhou233.orangex.hook.JuiceAgentBridge;
import cn.xiaozhou233.orangex.input.ClientInput;
import cn.xiaozhou233.orangex.input.internal.VersionInput;
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.runtime.RuntimeInfo;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.LoaderClassPath;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import java.io.ByteArrayInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* 1.8.9 input screen.
*
* <p>{@code GuiScreen} is abstract in 1.8.9, so a concrete empty subclass is
* generated at runtime and defined into the game class loader. Opening it via
* {@code Minecraft#displayGuiScreen} calls {@code setIngameNotInFocus()},
* which ungrabs the cursor, and while {@code currentScreen != null} the
* player's mouse and keyboard input is not processed.</p>
*
* <p>This class imports LWJGL 2 directly and is therefore loaded only on
* 1.8.9 through a reflective factory in the wrapper.</p>
*/
public final class V1_8_9Input implements VersionInput {
/** LWJGL 2 {@code Keyboard.KEY_M}. */
public static final int TOGGLE_KEY = Keyboard.KEY_M;
private static final String MINECRAFT_CLASS = "net/minecraft/client/Minecraft";
private static final String GUI_SCREEN_CLASS = "net/minecraft/client/gui/GuiScreen";
private static final String GENERATED_SCREEN =
"cn.xiaozhou233.orangex.input.internal.v1_8_9.GeneratedInputScreen";
private final Object minecraft;
private final ClassLoader loader;
private final Class<?> guiScreenClass;
private final Field currentScreenField;
private final Field worldField;
private final Field screenWidthField;
private final Field screenHeightField;
private final Method displayGuiScreen;
private Object shellScreen;
private Class<?> inputScreenClass;
public V1_8_9Input(RuntimeInfo runtimeInfo,
MappingResolver resolver,
Object minecraft) {
this.minecraft = minecraft;
MappingClass minecraftMapping = resolver.mapClass(MINECRAFT_CLASS);
MappingClass guiScreenMapping = resolver.mapClass(GUI_SCREEN_CLASS);
ClassLoader loader = runtimeInfo.getMinecraftClassLoader();
this.loader = loader;
Class<?> minecraftClass = loadClass(
minecraftMapping.getTargetName(), loader);
this.guiScreenClass = loadClass(
guiScreenMapping.getTargetName(), loader);
this.currentScreenField = findField(
minecraftClass,
minecraftMapping.getField("currentScreen").getTargetName());
this.worldField = findField(
minecraftClass,
minecraftMapping.getField("theWorld").getTargetName());
this.screenWidthField = findField(
guiScreenClass,
guiScreenMapping.getField("width").getTargetName());
this.screenHeightField = findField(
guiScreenClass,
guiScreenMapping.getField("height").getTargetName());
MappingMethod displayMapping = resolver.mapMethod(
MINECRAFT_CLASS,
"displayGuiScreen",
"(Lnet/minecraft/client/gui/GuiScreen;)V");
this.displayGuiScreen = findDisplayGuiScreen(
minecraftClass, displayMapping.getTargetName());
}
private static Class<?> loadClass(String internalName, ClassLoader loader) {
try {
return Class.forName(
internalName.replace('/', '.'), false, loader);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(
"Cannot load " + internalName, e);
}
}
private static Field findField(Class<?> owner, String name) {
for (Class<?> current = owner; current != null; current = current.getSuperclass()) {
try {
Field field = current.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException ignored) {
// Continue with the superclass.
}
}
throw new IllegalStateException(
"Cannot find field '" + name + "' on " + owner.getName());
}
private Method findDisplayGuiScreen(Class<?> minecraftClass, String name) {
for (Method method : minecraftClass.getDeclaredMethods()) {
if (!method.getName().equals(name)
|| method.getParameterTypes().length != 1
|| Modifier.isStatic(method.getModifiers())) {
continue;
}
if (method.getParameterTypes()[0].isAssignableFrom(guiScreenClass)) {
method.setAccessible(true);
return method;
}
}
try {
Method method = minecraftClass.getDeclaredMethod(name, guiScreenClass);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException e) {
throw new IllegalStateException(
"Cannot find displayGuiScreen on " + minecraftClass.getName(), e);
}
}
@Override
public boolean isInWorld() {
try {
return worldField.get(minecraft) != null;
} catch (IllegalAccessException e) {
throw new IllegalStateException("Cannot read the world field", e);
}
}
@Override
public boolean isInputScreenOpen() {
if (shellScreen == null) {
return false;
}
try {
return currentScreenField.get(minecraft) == shellScreen;
} catch (IllegalAccessException e) {
throw new IllegalStateException("Cannot read the current screen", e);
}
}
@Override
public boolean isScreenOpen() {
try {
return currentScreenField.get(minecraft) != null;
} catch (IllegalAccessException e) {
throw new IllegalStateException("Cannot read the current screen", e);
}
}
@Override
public boolean isInputScreenInstance(Object screen) {
return shellScreen != null && shellScreen == screen;
}
@Override
public void openInputScreen() {
if (isInputScreenOpen()) {
return;
}
try {
Object screen = inputScreenClass().getDeclaredConstructor().newInstance();
shellScreen = screen;
displayGuiScreen.invoke(minecraft, screen);
ClientInput.onScreenOpened(getGuiMouseX(), getGuiMouseY());
} catch (ReflectiveOperationException e) {
shellScreen = null;
throw new IllegalStateException("Cannot open the 1.8.9 input screen", e);
}
}
/**
* {@code GuiScreen} is abstract in 1.8.9, so generate a concrete empty
* subclass at runtime and define it into the game class loader. Doing it
* with bytecode avoids hardcoding obfuscated class names.
*/
private synchronized Class<?> inputScreenClass() {
if (inputScreenClass != null) {
return inputScreenClass;
}
try {
ClassPool pool = new ClassPool(true);
pool.appendClassPath(new LoaderClassPath(loader));
CtClass base;
try {
base = pool.get(guiScreenClass.getName());
} catch (Throwable notFound) {
// Some launch environments hide transformed class resources;
// fall back to the bytes the agent can read for the loaded class.
byte[] baseBytes = JuiceAgentBridge.getClassBytesByName(
guiScreenClass.getName().replace('.', '/'));
if (baseBytes == null) {
throw new IllegalStateException(
"Cannot load " + guiScreenClass.getName(), notFound);
}
base = pool.makeClass(new ByteArrayInputStream(baseBytes));
}
CtClass generated = pool.makeClass(GENERATED_SCREEN);
generated.setModifiers(Modifier.PUBLIC);
generated.setSuperclass(base);
CtConstructor constructor = new CtConstructor(new CtClass[0], generated);
constructor.setModifiers(Modifier.PUBLIC);
constructor.setBody("super();");
generated.addConstructor(constructor);
byte[] bytes;
try {
bytes = generated.toBytecode();
} finally {
generated.detach();
base.detach();
}
Class<?> defined = JuiceAgentBridge.defineClass(loader, bytes);
if (defined == null) {
throw new IllegalStateException(
"JuiceAgent.defineClass returned null");
}
inputScreenClass = defined;
return inputScreenClass;
} catch (Throwable throwable) {
throw new IllegalStateException(
"Cannot generate the 1.8.9 input screen", throwable);
}
}
@Override
public void closeInputScreen() {
if (!isInputScreenOpen()) {
shellScreen = null;
ClientInput.reset();
return;
}
try {
displayGuiScreen.invoke(minecraft, new Object[]{null});
shellScreen = null;
ClientInput.reset();
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Cannot close the 1.8.9 input screen", e);
}
}
@Override
public boolean isToggleKeyDown() {
return Keyboard.isKeyDown(TOGGLE_KEY);
}
@Override
public boolean isToggleEventDriven() {
return true;
}
/**
* Used by injected {@code GuiScreen}/{@code KeyBinding} code to ignore
* LWJGL auto-repeat events.
*/
public static boolean isRepeatEvent() {
return Keyboard.isRepeatEvent();
}
@Override
public double getGuiMouseX() {
Object screen = shellScreen;
if (screen == null) {
return 0.0;
}
try {
int width = screenWidthField.getInt(screen);
return (double) Mouse.getX() * (double) width / (double) Display.getWidth();
} catch (IllegalAccessException e) {
throw new IllegalStateException("Cannot read the GUI width", e);
}
}
@Override
public double getGuiMouseY() {
Object screen = shellScreen;
if (screen == null) {
return 0.0;
}
try {
int height = screenHeightField.getInt(screen);
return (double) height
- (double) Mouse.getY() * (double) height / (double) Display.getHeight()
- 1.0;
} catch (IllegalAccessException e) {
throw new IllegalStateException("Cannot read the GUI height", e);
}
}
}
@@ -0,0 +1,90 @@
package cn.xiaozhou233.orangex.input.v26_2;
import cn.xiaozhou233.orangex.input.ClientInput;
import cn.xiaozhou233.orangex.input.internal.VersionInput;
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
import com.mojang.blaze3d.platform.InputConstants;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
/**
* 26.2 input implementation.
*
* <p>Loaded reflectively only on 26.2; the wrapper keeps 1.8.9 runtimes free
* of these references.</p>
*/
public final class V26_2Input implements VersionInput {
/** GLFW_KEY_M. */
private static final int TOGGLE_KEY = 77;
private final Minecraft minecraft;
private Screen shellScreen;
public V26_2Input(RuntimeInfo runtimeInfo, Object minecraft) {
this.minecraft = (Minecraft) minecraft;
}
@Override
public boolean isInWorld() {
return minecraft.level != null;
}
@Override
public boolean isInputScreenOpen() {
return shellScreen != null && minecraft.gui.screen() == shellScreen;
}
@Override
public boolean isScreenOpen() {
return minecraft.gui.screen() != null;
}
@Override
public boolean isInputScreenInstance(Object screen) {
return shellScreen != null && shellScreen == screen;
}
@Override
public void openInputScreen() {
if (isInputScreenOpen()) {
return;
}
shellScreen = new V26_2InputScreen();
minecraft.gui.setScreen(shellScreen);
ClientInput.onScreenOpened(getGuiMouseX(), getGuiMouseY());
}
@Override
public void closeInputScreen() {
if (!isInputScreenOpen()) {
shellScreen = null;
ClientInput.reset();
return;
}
minecraft.gui.setScreen(null);
shellScreen = null;
ClientInput.reset();
}
@Override
public boolean isToggleKeyDown() {
return InputConstants.isKeyDown(minecraft.getWindow(), TOGGLE_KEY);
}
@Override
public boolean isToggleEventDriven() {
return false;
}
@Override
public double getGuiMouseX() {
return minecraft.mouseHandler.getScaledXPos(minecraft.getWindow());
}
@Override
public double getGuiMouseY() {
return minecraft.mouseHandler.getScaledYPos(minecraft.getWindow());
}
}
@@ -0,0 +1,69 @@
package cn.xiaozhou233.orangex.input.v26_2;
import cn.xiaozhou233.orangex.input.ClientInput;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.network.chat.Component;
/**
* Empty input screen for 26.2.
*
* <p>The client GUI is still rendered by the HUD hook; this screen only exists
* to move the game into its "screen open" state. Doing so makes
* {@code Gui#setScreen} release the mouse and clear key mappings, and routes
* mouse events to this instance instead of the player.</p>
*/
public final class V26_2InputScreen extends Screen {
public V26_2InputScreen() {
super(Component.empty());
}
@Override
public void extractBackground(GuiGraphicsExtractor graphics,
int mouseX, int mouseY, float partialTick) {
// No blur, panorama, menu texture or dim layer.
}
@Override
public void extractRenderState(GuiGraphicsExtractor graphics,
int mouseX, int mouseY, float partialTick) {
// Drawn by the HUD hook instead.
}
@Override
public boolean isPauseScreen() {
return false;
}
@Override
public void mouseMoved(double x, double y) {
ClientInput.onMouseMove(x, y);
}
@Override
public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
ClientInput.onMouseButton(event.x(), event.y(), event.button(), true);
return true;
}
@Override
public boolean mouseReleased(MouseButtonEvent event) {
ClientInput.onMouseButton(event.x(), event.y(), event.button(), false);
return true;
}
@Override
public boolean mouseDragged(MouseButtonEvent event, double dragX, double dragY) {
ClientInput.onMouseMove(event.x(), event.y());
return true;
}
@Override
public boolean mouseScrolled(double x, double y,
double scrollX, double scrollY) {
ClientInput.onMouseMove(x, y);
return true;
}
}
@@ -1,6 +1,7 @@
package cn.xiaozhou233.orangex.render;
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
import cn.xiaozhou233.orangex.input.ClientInput;
import cn.xiaozhou233.orangex.render.api.FontRenderer;
import cn.xiaozhou233.orangex.render.api.Render2D;
import org.greenrobot.eventbus.Subscribe;
@@ -29,11 +30,23 @@ public final class FontDebugOverlay {
8, 26, 0xFF55FFFF);
body.drawString("ASCII 0123456789", 8, 40, 0xFFAAAAAA);
body.drawString("中文测试:钻石剑 / 迅捷", 8, 54, 0xFFFFAA00);
body.drawString("Input: " + (ClientInput.isOpen() ? "OPEN" : "closed")
+ " mouse " + (int) ClientInput.getMouseX()
+ ", " + (int) ClientInput.getMouseY(),
8, 68, 0xFF55FF55);
body.drawString("M: toggle input screen", 8, 82, 0xFF888888);
// Large high-contrast marker: if this is invisible too, the problem is
// GL state/coordinates rather than the glyph atlas.
FontRenderer marker = render2D.getFont(28.0f, true);
marker.drawCenteredString("TEST", render2D.getWidth() / 2.0,
render2D.getHeight() / 2.0 - 24.0, 0xFFFF3030);
if (ClientInput.isOpen()) {
double mouseX = ClientInput.getMouseX();
double mouseY = ClientInput.getMouseY();
render2D.drawLine(mouseX - 7, mouseY, mouseX + 7, mouseY, 1.0, 0xFFFF4040);
render2D.drawLine(mouseX, mouseY - 7, mouseX, mouseY + 7, 1.0, 0xFFFF4040);
}
}
}
@@ -19,6 +19,14 @@ public final class Render2DManager {
private final FontBackend backend;
private final FontManager fonts;
/**
* Whether the overlay is drawn on screens that are not backed by a loaded
* level (title screen, world selection, ...). 1.8.9 never renders the HUD
* there, and this defaults to the same behaviour on every version.
* Enable with {@code -Dorangex.renderInMenus=true}.
*/
private volatile boolean renderInMenus = Boolean.getBoolean("orangex.renderInMenus");
public Render2DManager(RuntimeInfo runtimeInfo,
MappingResolver mappingResolver,
Object minecraft) {
@@ -28,6 +36,19 @@ public final class Render2DManager {
}
public void fire(Object platformContext) {
fire(platformContext, true);
}
/**
* @param inWorld {@code true} when a level is loaded (the game's own
* "should render level" flag). When {@code false} the
* event is dropped unless {@link #isRenderInMenus()} is on.
*/
public void fire(Object platformContext, boolean inWorld) {
if (!inWorld && !renderInMenus) {
return;
}
EventBus eventBus = OrangeX.getInstance().getEventBus();
if (!eventBus.hasSubscriberForEvent(EventRender2D.class)) {
return;
@@ -35,12 +56,20 @@ public final class Render2DManager {
Render2D context = backend.createRender2D(fonts, platformContext);
try {
eventBus.post(new EventRender2D(context));
eventBus.post(new EventRender2D(context, inWorld));
} finally {
context.flush();
}
}
public boolean isRenderInMenus() {
return renderInMenus;
}
public void setRenderInMenus(boolean renderInMenus) {
this.renderInMenus = renderInMenus;
}
public String getBackendName() {
return backend.getName();
}
@@ -3,8 +3,8 @@ package cn.xiaozhou233.orangex.wrapper.api;
/**
* Cross-version view of {@code net.minecraft.client.Minecraft}.
*
* <p>Only the native client instance is exposed for now. More operations will be
* added incrementally as they are needed.</p>
* <p>Only the native client instance and the input-screen helpers are exposed
* for now. More operations will be added incrementally as they are needed.</p>
*/
public interface Minecraft {
@@ -15,4 +15,58 @@ public interface Minecraft {
* handling belongs to the implementation.</p>
*/
Object getMinecraft();
/**
* {@code true} while a level is loaded (the title screen returns
* {@code false}).
*/
boolean isInWorld();
/**
* {@code true} when the OrangeX empty input screen is the current screen.
*/
boolean isInputScreenOpen();
/**
* {@code true} when any Minecraft screen is open, including vanilla ones.
*/
boolean isScreenOpen();
/**
* Identity check for injected code: returns {@code true} only for the
* screen instance created by {@link #openInputScreen()}.
*/
boolean isInputScreenInstance(Object screen);
/**
* Opens an empty screen. This releases the cursor and stops mouse and
* keyboard input from reaching the player.
*/
void openInputScreen();
/**
* Closes the input screen and gives mouse capture back to the game.
*/
void closeInputScreen();
/**
* {@code true} while the GUI toggle key (M) is held.
*/
boolean isToggleKeyDown();
/**
* {@code true} when the toggle is driven by key events (1.8.9) rather
* than per-tick polling (26.2).
*/
boolean isToggleEventDriven();
/**
* Current cursor X in Minecraft GUI pixels.
*/
double getGuiMouseX();
/**
* Current cursor Y in Minecraft GUI pixels.
*/
double getGuiMouseY();
}
@@ -1,5 +1,6 @@
package cn.xiaozhou233.orangex.wrapper.internal.v1_8_9;
import cn.xiaozhou233.orangex.input.internal.VersionInput;
import cn.xiaozhou233.orangex.mapping.MappingClass;
import cn.xiaozhou233.orangex.mapping.MappingField;
import cn.xiaozhou233.orangex.mapping.MappingResolver;
@@ -22,12 +23,15 @@ public final class V1_8_9Minecraft implements Minecraft {
private static final String INSTANCE_FIELD = "theMinecraft";
private final RuntimeInfo runtimeInfo;
private final MappingResolver mappingResolver;
private final MappingClass mappingMinecraft;
private Object instance;
private VersionInput input;
public V1_8_9Minecraft(RuntimeInfo runtimeInfo, MappingResolver mappingResolver) {
this.runtimeInfo = runtimeInfo;
this.mappingResolver = mappingResolver;
this.mappingMinecraft = mappingResolver.mapClass(MINECRAFT_CLASS);
}
@@ -39,6 +43,80 @@ public final class V1_8_9Minecraft implements Minecraft {
return instance;
}
/**
* Loads the version-specific input implementation on first use. The class
* name is kept as a string so a 26.2 runtime never resolves LWJGL 2.
*/
private synchronized VersionInput input() {
if (input == null) {
try {
Class<?> bridge = Class.forName(
"cn.xiaozhou233.orangex.input.internal.v1_8_9.V1_8_9Input",
true,
V1_8_9Minecraft.class.getClassLoader());
input = (VersionInput) bridge.getConstructor(
RuntimeInfo.class,
MappingResolver.class,
Object.class)
.newInstance(runtimeInfo, mappingResolver, getMinecraft());
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(
"Cannot create the 1.8.9 input bridge", e);
}
}
return input;
}
@Override
public boolean isInWorld() {
return input().isInWorld();
}
@Override
public boolean isInputScreenOpen() {
return input().isInputScreenOpen();
}
@Override
public boolean isScreenOpen() {
return input().isScreenOpen();
}
@Override
public boolean isInputScreenInstance(Object screen) {
return input().isInputScreenInstance(screen);
}
@Override
public void openInputScreen() {
input().openInputScreen();
}
@Override
public void closeInputScreen() {
input().closeInputScreen();
}
@Override
public boolean isToggleKeyDown() {
return input().isToggleKeyDown();
}
@Override
public boolean isToggleEventDriven() {
return input().isToggleEventDriven();
}
@Override
public double getGuiMouseX() {
return input().getGuiMouseX();
}
@Override
public double getGuiMouseY() {
return input().getGuiMouseY();
}
private Object resolveInstance() {
MappingField mappingField = mappingMinecraft.getField(INSTANCE_FIELD);
if (mappingField == null) {
@@ -1,5 +1,6 @@
package cn.xiaozhou233.orangex.wrapper.internal.v26_2;
import cn.xiaozhou233.orangex.input.internal.VersionInput;
import cn.xiaozhou233.orangex.mapping.MappingClass;
import cn.xiaozhou233.orangex.mapping.MappingField;
import cn.xiaozhou233.orangex.mapping.MappingResolver;
@@ -25,6 +26,7 @@ public final class V26_2Minecraft implements Minecraft {
private final MappingClass mappingMinecraft;
private Object instance;
private VersionInput input;
public V26_2Minecraft(RuntimeInfo runtimeInfo,
MappingResolver mappingResolver) {
@@ -40,6 +42,79 @@ public final class V26_2Minecraft implements Minecraft {
return instance;
}
/**
* Loads the version-specific input implementation on first use. Keeping
* the 26.2 class behind a string keeps 1.8.9 runtimes clean.
*/
private synchronized VersionInput input() {
if (input == null) {
try {
Class<?> bridge = Class.forName(
"cn.xiaozhou233.orangex.input.v26_2.V26_2Input",
true,
V26_2Minecraft.class.getClassLoader());
input = (VersionInput) bridge.getConstructor(
RuntimeInfo.class,
Object.class)
.newInstance(runtimeInfo, getMinecraft());
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(
"Cannot create the 26.2 input bridge", e);
}
}
return input;
}
@Override
public boolean isInWorld() {
return input().isInWorld();
}
@Override
public boolean isInputScreenOpen() {
return input().isInputScreenOpen();
}
@Override
public boolean isScreenOpen() {
return input().isScreenOpen();
}
@Override
public boolean isInputScreenInstance(Object screen) {
return input().isInputScreenInstance(screen);
}
@Override
public void openInputScreen() {
input().openInputScreen();
}
@Override
public void closeInputScreen() {
input().closeInputScreen();
}
@Override
public boolean isToggleKeyDown() {
return input().isToggleKeyDown();
}
@Override
public boolean isToggleEventDriven() {
return input().isToggleEventDriven();
}
@Override
public double getGuiMouseX() {
return input().getGuiMouseX();
}
@Override
public double getGuiMouseY() {
return input().getGuiMouseY();
}
private Object resolveInstance() {
MappingField mappingField = mappingMinecraft.getField(INSTANCE_FIELD);
if (mappingField == null) {
+2
View File
@@ -9,6 +9,7 @@
| [vape-font-gui-rendering.md](vape-font-gui-rendering.md) | Vape 4.21 的字体光栅化、文本排版、GUI 组件树、双渲染后端与 1.7.10–26.2 跨版本路径分析 |
| [font-port.md](font-port.md) | OrangeX 的字体移植实现:TTF 烘焙、Render2D API、1.8.9 / 26.2 接入、调试参数与限制 |
| [gui-rendering.md](gui-rendering.md) | 2D GUI 绘制层:矩形、渐变、圆角、描边、直线、裁剪及两版本实现 |
| [world-gating-and-input.md](world-gating-and-input.md) | 世界内渲染判定、1.8.9 / 26.2 鼠标捕获差异,以及已落地的空 GUI / 输入层实现 |
## 快速导航
@@ -25,6 +26,7 @@
- Universal Shader 批次渲染 → 主文档 §3.5
- 1.21.6+ / 26.x 兼容 → 主文档 §3.7
- 版本矩阵 → 主文档 §4
- 世界内渲染判定与鼠标输入 → [world-gating-and-input.md](world-gating-and-input.md)
## 阅读前提
+418
View File
@@ -0,0 +1,418 @@
# 世界内渲染与鼠标输入
本文记录两件事:
1. 为什么 1.8.9 的字体 / GUI 只在进入世界后绘制,而 26.2 在主界面也会绘制,以及 OrangeX 现在如何统一。
2. 客户端 GUI 打开时,如何让鼠标在 GUI 上移动,而不是继续控制游戏视角。
> 状态:第 1 部分和第 2 部分的空 GUI / 鼠标输入已落地。M 键打开或关闭输入界面。
---
## 1. 世界内渲染
### 1.1 两个版本的差异
| 版本 | Hook 点 | 调用时机 |
| --- | --- | --- |
| 1.8.9 | `GuiIngame#renderGameOverlay(float)` | `EntityRenderer#updateCameraAndRender` 中,只有 `theWorld != null` 才会调用 |
| 26.2 | `Gui#extractRenderState(DeltaTracker, boolean, boolean)` | 每帧都调用,主界面 / 选世界 / 加载界面同样会执行 |
26.2 的第二个参数就是“当前是否渲染世界”:
```java
// GameRenderer#extract
boolean readyForLevelRendering =
resourcesLoaded && advanceGameTime && minecraft.level != null;
minecraft.gui.extractRenderState(deltaTracker, readyForLevelRendering, resourcesLoaded);
```
所以 26.2 并不是渲染层出了问题,而是 Hook 拿到的回调本身不区分“菜单”和“世界”。
### 1.2 OrangeX 的处理
26.2 的注入代码把 `shouldRenderLevel` 一起传给门面:
```java
// Render2DHook,26.2 分支
// $0 = this, $1 = DeltaTracker, $2 = shouldRenderLevel
method.insertAfter("Render2DEvents.fire($0, $2);");
```
> 注意:Javassist 的 `$0` 是 `this`,`$1` 才是第一个参数。26.2 的 `shouldRenderLevel` 是第二个参数,因此是 `$2`。
1.8.9 的 HUD 方法本来就只在世界内执行,显式传 `true`:
```java
method.insertAfter("Render2DEvents.fire(null, true);");
```
事件链:
```text
注入代码
└─ Render2DEvents.fire(context, inWorld)
└─ Render2DManager.fire(context, inWorld)
├─ inWorld == false 且未开启菜单渲染 → 直接 return
└─ post EventRender2D(context, inWorld)
```
相关文件:
```text
OrangeX/src/main/java/cn/xiaozhou233/orangex/
├── hook/impl/Render2DHook.java
├── event/facade/Render2DEvents.java
├── event/impl/EventRender2D.java
└── render/Render2DManager.java
```
### 1.3 监听器侧
`EventRender2D` 新增了:
```java
public boolean isInWorld();
```
默认情况下主界面不会收到事件;如果以后需要让某个功能在菜单里也绘制,可以临时打开:
```java
OrangeX.getInstance().getRender2DManager().setRenderInMenus(true);
```
或启动参数:
```text
-Dorangex.renderInMenus=true
```
打开后事件仍然会带 `inWorld=false`,监听器可以自行区分。
---
## 2. 鼠标输入
渲染和输入是两套独立机制。字体 / GUI 画出来不代表鼠标就能用,真正决定鼠标行为的是游戏的鼠标捕获状态:
- 1.8.9:`Minecraft#inGameHasFocus` + `MouseHelper`
- 26.2:`MouseHandler#mouseGrabbed`
只要还在捕获状态,鼠标移动就会转视角。
### 2.1 为什么“只放开鼠标”不够
#### 1.8.9
`Minecraft#setIngameNotInFocus()` 会调用 `mouseHelper.ungrabMouseCursor()`,鼠标可以出来。但 `runTick()` 里还有:
```java
if (this.currentScreen == null) {
if (!this.inGameHasFocus && Mouse.getEventButtonState()) {
this.setIngameFocus(); // 下一次点击重新捕获
}
}
```
而且 `currentScreen == null` 时,鼠标事件仍会走 `KeyBinding.setKeyBindState(...)` / `KeyBinding.onTick(...)`,攻击、使用物品等逻辑依然会触发。
#### 26.2
`MouseHandler#releaseMouse()` 只是修改 `mouseGrabbed` 并恢复 GLFW 光标:
```java
public void releaseMouse() {
if (this.mouseGrabbed) {
this.mouseGrabbed = false;
...
InputConstants.grabOrReleaseMouse(this.minecraft.getWindow(), 212993, this.xpos, this.ypos);
}
}
```
但 `MouseHandler#onButton()` 中:
```java
if (this.minecraft.gui.screen() == null) {
if (!this.mouseGrabbed && pressed) {
this.grabMouse(); // 下一次点击重新捕获
}
}
```
`grabMouse()` 内部还会调用 `minecraft.gui.setScreen(null)`。
结论:**单纯 ungrab / releaseMouse 不能作为“打开 GUI”的实现**。
### 2.2 推荐方案:用一个只负责输入的 Screen
Screen 会同时完成:
- 释放鼠标捕获
- `KeyMapping.releaseAll()`,WASD / 攻击 / 物品栏不再控制游戏
- 把 `mouseMoved` / `mouseClicked` / `mouseScrolled` / `keyPressed` 路由给 GUI
- 关闭时自动重新捕获鼠标
因此推荐“HUD 继续负责绘制,Screen 只负责输入”的组合,而不是把 HUD 直接改造成 Screen。
#### 1.8.9
`GuiScreen` 是**抽象类**(1.8.8 / 1.8.9 都是),不能直接 `new`。实际实现是运行时用 Javassist 生成一个空的 concret 子类,再通过 `JuiceAgent#defineClass` 定义到游戏 ClassLoader:
```text
GuiScreen(抽象)
└─ GeneratedInputScreen(运行时生成,public 无参构造 → super())
```
生成后用 `MappingResolver` 解析出的 `displayGuiScreen` 打开:
```java
Object screen = inputScreenClass.getDeclaredConstructor().newInstance();
mcClass.getMethod(displayGuiScreenName, guiScreenClass).invoke(mc, screen);
```
`displayGuiScreen(screen)` 内部会 `setIngameNotInFocus()`;`displayGuiScreen(null)` 内部会 `setIngameFocus()`。
需要 Hook `GuiScreen` 接收输入,并且只处理自己的空壳实例:
```text
GuiScreen#drawScreen(int mouseX, int mouseY, float partialTicks) // 每帧鼠标坐标
GuiScreen#mouseClicked(int mouseX, int mouseY, int mouseButton)
GuiScreen#mouseReleased(int mouseX, int mouseY, int state)
GuiScreen#mouseClickMove(int mouseX, int mouseY, int button, long time)
GuiScreen#keyTyped(char typedChar, int keyCode) // ESC 默认关闭界面
```
这里拿到的坐标已经是 GUI 缩放后的坐标,可以直接给 `Render2D` 使用。
两点注意:
- 原版 `GuiScreen#drawScreen()` 默认只画 `buttonList` / `labelList`,空壳不会覆盖 HUD。
- `GuiScreen#doesGuiPauseGame()` 默认返回 `true`,单人会暂停;`GuiInputHook` 会只对生成的空壳返回 `false`。
#### 26.2
`Screen` 是抽象类,实际实现是 `V26_2InputScreen`(输入状态记录在 `ClientInput`):
```java
public final class V26_2InputScreen extends Screen {
public V26_2InputScreen() {
super(Component.empty());
}
// 不要原版的模糊 / 菜单背景
@Override
public void extractBackground(GuiGraphicsExtractor g, int mouseX, int mouseY, float a) {
}
// 不想暂停世界就返回 false
@Override
public boolean isPauseScreen() {
return false;
}
// GUI 仍由 HUD Hook 绘制,这里留空
@Override
public void extractRenderState(GuiGraphicsExtractor g, int mouseX, int mouseY, float a) {
}
@Override
public void mouseMoved(double x, double y) {
ClientInput.onMouseMove(x, y);
}
@Override
public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
ClientInput.onMouseButton(event.x(), event.y(), event.button(), true);
return true;
}
@Override
public boolean mouseReleased(MouseButtonEvent event) {
ClientInput.onMouseButton(event.x(), event.y(), event.button(), false);
return true;
}
@Override
public boolean mouseScrolled(double x, double y, double scrollX, double scrollY) {
ClientInput.onMouseMove(x, y);
return true;
}
}
```
ESC 不需要自己处理:`Screen#keyPressed` 默认会调用 `onClose()`,进而 `gui.setScreen(null)`,`ClientInput` 在下一个 tick 检测到界面关闭后自动重置状态。
打开 / 关闭(`V26_2Input` 内部):
```java
minecraft.gui.setScreen(new V26_2InputScreen()); // releaseMouse + releaseAll + init
minecraft.gui.setScreen(null); // grabMouse
```
26.2 的 `mouseMoved(x, y)`、`MouseButtonEvent.x()/y()` 已经是 `MouseHandler#getScaledXPos()` 换算后的 GUI 坐标,不要再乘 `guiScale`。
绘制顺序方面,26.2 的 `Gui#extractRenderState` 会先提取 Screen,再走到 OrangeX 的 Hook 尾部,所以 HUD Hook 里的内容会盖在 Screen 之上;1.8.9 则是 HUD 先画、空壳 Screen 后画,只要空壳不画背景就不会遮挡。
#### 26.2 的编译依赖
`libraries/Minecraft26.2.jar` 是 Java 25 字节码(class version 69),而当前 Gradle 使用 JDK 17,不能直接作为 `compileOnly` 依赖。因此 OrangeX 增加了一个只参与编译的 stub 模块:
```text
Minecraft262Stubs/
└── src/main/java/
├── com/mojang/blaze3d/platform/{Window,InputConstants}.java
└── net/minecraft/
├── client/{Minecraft,MouseHandler}.java
├── client/gui/{Gui,GuiGraphicsExtractor}.java
├── client/gui/screens/Screen.java
├── client/input/MouseButtonEvent.java
├── client/multiplayer/ClientLevel.java
└── network/chat/{Component,MutableComponent}.java
```
`OrangeX/build.gradle` 使用 `compileOnly project(':Minecraft262Stubs')`。stub **不会打进 OrangeX.jar**,运行时仍然加载游戏提供的真正 26.2 类。stub 里的字段类型必须和真实类一致,否则会生成错误的字段描述符(例如 `Minecraft#level` 必须是 `ClientLevel` 而不是 `Object`)。
### 2.3 当前实现
```text
OrangeX/src/main/java/cn/xiaozhou233/orangex/
├── input/
│ ├── ClientInput.java 跨版本输入状态:开/关、鼠标坐标、按键状态
│ ├── InputController.java 在 EventTickPre 中驱动 ClientInput
│ ├── internal/
│ │ ├── VersionInput.java 版本输入接口
│ │ └── v1_8_9/V1_8_9Input.java 1.8.9:运行时生成 GuiScreen 子类 + LWJGL 2
│ └── v26_2/
│ ├── V26_2Input.java 26.2:gui.setScreen + InputConstants
│ └── V26_2InputScreen.java 26.2 空 Screen
├── event/facade/InputEvents.java 1.8.9 注入代码的门面
└── hook/impl/
├── GuiInputHook.java 1.8.9 GuiScreen 输入 / 关闭 Hook
└── KeyPressHook.java 1.8.9 KeyBinding.onTick 打开 Hook
```
行为:
- M 键在**世界内**打开空 GUI;再次按下关闭。
- 1.8.9 的开关走事件而不是 tick 轮询:
- 打开:`KeyBinding#onTick(int)` → `InputEvents.onKeyPressed` → `ClientInput.requestOpen()`
- 关闭:`GuiScreen#keyTyped(char, int)` → `InputEvents.onKeyTyped` → `ClientInput.requestClose()`
- 两者都只在 tick 末尾(`EventTickPost` → `ClientInput.applyPending`)真正执行。
- 原因:如果在键盘循环里直接打开 Screen,同一个 M 事件会立刻被 `currentScreen.handleKeyboardInput()` 再处理一次,导致刚打开就关闭。
- 自动重复事件通过 `V1_8_9Input.isRepeatEvent()` 过滤,按住 M 不会反复开关。
- 26.2 仍然每 tick 用 `InputConstants.isKeyDown(window, 77)` 轮询 M。
- 打开时:
- 1.8.9:运行时生成 `GuiScreen` 具体子类,再 `Minecraft#displayGuiScreen(...)`;`doesGuiPauseGame()` 对自己的空壳返回 `false`。
- 26.2:`Gui#setScreen(new V26_2InputScreen())`,`isPauseScreen()` 返回 `false`。
- 打开后鼠标由系统光标接管,`GuiScreen#drawScreen` / `Screen#mouseMoved` 持续把 GUI 坐标写入 `ClientInput`。
- `ClientInput` 可供 `EventRender2D` 读取:
```java
if (ClientInput.isOpen()) {
double x = ClientInput.getMouseX();
double y = ClientInput.getMouseY();
boolean left = ClientInput.isLeftDown();
}
```
`FontDebugOverlay` 现在会显示 `Input: OPEN/closed` 和鼠标坐标,并在 GUI 打开时画一个红色十字光标。
### 2.4 备选方案:不经过 Screen 的 Overlay
如果完全不想引入 Screen,也可以参考 Vape 的纯 Overlay 思路,但需要自己补齐所有输入拦截:
26.2:
```text
mouseHandler.releaseMouse()
Hook MouseHandler#grabMouse() GUI 打开时直接 return
Hook MouseHandler#onButton(...) GUI 打开时转发点击并 return
Hook MouseHandler#onScroll(...) GUI 打开时转发滚轮并 return
Hook KeyboardHandler#keyPress(...) GUI 打开时转发键盘并 return
```
鼠标坐标:
```java
double x = mouseHandler.getScaledXPos(minecraft.getWindow());
double y = mouseHandler.getScaledYPos(minecraft.getWindow());
```
1.8.9:
```text
mc.setIngameNotInFocus()
Hook Minecraft#setIngameFocus() GUI 打开时直接 return
处理 runTick() 中 currentScreen == null 的鼠标按键 / KeyBinding 路径
```
鼠标坐标:
```java
int x = Mouse.getX() * scaledWidth / mc.displayWidth;
int y = scaledHeight - Mouse.getY() * scaledHeight / mc.displayHeight - 1;
```
这条路的优点是绕开 Screen API;缺点是键盘、点击、滚轮的拦截全部要自己维护,ClickGUI 场景下不如 Screen 方案稳。
---
## 3. 常见坑
| 现象 | 原因 |
| --- | --- |
| 26.2 主界面也绘制 HUD | `Gui#extractRenderState` 每帧执行,需要看 `shouldRenderLevel` |
| 注入后 `shouldRenderLevel` 取错 | Javassist `$0` 是 `this`,第二个参数是 `$2` |
| 放开鼠标后点一下又转视角 | 1.8.9 `runTick` 会 `setIngameFocus`;26.2 `onButton` 会 `grabMouse` |
| 26.2 `grabMouse` 把界面关掉 | `MouseHandler#grabMouse` 内部会 `gui.setScreen(null)` |
| 点击坐标偏移 | Screen 回调坐标已经过 GUI Scale,不要再乘一次 |
| 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 存在时都不响应 |
---
## 4. 相关文件
```text
OrangeX/src/main/java/cn/xiaozhou233/orangex/
├── hook/
│ ├── HookManager.java
│ └── impl/
│ ├── TickHook.java
│ ├── Render2DHook.java
│ ├── GuiInputHook.java
│ └── KeyPressHook.java
├── input/
│ ├── ClientInput.java
│ ├── InputController.java
│ ├── internal/
│ │ ├── VersionInput.java
│ │ └── v1_8_9/V1_8_9Input.java
│ └── v26_2/
│ ├── V26_2Input.java
│ └── V26_2InputScreen.java
├── event/
│ ├── facade/
│ │ ├── TickEvents.java
│ │ ├── Render2DEvents.java
│ │ └── InputEvents.java
│ └── impl/
│ ├── EventTickPre.java
│ ├── EventTickPost.java
│ └── EventRender2D.java
├── render/
│ ├── Render2DManager.java
│ └── FontDebugOverlay.java
└── wrapper/
├── api/Minecraft.java
└── internal/
├── v1_8_9/V1_8_9Minecraft.java
└── v26_2/V26_2Minecraft.java
Minecraft262Stubs/src/main/java/ 26.2 compileOnly stubs(不打包)
```
+1
View File
@@ -0,0 +1 @@
Minecraft26.2.jar
@@ -0,0 +1 @@
https://piston-data.mojang.com/v1/objects/2dc72797acbc1b63fc16a11c4ac393605f453754/client.jar
Binary file not shown.
+1
View File
@@ -3,3 +3,4 @@ include 'Loader'
include 'OrangeX'
include 'Injector'
include 'Minecraft1.8.8'
include 'Minecraft262Stubs'