Compare commits

..
14 Commits
Author SHA1 Message Date
xiaozhou233 d241addec7 Fix: Scale injector GUI for HiDPI displays 2026-11-07 20:02:19 +08:00
xiaozhou233 54b476451c Feat: Add dark injector GUI
- Replace the console selection with a FlatDarkLaf Swing window

- List detected Minecraft windows, support a hidden custom PID input and refresh

- Run injection on a background thread and report the result in the status label

- Bundle FlatLaf into injector.jar so the packaged GUI runs standalone
2026-11-07 19:11:06 +08:00
xiaozhou233 f6d8c7da2f Feat: Add module value system
- Add Value, BooleanValue, KeybindValue and ModeValue

- Store values per module with defaults, reset, visibility and JSON encoding

- Wire module keybinds to EventKey so bound keys toggle modules
2026-11-07 18:58:04 +08:00
xiaozhou233 7e27752ffc Feat: HUD Module 2026-11-07 18:45:52 +08:00
xiaozhou233 c8e23c5d1c Build: Keep Java 8 output while compiling 26.2 sources
- Compile main sources with --release 8

- Move record-dependent v26_2 input classes to a separate source set

- Use a JDK 25 toolchain for that source set, still emitting class version 52

- Fix the Injector PrintStream charset constructor for Java 8
2026-11-07 17:01:36 +08:00
xiaozhou233 a84b04877d Refactor: Route key input through EventBus
- Post EventKey from 1.8.9 KeyBinding/GuiScreen hooks

- Hook 26.2 KeyboardHandler#keyPress so keys fire while walking

- Normalize 26.2 GLFW key codes to 1.8.9 LWJGL 2 codes

- Drive the GUI toggle from InputController instead of tick polling
2026-11-07 16:48:26 +08:00
xiaozhou233 70d8a854ea Feat: Auto download client jar and dependence 2026-11-07 15:46:11 +08:00
xiaozhou233 fdeec2a2f5 Fix: Injector warning and Chinese garbled text 2026-11-07 15:15:32 +08:00
xiaozhou233 fea7089ff8 Feat: Upgrade to Java25 gradle-9.8.2, Delete Stubs 2026-11-07 15:11:18 +08:00
xiaozhou233 0599e48ebe Docs: world-gating-and-input.md 2026-11-07 14:52:28 +08:00
xiaozhou233 0232fb0446 Docs: Add support version 2026-11-07 14:03:36 +08:00
xiaozhou233 5c726f54e4 Docs: Add launcher class-loader troubleshooting and hook file index 2026-11-07 13:55:05 +08:00
xiaozhou233 4b55871a8b Fix: Resolve hooks on launchers with remapped class loaders
Inject through the top-level orangexbridge package instead of imported cn.* names, build a fresh Javassist pool with agent-provided runtime class bytes, and fall back to safe class paths. Fixes Lunar GenesisClassLoader hook failures where resource class files still use obfuscated names.
2026-11-07 13:51:57 +08:00
xiaozhou233 cfb0ba4a48 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.
2026-11-07 13:34:52 +08:00
55 changed files with 3529 additions and 198 deletions

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@
<component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="zulu-25" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
+1
View File
@@ -2,6 +2,7 @@
<configuration default="false" name="Injector" type="Application" factoryName="Application">
<option name="MAIN_CLASS_NAME" value="cn.xiaozhou233.orangex.injector.Main" />
<module name="OrangeX-Client.Injector.main" />
<option name="VM_PARAMETERS" value="--enable-native-access=ALL-UNNAMED -Dfile.encoding=UTF-8" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/out" />
<extension name="coverage">
<pattern>
+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" />
+9
View File
@@ -12,6 +12,9 @@ repositories {
dependencies {
testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
// Source: https://mvnrepository.com/artifact/com.formdev/flatlaf
implementation 'com.formdev:flatlaf:3.8'
}
test {
@@ -24,6 +27,12 @@ tasks.named('jar') {
manifest {
attributes 'Main-Class': 'cn.xiaozhou233.orangex.injector.Main'
}
// Bundle runtime dependencies (FlatLaf) so injector.jar is self-contained.
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA'
}
tasks.withType(JavaCompile).configureEach {
@@ -0,0 +1,310 @@
package cn.xiaozhou233.orangex.injector;
import cn.xiaozhou233.juiceagent.injector.Injector;
import cn.xiaozhou233.juiceagent.injector.WindowInfo;
import com.formdev.flatlaf.util.UIScale;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
/**
* Injector front-end: lists the running Minecraft windows, optionally accepts a
* PID typed by hand, and runs {@link Injector#inject(int, String, String)} on a
* background thread.
*/
public class InjectorWindow extends JFrame {
private static final String[] WINDOW_TITLES = {
"Minecraft", "minecraft", "1.8.9", "Badlion", "Lunar"
};
private static final String[] IGNORED_TITLES = {
"Badlion Client", "Badlion Chat", "Home - Lunar Client"
};
private static final Color ACCENT = new Color(0xFF8A00);
private static final Color SUCCESS = new Color(0x66BB6A);
private static final Color ERROR = new Color(0xEF5350);
private static final Color MUTED = new Color(0xAAAAAA);
private final String agentPath;
private final String configDir;
private final DefaultComboBoxModel<ProcessEntry> processModel = new DefaultComboBoxModel<>();
private final JComboBox<ProcessEntry> processBox = new JComboBox<>(processModel);
private final JButton refreshButton = new JButton("Refresh");
private final JCheckBox customPidCheck = new JCheckBox("Use custom PID");
private final JTextField pidField = new JTextField();
private final JButton injectButton = new JButton("Inject");
private final JLabel statusLabel = new JLabel("Ready", SwingConstants.CENTER);
private boolean busy;
public InjectorWindow(String agentPath, String configDir) {
super("OrangeX Injector");
this.agentPath = agentPath;
this.configDir = configDir;
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
setContentPane(buildContent());
setSize(UIScale.scale(470), UIScale.scale(340));
setLocationRelativeTo(null);
getRootPane().setDefaultButton(injectButton);
refreshButton.addActionListener(event -> refreshProcesses());
customPidCheck.addActionListener(event -> {
boolean custom = customPidCheck.isSelected();
pidField.setVisible(custom);
revalidate();
repaint();
if (custom) {
pidField.requestFocusInWindow();
}
updateControls();
});
injectButton.addActionListener(event -> inject());
refreshProcesses();
}
private JPanel buildContent() {
JPanel root = new JPanel(new GridBagLayout());
root.setBorder(new EmptyBorder(
UIScale.scale(20), UIScale.scale(26),
UIScale.scale(16), UIScale.scale(26)));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
int row = 0;
JLabel title = new JLabel(
"<html><font color='#FF8A00'><b>OrangeX</b></font> Injector</html>",
SwingConstants.CENTER);
title.setFont(title.getFont().deriveFont(Font.BOLD, UIScale.scale(26f)));
gbc.gridy = row++;
gbc.insets = UIScale.scale(new Insets(0, 0, 20, 0));
root.add(title, gbc);
processBox.setPreferredSize(new Dimension(UIScale.scale(200), UIScale.scale(34)));
JPanel processRow = new JPanel(new BorderLayout(UIScale.scale(8), 0));
processRow.add(processBox, BorderLayout.CENTER);
processRow.add(refreshButton, BorderLayout.EAST);
gbc.gridy = row++;
gbc.insets = UIScale.scale(new Insets(0, 0, 10, 0));
root.add(processRow, gbc);
gbc.gridy = row++;
gbc.insets = UIScale.scale(new Insets(0, 0, 8, 0));
root.add(customPidCheck, gbc);
pidField.setPreferredSize(new Dimension(0, UIScale.scale(34)));
pidField.putClientProperty("JTextField.placeholderText", "Enter a process ID");
pidField.setVisible(false);
gbc.gridy = row++;
gbc.insets = UIScale.scale(new Insets(0, 0, 10, 0));
root.add(pidField, gbc);
injectButton.setPreferredSize(new Dimension(0, UIScale.scale(40)));
injectButton.setFont(injectButton.getFont().deriveFont(
Font.BOLD, UIScale.scale(15f)));
injectButton.setBackground(ACCENT);
injectButton.setForeground(Color.WHITE);
injectButton.putClientProperty("JButton.buttonType", "roundRect");
gbc.gridy = row++;
gbc.insets = UIScale.scale(new Insets(10, 0, 12, 0));
root.add(injectButton, gbc);
statusLabel.setFont(statusLabel.getFont().deriveFont(UIScale.scale(12f)));
statusLabel.setForeground(MUTED);
gbc.gridy = row++;
gbc.insets = new Insets(0, 0, 0, 0);
root.add(statusLabel, gbc);
// Keeps the content aligned to the top when the PID field is hidden.
gbc.gridy = row;
gbc.weighty = 1.0;
root.add(Box.createVerticalGlue(), gbc);
return root;
}
/**
* Rescans the open windows and fills the selection box. Errors are shown
* in the status label instead of terminating the window.
*/
public void refreshProcesses() {
processModel.removeAllElements();
List<ProcessEntry> processes;
try {
processes = scanProcesses();
} catch (Throwable throwable) {
throwable.printStackTrace();
setStatus("Failed to scan windows: " + throwable.getClass().getSimpleName(), ERROR);
updateControls();
return;
}
for (ProcessEntry process : processes) {
processModel.addElement(process);
}
if (processes.isEmpty()) {
setStatus("No Minecraft process found", ERROR);
} else {
setStatus(processes.size() + " Minecraft process(es) found", MUTED);
}
updateControls();
}
private List<ProcessEntry> scanProcesses() {
Map<Integer, ProcessEntry> found = new LinkedHashMap<>();
for (String title : WINDOW_TITLES) {
WindowInfo[] windows = Injector.findWindowsByTitle(title);
if (windows == null) {
continue;
}
for (WindowInfo window : windows) {
if (window == null || window.title == null || found.containsKey(window.pid)) {
continue;
}
if (isIgnored(window.title)) {
continue;
}
found.put(window.pid, new ProcessEntry(window.pid, window.title));
}
}
return new ArrayList<>(found.values());
}
private static boolean isIgnored(String title) {
for (String ignored : IGNORED_TITLES) {
if (title.contains(ignored)) {
return true;
}
}
return false;
}
private void inject() {
Integer pid = selectedPid();
if (pid == null) {
return;
}
busy = true;
updateControls();
setStatus("Injecting into PID " + pid + "...", MUTED);
new SwingWorker<Boolean, Void>() {
@Override
protected Boolean doInBackground() {
return Injector.inject(pid, agentPath, configDir);
}
@Override
protected void done() {
busy = false;
updateControls();
try {
if (Boolean.TRUE.equals(get())) {
setStatus("Injection succeeded (PID " + pid + ")", SUCCESS);
} else {
setStatus("Injection failed (PID " + pid + ")", ERROR);
JOptionPane.showMessageDialog(
InjectorWindow.this,
"Injector.inject returned false for PID " + pid + ".",
"Injection failed",
JOptionPane.ERROR_MESSAGE);
}
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
setStatus("Injection interrupted", ERROR);
} catch (ExecutionException exception) {
Throwable cause = exception.getCause() == null
? exception : exception.getCause();
cause.printStackTrace();
setStatus("Injection failed (PID " + pid + ")", ERROR);
JOptionPane.showMessageDialog(
InjectorWindow.this,
cause.toString(),
"Injection failed",
JOptionPane.ERROR_MESSAGE);
}
}
}.execute();
}
private Integer selectedPid() {
if (customPidCheck.isSelected()) {
String text = pidField.getText().trim();
if (text.isEmpty()) {
showError("Enter a PID first, or untick \"Use custom PID\".");
return null;
}
try {
int pid = Integer.parseInt(text);
if (pid <= 0) {
throw new NumberFormatException("PID must be positive");
}
return pid;
} catch (NumberFormatException exception) {
showError("PID must be a positive integer.");
return null;
}
}
ProcessEntry selected = (ProcessEntry) processBox.getSelectedItem();
if (selected == null) {
showError("No Minecraft process selected. Start the game or use a custom PID.");
return null;
}
return selected.pid;
}
private void updateControls() {
boolean custom = customPidCheck.isSelected();
boolean hasProcess = processModel.getSize() > 0;
processBox.setEnabled(!busy && !custom && hasProcess);
refreshButton.setEnabled(!busy && !custom);
customPidCheck.setEnabled(!busy);
pidField.setEnabled(!busy);
injectButton.setEnabled(!busy && (custom || hasProcess));
}
private void setStatus(String text, Color color) {
statusLabel.setText(text);
statusLabel.setForeground(color);
}
private void showError(String message) {
setStatus(message, ERROR);
JOptionPane.showMessageDialog(
this, message, "OrangeX Injector", JOptionPane.WARNING_MESSAGE);
}
private static final class ProcessEntry {
private final int pid;
private final String title;
private ProcessEntry(int pid, String title) {
this.pid = pid;
this.title = title;
}
@Override
public String toString() {
return title + " (PID: " + pid + ")";
}
}
}
@@ -1,95 +1,142 @@
package cn.xiaozhou233.orangex.injector;
import cn.xiaozhou233.juiceagent.injector.Injector;
import cn.xiaozhou233.juiceagent.injector.WindowInfo;
import com.formdev.flatlaf.FlatDarkLaf;
import com.formdev.flatlaf.FlatLaf;
import com.formdev.flatlaf.util.UIScale;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
public class Main {
public static String orangexPath = new File(System.getProperty("user.home") + "/.orangex").getAbsolutePath();
private static int pid = -1;
public static final String orangexPath =
new File(System.getProperty("user.home"), ".orangex").getAbsolutePath();
public static final String agentPath =
new File(orangexPath, "libloader.dll").getAbsolutePath();
public static final String configDir = orangexPath;
public static void main(String[] args) {
setupConsole();
System.out.println("================");
System.out.println("OrangeX Injector v1.0.0");
System.out.println("OrangeX Path: " + orangexPath);
System.out.println("================");
// Unzip injection
extractInjection();
if (!loadNativeLibrary()) {
return;
}
SwingUtilities.invokeLater(() -> {
installLookAndFeel();
InjectorWindow window = new InjectorWindow(agentPath, configDir);
window.setVisible(true);
});
}
private static void setupConsole() {
try {
System.setOut(new PrintStream(
new FileOutputStream(FileDescriptor.out),
true,
StandardCharsets.UTF_8.name()
));
System.setErr(new PrintStream(
new FileOutputStream(FileDescriptor.err),
true,
StandardCharsets.UTF_8.name()
));
} catch (Exception exception) {
exception.printStackTrace();
}
}
private static void extractInjection() {
File zipFile = new File("./injection.zip");
if (!zipFile.exists()) {
System.err.println("injection.zip not found!");
return;
}
try (InputStream zipStream = new FileInputStream(zipFile)) {
FileUtils.unzip(zipStream, new File(orangexPath));
System.out.println("Done!");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Extracted injection.zip to " + orangexPath);
} catch (IOException exception) {
System.err.println("[ERROR] Failed to extract injection.zip: " + exception.getMessage());
exception.printStackTrace();
}
// Load libinject native library
System.load(new File(orangexPath + "/libinject.dll").getAbsolutePath());
System.out.println("Loaded libinject.dll");
// Find Minecraft
ArrayList<Integer> pids = new ArrayList<>();
ArrayList<String> windowTitles = new ArrayList<>();
try {
String[] titles = {"Minecraft", "minecraft", "1.8.9", "Badlion", "Lunar"};
String[] ignoreTitles = {"Badlion Client", "Badlion Chat", "Home - Lunar Client"};
for (String title : titles) {
WindowInfo[] list = Injector.findWindowsByTitle(title);
if (list == null || list.length == 0) {
} else {
for (WindowInfo w : list) {
if (pids.contains(w.pid))
continue;
if (Arrays.stream(ignoreTitles).anyMatch(w.title::contains))
continue;
pids.add(w.pid);
windowTitles.add(w.title);
}
}
}
} catch (UnsatisfiedLinkError ule) {
throw new RuntimeException("Native method findWindowsByTitle not available", ule);
} catch (Exception ex) {
System.out.println("[ERROR] Error while calling native findWindowsByTitle: " + ex.getMessage());
ex.printStackTrace();
}
// Print results
System.out.println("=======================");
for (int i = 0; i < pids.size(); i++) {
System.out.printf("[ %d ] %s (PID: %d)%n", i + 1, windowTitles.get(i), pids.get(i));
}
System.out.println("=======================");
if (pids.isEmpty()) {
System.err.println("[ERROR] No Minecraft process found!");
}
// Input the sequence number
try (Scanner scanner = new Scanner(System.in)) {
System.out.printf("[INPUT] Select (1-%d): ", pids.size());
int index = scanner.nextInt();
if (index < 1 || index > pids.size()) {
throw new RuntimeException("Invalid selection: " + index);
}
pid = pids.get(index - 1);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Invalid input", e);
}
String agentPath = orangexPath + "/libloader.dll";
String configDir = orangexPath;
Injector.inject(pid, agentPath, configDir);
}
}
private static boolean loadNativeLibrary() {
try {
System.load(new File(orangexPath, "libinject.dll").getAbsolutePath());
System.out.println("Loaded libinject.dll");
return true;
} catch (Throwable throwable) {
throwable.printStackTrace();
JOptionPane.showMessageDialog(
null,
"Failed to load libinject.dll:\n" + throwable,
"OrangeX Injector",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
private static void installLookAndFeel() {
try {
FlatDarkLaf.setup();
UIManager.put("Component.accentColor", new Color(0xFF8A00));
UIManager.put("Component.arc", 10);
UIManager.put("Button.arc", 12);
} catch (Throwable throwable) {
System.out.println("[WARN] FlatLaf is not available; using the default look and feel");
return;
}
applyWindowScale();
}
/**
* Large monitors are often driven at 100% OS scaling, which makes Swing
* UIs look tiny. Compute the scale the JRE already applies and add a zoom
* factor on top until the UI reaches a comfortable physical size.
*/
private static void applyWindowScale() {
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
if (screen.height < 1120) {
return;
}
float target = screen.height >= 1800 ? 2.0f : 1.5f;
GraphicsConfiguration configuration = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration();
double effective = UIScale.getSystemScaleFactor(configuration)
* UIScale.getUserScaleFactor();
if (effective >= target) {
return;
}
float zoom = (float) (target / effective);
if (UIScale.setZoomFactor(zoom)) {
FlatLaf.updateUI();
System.out.println("[OrangeX] UI scale " + target + "x (zoom " + zoom + ")");
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
plugins {
id 'java'
id("com.gradleup.shadow") version "8.3.11"
id("com.gradleup.shadow") version "9.6.1"
}
group = 'cn.xiaozhou233.orangex.injector'
+38 -2
View File
@@ -1,6 +1,6 @@
plugins {
id 'java'
id("com.gradleup.shadow") version "8.3.11"
id("com.gradleup.shadow") version "9.6.1"
}
group = 'cn.xiaozhou233.orangex'
@@ -27,16 +27,52 @@ 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')
compileOnly files("../libraries/minecraft/Minecraft26.2.jar")
compileOnly files("../libraries/minecraft/com/mojang/brigadier/1.3.10/brigadier-1.3.10.jar")
// JuiceAgent is provided at runtime by the agent (see JuiceAgentBridge).
// Do NOT bundle it: Fabric's KnotClassLoader would load a second copy of
// the API whose native methods are not registered.
}
// The 26.2 input classes import game classes that are records / class-file
// version 69, so they cannot be compiled with --release 8. Keep them in a
// separate source set compiled by JDK 25, but still emit Java 8 bytecode so a
// 1.8.9 JVM can load the rest of the jar.
sourceSets {
main {
java {
exclude 'cn/xiaozhou233/orangex/input/v26_2/**'
}
}
v26_2 {
java {
srcDir 'src/main/java'
include 'cn/xiaozhou233/orangex/input/v26_2/**'
}
compileClasspath += sourceSets.main.output
compileClasspath += configurations.compileClasspath
}
}
tasks.named('compileV26_2Java', JavaCompile).configure {
javaCompiler = javaToolchains.compilerFor {
languageVersion = JavaLanguageVersion.of(25)
}
// No --release: the JDK 25 platform classpath is needed to resolve records
// from Minecraft26.2.jar, while -source/-target 8 keeps the output loadable
// by Java 8.
options.release = null
options.encoding = 'UTF-8'
}
tasks.named('shadowJar') {
destinationDirectory = rootProject.layout.projectDirectory.dir('out/tmp')
archiveFileName = "${project.name}.jar"
dependsOn tasks.named('v26_2Classes')
from sourceSets.v26_2.output
}
shadowJar {
@@ -1,8 +1,12 @@
package cn.xiaozhou233.orangex;
import cn.xiaozhou233.orangex.event.impl.EventKey;
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
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.modules.ModuleManager;
import cn.xiaozhou233.orangex.render.FontDebugOverlay;
import cn.xiaozhou233.orangex.render.Render2DManager;
import cn.xiaozhou233.orangex.runtime.RuntimeDetector;
@@ -27,6 +31,10 @@ public class OrangeX {
private RuntimeInfo runtimeInfo;
@Getter
private Render2DManager render2DManager;
@Getter
private ModuleManager moduleManager = new ModuleManager();
@Getter
private Minecraft minecraft;
public OrangeX() {
System.out.println("OrangeX <init> start!");
@@ -41,15 +49,18 @@ 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));
eventBus.register(this);
moduleManager.init();
HookManager.getINSTANCE().applyAll();
}
@@ -57,4 +68,9 @@ public class OrangeX {
public void stop() {
System.out.println("OrangeX stop!");
}
@Subscribe
public void onKey(EventKey event) {
System.out.println("KEY: " + event.getKey());
}
}
@@ -0,0 +1,115 @@
package cn.xiaozhou233.orangex.event.facade;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.input.ClientInput;
import cn.xiaozhou233.orangex.input.KeyCodes;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
/**
* Input entry point shared by injected 1.8.9 code and the 26.2 input screen.
*
* <p>Every vanilla screen goes through these methods, so each callback first
* checks whether the instance is the empty input screen created by OrangeX.
* Key events are not handled here: they are posted as
* {@link cn.xiaozhou233.orangex.event.impl.EventKey} so features can subscribe
* to them, and {@link cn.xiaozhou233.orangex.input.InputController} consumes
* the GUI toggle.</p>
*/
public final class InputEvents {
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. The injected code already dropped auto-repeat events.
*/
public static void onKeyPressed(int keyCode) {
if (DEBUG) {
System.out.println("[OrangeX] key pressed: " + keyCode);
}
KeyEvents.fire(keyCode);
}
/**
* Called from the 26.2 {@code KeyboardHandler#keyPress} hook. Translates
* the GLFW key code to the canonical 1.8.9 numbering before posting.
*/
public static void onGlfwKeyPressed(int glfwKeyCode) {
onKeyPressed(KeyCodes.fromGlfw(glfwKeyCode));
}
/**
* 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.
*/
public static boolean onKeyTyped(Object screen, int keyCode) {
if (!isOurs(screen)) {
return false;
}
KeyEvents.fire(keyCode);
return keyCode == KeyCodes.M;
}
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() {
}
}
@@ -0,0 +1,41 @@
package cn.xiaozhou233.orangex.event.facade;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.event.impl.EventKey;
import cn.xiaozhou233.orangex.input.KeyCodes;
import org.greenrobot.eventbus.EventBus;
/**
* Entry point for raw key events.
*
* <p>Injected code and version-specific input code only call this facade;
* subscribers receive {@link EventKey} through the shared EventBus. All key
* codes are normalised to the 1.8.9 / LWJGL 2 numbering.</p>
*/
public final class KeyEvents {
private static final EventBus BUS = OrangeX.getInstance().getEventBus();
private static boolean failureLogged;
/**
* @param key canonical 1.8.9 (LWJGL 2) key code.
*/
public static void fire(int key) {
if (key == KeyCodes.NONE) {
return;
}
try {
BUS.post(new EventKey(key));
} catch (Throwable throwable) {
if (!failureLogged) {
failureLogged = true;
System.err.println("[OrangeX] Key event dispatch failed");
throwable.printStackTrace();
}
}
}
private KeyEvents() {
}
}
@@ -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() {
}
}
@@ -0,0 +1,18 @@
package cn.xiaozhou233.orangex.event.impl;
import cn.xiaozhou233.orangex.event.Event;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* A key press delivered through the EventBus.
*
* <p>{@link #getKey()} always uses the 1.8.9 / LWJGL 2 numbering, even when
* the game runs on 26.2. Modern GLFW key codes are translated before the
* event is posted (see {@code KeyCodes#fromGlfw(int)}).</p>
*/
@Getter
@AllArgsConstructor
public class EventKey implements Event {
private final int key;
}
@@ -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;
}
}
@@ -0,0 +1,79 @@
package cn.xiaozhou233.orangex.hook;
import javassist.ClassPath;
import javassist.NotFoundException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
/**
* Resolves game classes from the <strong>loaded</strong> class bytes through
* the JuiceAgent.
*
* <p>Some launchers (for example Lunar's Genesis class loader) serve
* MCP-named class resources but the bytes inside still use obfuscated class
* names. Javassist then throws errors such as
* {@code cannot find net.minecraft.util.IThreadListener: od found in ...}.
* The agent can return the current, runtime-named bytecode instead.</p>
*/
final class AgentClassPath implements ClassPath {
private final ClassLoader loader;
AgentClassPath(ClassLoader loader) {
this.loader = loader;
}
@Override
public InputStream openClassfile(String classname) throws NotFoundException {
if (isPlatformClass(classname)
|| classname.startsWith("cn.xiaozhou233.")
|| classname.startsWith("orangexbridge.")) {
return null;
}
byte[] bytes = readBytes(classname);
return bytes == null ? null : new ByteArrayInputStream(bytes);
}
private byte[] readBytes(String classname) {
String internalName = classname.replace('.', '/');
try {
byte[] bytes = JuiceAgentBridge.getClassBytesByName(internalName);
if (bytes != null) {
return bytes;
}
} catch (Throwable ignored) {
// The class may not be loaded yet.
}
if (loader == null) {
return null;
}
try {
Class.forName(classname, false, loader);
return JuiceAgentBridge.getClassBytesByName(internalName);
} catch (Throwable ignored) {
return null;
}
}
private static boolean isPlatformClass(String classname) {
return classname.startsWith("java.")
|| classname.startsWith("javax.")
|| classname.startsWith("jdk.")
|| classname.startsWith("sun.")
|| classname.startsWith("com.sun.")
|| classname.startsWith("javassist.")
|| classname.startsWith("org.greenrobot.")
|| classname.startsWith("com.google.gson.");
}
@Override
public URL find(String classname) {
return null;
}
}
@@ -2,7 +2,6 @@ package cn.xiaozhou233.orangex.hook;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.LoaderClassPath;
import java.io.ByteArrayInputStream;
@@ -12,21 +11,10 @@ public abstract class ClassHook {
protected abstract void transform(CtClass ctClass) throws Exception;
/**
* Fully qualified names of classes referenced by the injected code.
* Their packages are imported so the injected source can use simple names.
*/
protected String[] getInjectedClassNames() {
return new String[0];
}
public final byte[] transform(ClassLoader loader, byte[] classBytes)
throws Exception {
ClassPool pool = ClassPool.getDefault();
pool.appendClassPath(new LoaderClassPath(loader));
ClassPoolUtils.prepare(pool, getInjectedClassNames());
ClassPool pool = ClassPoolUtils.createPool(loader);
CtClass ctClass = pool.makeClass(
new ByteArrayInputStream(classBytes),
false
@@ -2,13 +2,17 @@ package cn.xiaozhou233.orangex.hook;
import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.LoaderClassPath;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
/**
* Javassist setup shared by all hooks.
*
* <p>A fresh pool is created for each transform instead of using
* {@link ClassPool#getDefault()}: on some launchers the current thread has a
* {@code null} context class loader, which makes the default pool's system
* path throw while resolving imported class names.</p>
*/
public final class ClassPoolUtils {
@@ -18,69 +22,66 @@ public final class ClassPoolUtils {
*/
private static final String ORANGEX_JAR_PROPERTY = "orangex.jar";
private static final Set<String> importedPackages = new HashSet<String>();
private static boolean classPathAdded;
private static boolean bridgeChecked;
/**
* Prepares {@code pool} for compiling injected code.
*
* <p>Solves two problems:</p>
*
* Creates a pool that can resolve:
* <ul>
* <li>{@link ClassPool#getDefault()} only knows the JVM class path. The
* OrangeX jar is injected into the game class loader at runtime, so it
* must be added explicitly, otherwise javassist cannot find OrangeX
* classes.</li>
* <li>Vanilla 1.8.8 contains an obfuscated class in the default package
* named {@code cn}, which collides with the first segment of our
* package. Javassist resolves qualified names from left to right, finds
* that class instead of the package, and fails with the misleading
* {@code no such class: cn$xiaozhou233...}. Importing the packages lets
* injected code use simple class names and avoids the collision.</li>
* <li>OrangeX classes from the injected jar;</li>
* <li>game classes from their runtime (post-transform) bytes through
* the agent, avoiding launchers whose class-loader resources still
* contain obfuscated names;</li>
* <li>anything else via the game loader and the system loader.</li>
* </ul>
*
* @param classNames fully qualified names of the classes referenced by the
* injected code; their packages are imported
* @param loader the game class loader
*/
public static synchronized void prepare(ClassPool pool, String... classNames) {
importPackages(pool, classNames);
if (classPathAdded) {
return;
}
classPathAdded = true;
public static ClassPool createPool(ClassLoader loader) {
ClassPool pool = new ClassPool(false);
File jar = orangeXJar();
if (jar == null) {
if (jar != null) {
try {
pool.insertClassPath(jar.getAbsolutePath());
System.out.println("[OrangeX] javassist classpath: "
+ jar.getAbsolutePath());
} catch (Throwable t) {
System.out.println("[OrangeX] Failed to add javassist classpath: "
+ jar.getAbsolutePath() + " (" + t + ")");
}
} else {
System.out.println("[OrangeX] WARNING: OrangeX.jar not found for javassist; "
+ "injected classes may fail to compile");
pool.insertClassPath(new ClassClassPath(ClassPoolUtils.class));
return;
}
try {
pool.insertClassPath(jar.getAbsolutePath());
System.out.println("[OrangeX] javassist classpath: " + jar.getAbsolutePath());
} catch (Throwable t) {
System.out.println("[OrangeX] Failed to add javassist classpath: "
+ jar.getAbsolutePath() + " (" + t + ")");
// Runtime bytes of already-loaded game classes (MCP-named even when
// the launcher's resource stream is still obfuscated).
pool.appendClassPath(new AgentClassPath(loader));
if (loader != null) {
pool.appendClassPath(new SafeClassPath(new LoaderClassPath(loader)));
}
}
private static void importPackages(ClassPool pool, String[] classNames) {
for (String className : classNames) {
int dot = className.lastIndexOf('.');
if (dot <= 0) {
continue;
}
ClassLoader system = ClassLoader.getSystemClassLoader();
if (system != null) {
pool.appendClassPath(new SafeClassPath(new LoaderClassPath(system)));
} else {
pool.appendClassPath(new ClassClassPath(Object.class));
}
String packageName = className.substring(0, dot);
if (importedPackages.add(packageName)) {
pool.importPackage(packageName);
if (!bridgeChecked) {
bridgeChecked = true;
try {
pool.get("orangexbridge.Hooks");
System.out.println("[OrangeX] javassist bridge OK");
} catch (Throwable t) {
System.out.println("[OrangeX] javassist bridge FAILED");
t.printStackTrace();
}
}
return pool;
}
private static File orangeXJar() {
@@ -6,17 +6,29 @@ import lombok.Getter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public final class HookManager {
@Getter
private static final HookManager INSTANCE = new HookManager();
/**
* Original (pre-injection) bytes of every hook target, keyed by dot name.
* Used by 1.8.9 screen generation so it never has to retransform a class
* that has already been patched.
*/
private static final Map<String, byte[]> TARGET_BYTES =
new ConcurrentHashMap<String, byte[]>();
private final List<ClassHook> hooks = new ArrayList<ClassHook>();
private HookManager() {
register(new TickHook());
register(new Render2DHook());
register(new GuiInputHook());
register(new KeyPressHook());
}
public void register(ClassHook hook) {
@@ -38,6 +50,7 @@ public final class HookManager {
if (classBytes == null) {
continue;
}
TARGET_BYTES.put(className, classBytes);
byte[] bytes = hook.transform(loader, classBytes);
JuiceAgentBridge.retransformClassByName(className, bytes);
@@ -47,4 +60,8 @@ public final class HookManager {
}
}
}
public static byte[] getTargetBytes(String className) {
return TARGET_BYTES.get(className);
}
}
@@ -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,37 @@
package cn.xiaozhou233.orangex.hook;
import javassist.ClassPath;
import java.io.InputStream;
import java.net.URL;
/**
* Wraps a {@link ClassPath} so launcher-specific exceptions are treated as
* "not found" instead of aborting Javassist's class path search.
*/
final class SafeClassPath implements ClassPath {
private final ClassPath delegate;
SafeClassPath(ClassPath delegate) {
this.delegate = delegate;
}
@Override
public InputStream openClassfile(String classname) {
try {
return delegate.openClassfile(classname);
} catch (Throwable ignored) {
return null;
}
}
@Override
public URL find(String classname) {
try {
return delegate.find(classname);
} catch (Throwable ignored) {
return null;
}
}
}
@@ -0,0 +1,90 @@
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 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",
"orangexbridge.Hooks.inputDraw($0, $1, $2);");
injectBefore(ctClass, "mouseClicked", "(III)V",
"if (orangexbridge.Hooks.inputClick($0, $1, $2, $3)) return;");
injectBefore(ctClass, "mouseReleased", "(III)V",
"if (orangexbridge.Hooks.inputRelease($0, $1, $2, $3)) return;");
injectBefore(ctClass, "mouseClickMove", "(IIIJ)V",
"orangexbridge.Hooks.inputDrag($0, $1, $2, $3);");
// Forward every key typed on our empty screen as an EventKey. The
// facade only consumes the toggle key so ESC and other keys keep
// their vanilla Screen behaviour.
injectBefore(ctClass, "keyTyped", "(CI)V",
"if (!orangexbridge.Legacy.isRepeatEvent()"
+ " && orangexbridge.Hooks.inputKeyTyped($0, $2)) return;");
// The empty screen is an overlay: it must not pause singleplayer.
injectAfter(ctClass, "doesGuiPauseGame", "()Z",
"if (orangexbridge.Hooks.isOurScreen($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,95 @@
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;
/**
* Key-press hook for both supported versions.
*
* <ul>
* <li>1.8.9: {@code KeyBinding#onTick(int)} is called for every key press
* while no screen is open. This keeps short taps from being missed
* between two 20 Hz client ticks.</li>
* <li>26.2: {@code KeyboardHandler#keyPress(long, int, KeyEvent)} is the
* GLFW callback and therefore runs for every key press, including while
* walking with no screen open. The input screen's own
* {@code Screen#keyPressed} is not enough because the game does not
* deliver keys to a screen that is not open.</li>
* </ul>
*/
public final class KeyPressHook extends ClassHook {
private static final String KEY_BINDING =
"net/minecraft/client/settings/KeyBinding";
private static final String KEYBOARD_HANDLER =
"net/minecraft/client/KeyboardHandler";
/** GLFW_PRESS. */
private static final int GLFW_PRESS = 1;
private static final RuntimeInfo runtimeInfo =
OrangeX.getInstance().getRuntimeInfo();
private static final MappingResolver resolver = MappingManager.getResolver();
@Override
protected String getTargetClass() {
switch (runtimeInfo.getMinecraftVersion()) {
case V1_8_9:
return resolver.mapClass(KEY_BINDING)
.getTargetName().replace("/", ".");
case V26_2:
return resolver.mapClass(KEYBOARD_HANDLER)
.getTargetName().replace("/", ".");
default:
return null;
}
}
@Override
protected void transform(CtClass ctClass) throws Exception {
switch (runtimeInfo.getMinecraftVersion()) {
case V1_8_9:
transformLegacy(ctClass);
break;
case V26_2:
transformModern(ctClass);
break;
default:
break;
}
}
private void transformLegacy(CtClass ctClass) throws Exception {
MappingMethod mapping = resolver.mapMethod(
KEY_BINDING, "onTick", "(I)V");
CtMethod method = ctClass.getMethod(
mapping.getTargetName(), mapping.getTargetDescriptor());
// $1 is the key code. Ignore auto-repeat so holding a key does not
// flood the EventBus. Every other key is forwarded as an EventKey.
method.insertBefore(
"if (!orangexbridge.Legacy.isRepeatEvent())"
+ " { orangexbridge.Hooks.inputKeyPressed($1); }");
}
private void transformModern(CtClass ctClass) throws Exception {
MappingMethod mapping = resolver.mapMethod(
KEYBOARD_HANDLER,
"keyPress",
"(JILnet/minecraft/client/input/KeyEvent;)V");
CtMethod method = ctClass.getMethod(
mapping.getTargetName(), mapping.getTargetDescriptor());
// $2 is the GLFW action (1 = press, 0 = release, 2 = repeat).
// $3 is the KeyEvent record; its key() is a GLFW key code, which the
// facade normalises to the 1.8.9 numbering.
method.insertBefore(
"if ($2 == " + GLFW_PRESS + ")"
+ " { orangexbridge.Hooks.inputGlfwKeyPressed($3.key()); }");
}
}
@@ -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 {
@@ -28,13 +32,6 @@ public final class Render2DHook extends ClassHook {
OrangeX.getInstance().getRuntimeInfo();
private static final MappingResolver resolver = MappingManager.getResolver();
@Override
protected String[] getInjectedClassNames() {
return new String[]{
"cn.xiaozhou233.orangex.event.facade.Render2DEvents"
};
}
@Override
protected String getTargetClass() {
switch (runtimeInfo.getMinecraftVersion()) {
@@ -104,7 +101,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("orangexbridge.Hooks.render2d(null, true);");
return;
} else {
MappingMethod target = resolver.mapMethod(
@@ -115,7 +112,7 @@ public final class Render2DHook extends ClassHook {
methodDescriptor = target.getTargetDescriptor();
}
CtMethod method = ctClass.getMethod(methodName, methodDescriptor);
method.insertAfter("Render2DEvents.fire(null);");
method.insertAfter("orangexbridge.Hooks.render2d(null, true);");
break;
}
case V26_2: {
@@ -125,7 +122,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("orangexbridge.Hooks.render2d($0, $2);");
break;
}
default:
@@ -18,16 +18,12 @@ public final class TickHook extends ClassHook {
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.TickEvents"};
}
@Override
protected String getTargetClass() {
switch (runtimeInfo.getMinecraftVersion()) {
case V1_8_9:
return resolver.mapClass("net/minecraft/client/Minecraft").getTargetName().replace("/", ".");
return resolver.mapClass("net/minecraft/client/Minecraft")
.getTargetName().replace("/", ".");
case V26_2:
return "net.minecraft.client.Minecraft";
default:
@@ -66,9 +62,8 @@ public final class TickHook extends ClassHook {
CtMethod method = ctClass.getMethod(methodName, methodDesc);
// Simple names: the package is imported by ClassPoolUtils.
// Fully qualified "cn.*" names collide with the vanilla "cn" class.
method.insertBefore("TickEvents.firePre();");
method.insertAfter("TickEvents.firePost();");
// Fully qualified bridge name avoids the default-package "cn" class.
method.insertBefore("orangexbridge.Hooks.tickPre();");
method.insertAfter("orangexbridge.Hooks.tickPost();");
}
}
@@ -0,0 +1,169 @@
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 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 boolean started;
private static boolean pendingOpen;
private static boolean pendingClose;
private ClientInput() {
}
/**
* Called once per client tick by {@link InputController}. The toggle
* itself is event-driven on every supported version; this only reconciles
* the tracked state with the actual Minecraft screen.
*/
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());
}
}
/**
* Applies queued open / close requests after the tick's keyboard and mouse
* handling.
*/
public static void applyPending(Minecraft minecraft) {
if (pendingOpen) {
pendingOpen = false;
if (!open && minecraft.isInWorld() && !minecraft.isScreenOpen()) {
minecraft.openInputScreen();
}
}
if (pendingClose) {
pendingClose = false;
if (open) {
minecraft.closeInputScreen();
}
}
}
public static void requestOpen() {
pendingOpen = true;
}
public static void requestClose() {
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;
}
/**
* 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;
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,62 @@
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;
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.
*/
public final class InputController {
private final Minecraft minecraft;
private boolean failureLogged;
public InputController(Minecraft minecraft) {
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 {
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,153 @@
package cn.xiaozhou233.orangex.input;
/**
* Canonical key codes used by {@link cn.xiaozhou233.orangex.event.impl.EventKey}.
*
* <p>All events use the 1.8.9 / LWJGL 2 numbering, regardless of the running
* Minecraft version. Modern versions report GLFW key codes, so
* {@link #fromGlfw(int)} translates them before the event is posted. Keys that
* did not exist in 1.8.9 map to {@link #NONE}.</p>
*/
public final class KeyCodes {
/** LWJGL 2 {@code Keyboard.KEY_NONE}. */
public static final int NONE = 0;
/** LWJGL 2 {@code Keyboard.KEY_M}. */
public static final int M = 50;
/**
* Translates a GLFW key code (26.x) to the 1.8.9 LWJGL 2 key code used by
* {@code EventKey}.
*/
public static int fromGlfw(int key) {
switch (key) {
// Printable keys.
case 32: return 57; // SPACE
case 39: return 40; // APOSTROPHE
case 44: return 51; // COMMA
case 45: return 12; // MINUS
case 46: return 52; // PERIOD
case 47: return 53; // SLASH
case 48: return 11; // 0
case 49: return 2; // 1
case 50: return 3; // 2
case 51: return 4; // 3
case 52: return 5; // 4
case 53: return 6; // 5
case 54: return 7; // 6
case 55: return 8; // 7
case 56: return 9; // 8
case 57: return 10; // 9
case 59: return 39; // SEMICOLON
case 61: return 13; // EQUAL
case 65: return 30; // A
case 66: return 48; // B
case 67: return 46; // C
case 68: return 32; // D
case 69: return 18; // E
case 70: return 33; // F
case 71: return 34; // G
case 72: return 35; // H
case 73: return 23; // I
case 74: return 36; // J
case 75: return 37; // K
case 76: return 38; // L
case 77: return 50; // M
case 78: return 49; // N
case 79: return 24; // O
case 80: return 25; // P
case 81: return 16; // Q
case 82: return 19; // R
case 83: return 31; // S
case 84: return 20; // T
case 85: return 22; // U
case 86: return 47; // V
case 87: return 17; // W
case 88: return 45; // X
case 89: return 21; // Y
case 90: return 44; // Z
case 91: return 26; // LEFT_BRACKET
case 92: return 43; // BACKSLASH
case 93: return 27; // RIGHT_BRACKET
case 96: return 41; // GRAVE_ACCENT
// Function keys.
case 256: return 1; // ESCAPE
case 257: return 28; // ENTER
case 258: return 15; // TAB
case 259: return 14; // BACKSPACE
case 260: return 210; // INSERT
case 261: return 211; // DELETE
case 262: return 205; // RIGHT
case 263: return 203; // LEFT
case 264: return 208; // DOWN
case 265: return 200; // UP
case 266: return 201; // PAGE_UP
case 267: return 209; // PAGE_DOWN
case 268: return 199; // HOME
case 269: return 207; // END
case 280: return 58; // CAPS_LOCK
case 281: return 70; // SCROLL_LOCK
case 282: return 69; // NUM_LOCK
case 283: return 183; // PRINT_SCREEN
case 284: return 197; // PAUSE
case 290: return 59; // F1
case 291: return 60; // F2
case 292: return 61; // F3
case 293: return 62; // F4
case 294: return 63; // F5
case 295: return 64; // F6
case 296: return 65; // F7
case 297: return 66; // F8
case 298: return 67; // F9
case 299: return 68; // F10
case 300: return 87; // F11
case 301: return 88; // F12
case 302: return 100; // F13
case 303: return 101; // F14
case 304: return 102; // F15
case 305: return 103; // F16
case 306: return 104; // F17
case 307: return 105; // F18
case 308: return 113; // F19
// Keypad.
case 320: return 82; // KP_0
case 321: return 79; // KP_1
case 322: return 80; // KP_2
case 323: return 81; // KP_3
case 324: return 75; // KP_4
case 325: return 76; // KP_5
case 326: return 77; // KP_6
case 327: return 71; // KP_7
case 328: return 72; // KP_8
case 329: return 73; // KP_9
case 330: return 83; // KP_DECIMAL
case 331: return 181; // KP_DIVIDE
case 332: return 55; // KP_MULTIPLY
case 333: return 74; // KP_SUBTRACT
case 334: return 78; // KP_ADD
case 335: return 156; // KP_ENTER
case 336: return 141; // KP_EQUAL
// Modifiers.
case 340: return 42; // LEFT_SHIFT
case 341: return 29; // LEFT_CONTROL
case 342: return 56; // LEFT_ALT
case 343: return 219; // LEFT_SUPER
case 344: return 54; // RIGHT_SHIFT
case 345: return 157; // RIGHT_CONTROL
case 346: return 184; // RIGHT_ALT
case 347: return 220; // RIGHT_SUPER
case 348: return 221; // MENU
default:
return NONE;
}
}
private KeyCodes() {
}
}
@@ -0,0 +1,42 @@
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();
double getGuiMouseX();
double getGuiMouseY();
}
@@ -0,0 +1,311 @@
package cn.xiaozhou233.orangex.input.internal.v1_8_9;
import cn.xiaozhou233.orangex.hook.ClassPoolUtils;
import cn.xiaozhou233.orangex.hook.HookManager;
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 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 {
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 = ClassPoolUtils.createPool(loader);
CtClass base;
byte[] cachedBase = HookManager.getTargetBytes(
guiScreenClass.getName());
if (cachedBase != null) {
// Prefer the original bytes captured before our hooks were
// applied: retransforming GuiScreen again could drop the
// injected methods.
base = pool.makeClass(new ByteArrayInputStream(cachedBase));
} else {
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);
}
}
/**
* 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,76 @@
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 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 {
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 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;
}
}
@@ -0,0 +1,147 @@
package cn.xiaozhou233.orangex.modules;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.input.KeyCodes;
import cn.xiaozhou233.orangex.value.BooleanValue;
import cn.xiaozhou233.orangex.value.KeybindValue;
import cn.xiaozhou233.orangex.value.ModeValue;
import cn.xiaozhou233.orangex.value.Value;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import com.google.gson.JsonObject;
import lombok.Getter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Getter
public abstract class Module {
protected final Minecraft mc = OrangeX.getInstance().getMinecraft();
protected final String name;
protected final ModuleCategory category;
protected boolean enabled = false;
private final Map<String, Value<?>> valueMap = new LinkedHashMap<>();
private final KeybindValue keybind;
public Module(String name, ModuleCategory category) {
this(name, category, KeyCodes.NONE);
}
public Module(String name, ModuleCategory category, int defaultKey) {
this.name = name;
this.category = category;
this.keybind = new KeybindValue("keybind", defaultKey);
valueMap.put(keybind.getName(), keybind);
}
/**
* Registers a value so it can be displayed by configuration UIs and
* persisted with the module.
*
* @return the same value, for fluent field initialisation.
*/
protected <V extends Value<?>> V addValue(V value) {
if (valueMap.containsKey(value.getName())) {
throw new IllegalArgumentException(
"Module '" + name + "' already has a value named '" + value.getName() + "'");
}
valueMap.put(value.getName(), value);
return value;
}
protected BooleanValue addBoolean(String name, boolean defaultValue) {
return addValue(new BooleanValue(name, defaultValue));
}
protected KeybindValue addKeybind(String name, int defaultKey) {
return addValue(new KeybindValue(name, defaultKey));
}
protected ModeValue addMode(String name, String defaultMode, String... modes) {
return addValue(new ModeValue(name, defaultMode, modes));
}
public Value<?> getValue(String name) {
return valueMap.get(name);
}
public List<Value<?>> getValues() {
return Collections.unmodifiableList(new ArrayList<>(valueMap.values()));
}
public List<Value<?>> getVisibleValues() {
List<Value<?>> visible = new ArrayList<>();
for (Value<?> value : valueMap.values()) {
if (value.isVisible()) {
visible.add(value);
}
}
return visible;
}
public void resetValues() {
for (Value<?> value : valueMap.values()) {
value.reset();
}
}
/**
* Encodes every value (including the module keybind) for configuration
* storage.
*/
public JsonObject valuesToJson() {
JsonObject json = new JsonObject();
for (Value<?> value : valueMap.values()) {
json.add(value.getName(), value.toJson());
}
return json;
}
/**
* Restores previously encoded values. Unknown keys are ignored.
*/
public void valuesFromJson(JsonObject json) {
if (json == null) {
return;
}
for (Value<?> value : valueMap.values()) {
if (json.has(value.getName())) {
value.fromJson(json.get(value.getName()));
}
}
}
protected void onEnable() {
System.out.println("[OrangeX] Enable " + name);
}
protected void onDisable() {
System.out.println("[OrangeX] Disable " + name);
}
public void setEnabled(boolean setEnabled) {
if (this.enabled == setEnabled) return;
this.enabled = setEnabled;
if (this.enabled) {
if (OrangeX.getInstance().getEventBus().isRegistered(this))
return;
try { OrangeX.getInstance().getEventBus().register(this); } catch (Exception ignored) {}
onEnable();
} else {
if (!OrangeX.getInstance().getEventBus().isRegistered(this))
return;
try { OrangeX.getInstance().getEventBus().unregister(this); } catch (Exception ignored) {}
onDisable();
}
}
public void toggle() {
setEnabled(!this.enabled);
}
}
@@ -0,0 +1,11 @@
package cn.xiaozhou233.orangex.modules;
public enum ModuleCategory {
RENDER,
COMBAT,
WORLD,
MISC,
MOVEMENT,
PLAYER,
FUN
}
@@ -0,0 +1,60 @@
package cn.xiaozhou233.orangex.modules;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.event.impl.EventKey;
import cn.xiaozhou233.orangex.modules.impl.render.HUD;
import org.greenrobot.eventbus.Subscribe;
import java.awt.*;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
public class ModuleManager {
private static final List<Module> modules = new CopyOnWriteArrayList<>();
public ModuleManager() {
}
public void init() {
registerAll();
OrangeX.getInstance().getEventBus().register(this);
}
public void registerAll() {
register(new HUD());
}
public void register(Module module) {
modules.add(module);
System.out.println("[ModuleManager] Registered module: " + module.getName());
}
public Module getModule(String name) {
return modules.stream()
.filter(m -> m.getName().equalsIgnoreCase(name))
.findFirst()
.orElse(null);
}
public List<Module> getModulesByCategory(ModuleCategory category) {
return modules.stream()
.filter(m -> m.getCategory() == category)
.collect(Collectors.toList());
}
public List<Module> getAllModules() {
return modules;
}
@Subscribe
public void onKey(EventKey event) {
for (Module module : modules) {
if (module.getKeybind().getValue() == event.getKey()) {
module.toggle();
System.out.println("[ModuleManager] Toggled module: " + module.getName());
}
}
}
}
@@ -0,0 +1,118 @@
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 org.greenrobot.eventbus.Subscribe;
import java.awt.Color;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
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 LOGO_START_X = 5;
private static final int LOGO_START_Y = 5;
private static final int MODULE_MARGIN = 6;
private static final int MODULE_SPACING = 4;
private static final int RAINBOW_OFFSET = 200;
public HUD() {
super("HUD", ModuleCategory.RENDER);
setEnabled(true);
}
@Subscribe
public void onRender2D(EventRender2D event) {
long currentTime = System.currentTimeMillis();
renderLogo(event, currentTime);
renderModuleList(event, currentTime);
}
private void renderLogo(EventRender2D event, long currentTime) {
String title = "OrangeX";
int x = LOGO_START_X;
int y = LOGO_START_Y;
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)
);
x += (int) event.getRender2D()
.getFont(LOGO_FONT_SIZE)
.getStringWidth(character);
}
}
private void renderModuleList(EventRender2D event, long currentTime) {
List<Module> modules = OrangeX.getInstance()
.getModuleManager()
.getAllModules()
.stream()
.filter(Module::isEnabled)
.sorted(Comparator.comparingDouble(
module -> -event.getRender2D()
.getFont(MODULE_FONT_SIZE)
.getStringWidth(module.getName())
))
.collect(Collectors.toList());
int screenWidth = event.getRender2D().getWidth();
int y = MODULE_MARGIN;
for (int i = 0; i < modules.size(); i++) {
Module module = modules.get(i);
String name = module.getName();
int textWidth = (int) event.getRender2D()
.getFont(MODULE_FONT_SIZE)
.getStringWidth(name);
int x = screenWidth - textWidth - MODULE_MARGIN;
event.getRender2D()
.getFont(MODULE_FONT_SIZE)
.drawStringWithShadow(
name,
x,
y,
getRainbowColor(currentTime, i)
);
y += (int) (
event.getRender2D()
.getFont(MODULE_FONT_SIZE)
.getStringHeight() + MODULE_SPACING
);
}
}
private int getRainbowColor(long currentTime, int index) {
long offset = (long) index * RAINBOW_OFFSET;
float hue = ((currentTime + offset) % (long) RAINBOW_CYCLE)
/ RAINBOW_CYCLE;
return Color.HSBtoRGB(hue, 0.9f, 1.0f);
}
}
@@ -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();
}
@@ -0,0 +1,38 @@
package cn.xiaozhou233.orangex.value;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
/**
* An on/off value, for example "enabled" or "show background".
*/
public class BooleanValue extends Value<Boolean> {
public BooleanValue(String name, boolean defaultValue) {
super(name, defaultValue);
}
public boolean isEnabled() {
return getValue();
}
public void setEnabled(boolean enabled) {
setValue(enabled);
}
public void toggle() {
setValue(!isEnabled());
}
@Override
public JsonElement toJson() {
return new JsonPrimitive(isEnabled());
}
@Override
public void fromJson(JsonElement json) {
if (isBoolean(json)) {
setValue(json.getAsBoolean());
}
}
}
@@ -0,0 +1,58 @@
package cn.xiaozhou233.orangex.value;
import cn.xiaozhou233.orangex.input.KeyCodes;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
/**
* A single key binding. The stored key always uses the canonical 1.8.9 /
* LWJGL 2 numbering used by
* {@link cn.xiaozhou233.orangex.event.impl.EventKey}; {@link KeyCodes#NONE}
* means the binding is unbound.
*/
public class KeybindValue extends Value<Integer> {
public KeybindValue(String name, int defaultKey) {
super(name, normalize(defaultKey));
}
public int getKey() {
return getValue();
}
public void setKey(int key) {
setValue(normalize(key));
}
public boolean isBound() {
return getKey() != KeyCodes.NONE;
}
public void clear() {
setKey(KeyCodes.NONE);
}
/**
* @param key canonical 1.8.9 (LWJGL 2) key code.
* @return whether this binding is set and matches {@code key}.
*/
public boolean matches(int key) {
return isBound() && getKey() == key;
}
private static int normalize(int key) {
return key < 0 ? KeyCodes.NONE : key;
}
@Override
public JsonElement toJson() {
return new JsonPrimitive(getKey());
}
@Override
public void fromJson(JsonElement json) {
if (isNumber(json)) {
setKey(json.getAsInt());
}
}
}
@@ -0,0 +1,97 @@
package cn.xiaozhou233.orangex.value;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* A value limited to a fixed list of named modes, for example
* "Vanilla" / "Packet" / "Spoof".
*/
public class ModeValue extends Value<String> {
private final List<String> modes;
public ModeValue(String name, String defaultMode, String... modes) {
this(name, defaultMode, Arrays.asList(modes));
}
public ModeValue(String name, String defaultMode, Collection<String> modes) {
super(name, defaultMode);
if (modes == null || modes.isEmpty()) {
throw new IllegalArgumentException("Mode value '" + name + "' needs at least one mode");
}
this.modes = Collections.unmodifiableList(new ArrayList<>(modes));
if (!this.modes.contains(defaultMode)) {
throw new IllegalArgumentException(
"Default mode '" + defaultMode + "' is not in " + this.modes);
}
}
public List<String> getModes() {
return modes;
}
public String getMode() {
return getValue();
}
public boolean is(String mode) {
return getValue().equals(mode);
}
@Override
public void setValue(String newValue) {
if (!modes.contains(newValue)) {
throw new IllegalArgumentException(
"Unknown mode '" + newValue + "' for value '" + getName() + "'");
}
super.setValue(newValue);
}
public int getIndex() {
return modes.indexOf(getValue());
}
/**
* Selects the next mode, wrapping around at the end.
*
* @return the newly selected mode.
*/
public String next() {
String next = modes.get((getIndex() + 1) % modes.size());
setValue(next);
return next;
}
/**
* Selects the previous mode, wrapping around at the start.
*
* @return the newly selected mode.
*/
public String previous() {
String previous = modes.get((getIndex() - 1 + modes.size()) % modes.size());
setValue(previous);
return previous;
}
@Override
public JsonElement toJson() {
return new JsonPrimitive(getValue());
}
@Override
public void fromJson(JsonElement json) {
if (isString(json)) {
String mode = json.getAsString();
if (modes.contains(mode)) {
setValue(mode);
}
}
}
}
@@ -0,0 +1,114 @@
package cn.xiaozhou233.orangex.value;
import com.google.gson.JsonElement;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* A named, typed configuration value owned by a module.
*
* <p>Values keep their default so a module can be reset to a known state.
* Subclasses add type-specific helpers and decide how the value is encoded for
* configuration storage via {@link #toJson()} and {@link #fromJson(JsonElement)}.</p>
*
* @param <T> stored value type.
*/
public abstract class Value<T> {
private final String name;
private final T defaultValue;
private T value;
private Supplier<Boolean> visibility = () -> true;
private Consumer<T> changeListener;
protected Value(String name, T defaultValue) {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("Value name must not be empty");
}
this.name = name;
this.defaultValue = defaultValue;
this.value = defaultValue;
}
public String getName() {
return name;
}
public T getValue() {
return value;
}
public void setValue(T newValue) {
if (Objects.equals(value, newValue)) {
return;
}
this.value = newValue;
if (changeListener != null) {
changeListener.accept(newValue);
}
}
public T getDefaultValue() {
return defaultValue;
}
public boolean isDefault() {
return Objects.equals(value, defaultValue);
}
public void reset() {
setValue(defaultValue);
}
/**
* Hides the value from configuration UIs while the condition is false.
*/
public Value<T> visibleWhen(Supplier<Boolean> condition) {
this.visibility = condition == null ? () -> true : condition;
return this;
}
public boolean isVisible() {
return Boolean.TRUE.equals(visibility.get());
}
/**
* Registers a callback invoked after the value actually changes.
*/
public Value<T> onChange(Consumer<T> listener) {
this.changeListener = listener;
return this;
}
/**
* Encodes the current value for configuration storage.
*/
public abstract JsonElement toJson();
/**
* Restores a previously encoded value. Invalid input is ignored so a
* malformed config never leaves a module in an unusable state.
*/
public abstract void fromJson(JsonElement json);
protected static boolean isBoolean(JsonElement json) {
return json != null && json.isJsonPrimitive() && json.getAsJsonPrimitive().isBoolean();
}
protected static boolean isNumber(JsonElement json) {
return json != null && json.isJsonPrimitive() && json.getAsJsonPrimitive().isNumber();
}
protected static boolean isString(JsonElement json) {
return json != null && json.isJsonPrimitive() && json.getAsJsonPrimitive().isString();
}
@Override
public String toString() {
return name + "=" + value;
}
}
@@ -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,47 @@ 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();
/**
* 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,70 @@ 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 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,69 @@ 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 double getGuiMouseX() {
return input().getGuiMouseX();
}
@Override
public double getGuiMouseY() {
return input().getGuiMouseY();
}
private Object resolveInstance() {
MappingField mappingField = mappingMinecraft.getField(INSTANCE_FIELD);
if (mappingField == null) {
@@ -0,0 +1,74 @@
package orangexbridge;
import cn.xiaozhou233.orangex.event.facade.InputEvents;
import cn.xiaozhou233.orangex.event.facade.Render2DEvents;
import cn.xiaozhou233.orangex.event.facade.TickEvents;
/**
* Injection bridge.
*
* <p>Injected Javassist snippets call this class by its fully-qualified name.
* The package must not start with {@code cn}: vanilla 1.8.9 has an obfuscated
* class named {@code cn} in the default package, which makes Javassist treat
* {@code cn.xiaozhou233...} as a field access instead of a class name.</p>
*
* <p>Using a fixed full name also avoids depending on
* {@code ClassPool#importPackage}, which can be unreliable on launchers with
* custom class loaders.</p>
*/
public final class Hooks {
public static void tickPre() {
TickEvents.firePre();
}
public static void tickPost() {
TickEvents.firePost();
}
public static void render2d(Object context, boolean inWorld) {
Render2DEvents.fire(context, inWorld);
}
public static void render2d(Object context) {
Render2DEvents.fire(context);
}
public static void inputDraw(Object screen, int mouseX, int mouseY) {
InputEvents.onDrawScreen(screen, mouseX, mouseY);
}
public static boolean inputClick(Object screen, int mouseX,
int mouseY, int button) {
return InputEvents.onMouseClicked(screen, mouseX, mouseY, button);
}
public static boolean inputRelease(Object screen, int mouseX,
int mouseY, int button) {
return InputEvents.onMouseReleased(screen, mouseX, mouseY, button);
}
public static void inputDrag(Object screen, int mouseX,
int mouseY, int button) {
InputEvents.onMouseDragged(screen, mouseX, mouseY, button);
}
public static boolean inputKeyTyped(Object screen, int keyCode) {
return InputEvents.onKeyTyped(screen, keyCode);
}
public static void inputKeyPressed(int keyCode) {
InputEvents.onKeyPressed(keyCode);
}
public static void inputGlfwKeyPressed(int glfwKeyCode) {
InputEvents.onGlfwKeyPressed(glfwKeyCode);
}
public static boolean isOurScreen(Object screen) {
return InputEvents.isOurInputScreen(screen);
}
private Hooks() {
}
}
@@ -0,0 +1,19 @@
package orangexbridge;
import cn.xiaozhou233.orangex.input.internal.v1_8_9.V1_8_9Input;
/**
* 1.8.9-only injection bridge.
*
* <p>Kept separate from {@link Hooks} so a 26.2 runtime never has to resolve
* the LWJGL 2 classes used by {@link V1_8_9Input}.</p>
*/
public final class Legacy {
public static boolean isRepeatEvent() {
return V1_8_9Input.isRepeatEvent();
}
private Legacy() {
}
}
+5
View File
@@ -3,3 +3,8 @@
## 项目重构中, 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)
## 支持注入的版本
| Minecraft Version | Vanilla | Forge | Fabric | Badlion Client | MCP |
|:-----------------:|:-------:|:-----:|:------:|:--------------:|:---:|
| 1.8.9 | ✓ | ✓ | — | ✓ | ✓ |
| 26.2 | ✓ | ✗ | ✓ | — | — |
+8
View File
@@ -1,6 +1,7 @@
plugins {
id 'base'
}
apply from: 'gradle/dependencies.gradle'
def outputDir = layout.projectDirectory.dir('out/tmp')
def distDir = layout.projectDirectory.dir('out')
@@ -45,6 +46,7 @@ tasks.register('injectionZip', Zip) {
tasks.register('packageAll') {
group = 'build'
description = 'Builds Loader, OrangeX and Injector, then zips out/tmp into out/injection.zip'
dependsOn downloadDependencies
dependsOn cleanOut
dependsOn ':Loader:shadowJar', ':OrangeX:shadowJar', ':Injector:jar'
dependsOn injectionZip
@@ -70,3 +72,9 @@ subprojects {
mustRunAfter rootProject.tasks.named('cleanOut')
}
}
gradle.taskGraph.whenReady { taskGraph ->
if (taskGraph.hasTask(':build')) {
throw new GradleException('---> The build task is not supported. Please refer to the documentation. <---')
}
}
+50 -27
View File
@@ -17,7 +17,7 @@
├── hook.getTargetClass() 目标类(点分名)
├── JuiceAgent.getClassBytesByName(...) 读取原始字节码
├── hook.transform(loader, bytes)
│ ├── ClassPoolUtils.prepare(...) 准备 Javassist 环境
│ ├── ClassPoolUtils.createPool(loader) 新建 Javassist 环境
│ ├── transform(ctClass) 插入调用
│ └── ctClass.toBytecode() 生成新字节码
└── JuiceAgent.retransformClassByName(...) 写回 JVM
@@ -31,7 +31,9 @@
| --- | --- | --- |
| `HookManager` | `hook/HookManager` | 注册所有 Hook,遍历、读取字节码、触发重转换 |
| `ClassHook` | `hook/ClassHook` | Hook 基类:目标类、注入逻辑、注入代码引用的类 |
| `ClassPoolUtils` | `hook/ClassPoolUtils` | 准备 Javassist `ClassPool`(导入包、加入 OrangeX.jar) |
| `ClassPoolUtils` | `hook/ClassPoolUtils` | 创建 Javassist `ClassPool`(OrangeX.jar + agent 字节 + loader) |
| `AgentClassPath` | `hook/AgentClassPath` | 用 agent 读取已加载类的运行时字节,兼容 Lunar 等启动器 |
| `orangexbridge.Hooks` | `orangexbridge/Hooks` | 注入代码统一入口,避免 `cn` 默认包冲突 |
| `JuiceAgentBridge` | `hook/JuiceAgentBridge` | 通过 system ClassLoader 反射调用 JuiceAgent API(Fabric 必需) |
| `TickHook` | `hook/impl/TickHook` | 在 `Minecraft.runTick()` 前后插入事件调用 |
| `TickEvents` | `event/facade/TickEvents` | 注入代码唯一引用的门面,负责 post 事件 |
@@ -142,11 +144,9 @@ MappingMethod m = resolver.mapMethod("net/minecraft/client/Minecraft", "runTick"
## 4. 注入代码的硬性规则
### 4.1 不要写全限定名(1.8.8 的 `cn` 类)
### 4.1 注入代码统一走 `orangexbridge`
Vanilla 1.8.8 的客户端 jar 里有一个**默认包**下的混淆类 `cn`(`1.8.8.jar!/cn.class`)。
Javassist 解析限定名是从左往右的,写:
Vanilla 1.8.8 的客户端 jar 里有一个**默认包**下的混淆类 `cn`(`1.8.8.jar!/cn.class`)。Javassist 解析限定名是从左往右的,写:
```java
method.insertBefore("cn.xiaozhou233.orangex.event.facade.TickEvents.firePre();");
@@ -158,38 +158,46 @@ method.insertBefore("cn.xiaozhou233.orangex.event.facade.TickEvents.firePre();")
no such class: cn$xiaozhou233.orangex.event.facade.TickEvents
```
这**不是** classpath 问题,加多少类路径都没用。正确做法是让 `ClassPoolUtils` 导入包,注入代码里只写简单类名:
这**不是** classpath 问题,加多少类路径都没用。现在所有注入代码都通过一个不会和默认包冲突的顶层包:
```java
@Override
protected String[] getInjectedClassNames() {
return new String[]{"cn.xiaozhou233.orangex.event.facade.TickEvents"};
}
// 注入时:
method.insertBefore("TickEvents.firePre();");
method.insertBefore("orangexbridge.Hooks.tickPre();");
```
`getInjectedClassNames()` 返回的类所在的包会被 `pool.importPackage(...)` 导入,Javassist 会通过 `searchImports` 找到 `TickEvents`,不再触发 `cn` 冲突。
`orangexbridge.Hooks` 只是转发到真正的 facade;1.8.9 专用的辅助方法在 `orangexbridge.Legacy`。这样不需要 `importPackage`,也不会触发 `cn` 冲突。
### 4.2 被引用的类必须对 Javassist 可见
`ClassPool.getDefault()` 只认识 JVM 启动时的 classpath,而 OrangeX.jar 是运行时注入的。`Loader` 会设置系统属性:
`Loader` 会设置系统属性:
```java
System.setProperty("orangex.jar", orangexFile.getAbsolutePath());
```
`ClassPoolUtils.prepare(...)` 读取该属性,把 jar 加到 `ClassPool` 的 classpath。因此:
`ClassPoolUtils.createPool(loader)` 会读取该属性,把 OrangeX.jar 放在 classpath 第一位,因此 `orangexbridge.*` 和 `cn.xiaozhou233.*` 都能从 jar 直接解析。
- 新增 Hook 时,凡是注入代码引用到的类,都要放进 `getInjectedClassNames()`;
- 不要绕过 `ClassHook.transform()` 自己创建 `ClassPool`,否则会缺少这些准备。
游戏类则由 `AgentClassPath` 通过 `JuiceAgent#getClassBytesByName` 提供**运行时字节码**。原因是一些启动器(例如 Lunar 的 GenesisClassLoader)按 MCP 名字提供资源,但资源里的字节仍然是混淆名,Javassist 会报:
### 4.3 `ClassPool` 是单例
```text
cannot find net.minecraft.util.IThreadListener: od found in net/minecraft/util/IThreadListener.class
```
`ClassPool.getDefault()` 返回全局单例,`ClassPoolUtils` 只会往里面加一次路径/导入项。不要在每个 Hook 里重复 `insertClassPath`,否则路径会无限增长。
从 agent 拿到已加载类的字节可以保证类名和目标类一致。
`ClassHook.transform()` 在最后会 `ctClass.detach()`,避免 `ClassPool` 长期持有一个不可回收的 `CtClass`。
### 4.3 `ClassPool` 不再用全局单例
`ClassPoolUtils.createPool(loader)` 每次创建一个新的 `ClassPool(false)`,包含:
```text
OrangeX.jar
AgentClassPath(已加载游戏类的运行时字节)
LoaderClassPath(game loader) 兜底
LoaderClassPath(system loader) JDK 类
```
不再使用 `ClassPool.getDefault()`:某些启动器的注入线程 `Thread.currentThread().getContextClassLoader()` 为 `null`,`getDefault()` 的系统路径会在解析类时抛异常。
`ClassHook.transform()` 最后会 `ctClass.detach()`,避免 `ClassPool` 长期持有 `CtClass`。
### 4.4 异常不要外泄
@@ -250,8 +258,9 @@ OrangeX.getInstance().getEventBus().register(new Object() {
| 现象 | 原因 |
| --- | --- |
| `no such class: cn$xiaozhou233...` | 注入代码写了全限定名,撞上 1.8.8 的 `cn` 类。改成 `getInjectedClassNames` + 简单类名 |
| `no such class: TickEvents` | `getInjectedClassNames()` 没声明该类,或 OrangeX.jar 没加入 `ClassPool` |
| `no such class: cn$xiaozhou233...` | 注入代码写了 `cn.*` 全限定名,撞上 1.8.8 的 `cn` 类。统一改用 `orangexbridge.Hooks` |
| `cannot find net.minecraft...: od found in ...` | Lunar / Genesis 等启动器的类资源仍是混淆名。确认 `AgentClassPath` 生效,并且日志里有 `javassist bridge OK` |
| `[OrangeX] javassist bridge FAILED` | OrangeX.jar 没放进 `ClassPool`,或部署的 jar 是旧版本(缺少 `orangexbridge`) |
| `CannotCompileException`,`getMethod` 抛 `NotFoundException` | 版本不对/方法名或描述符错误,检查 `MappingResolver` |
| 日志有 `[OrangeX] javassist classpath: ...` 但无事件打印 | 注入成功但没触发:确认目标方法真的每帧调用(1.8.x `runTick()V`,26.2 `runTick(Z)V`) |
| 事件 post 了但 `@Subscribe` 不执行 | 没注册 / 不是同一个 `EventBus` / 方法不是 `public` |
@@ -267,10 +276,24 @@ OrangeX/src/main/java/cn/xiaozhou233/orangex/
│ ├── HookManager.java
│ ├── ClassHook.java
│ ├── ClassPoolUtils.java
│ ├── AgentClassPath.java
│ ├── SafeClassPath.java
│ ├── JuiceAgentBridge.java
│ └── impl/TickHook.java
│ └── impl/
│ ├── TickHook.java
│ ├── Render2DHook.java
│ ├── GuiInputHook.java
│ └── KeyPressHook.java
└── event/
├── Event.java
├── facade/TickEvents.java
└── impl/EventTickPre.java, EventTickPost.java
├── facade/
│ ├── TickEvents.java
│ ├── Render2DEvents.java
│ ├── KeyEvents.java
│ └── InputEvents.java
└── impl/EventTickPre.java, EventTickPost.java, EventRender2D.java, EventKey.java
OrangeX/src/main/java/orangexbridge/
├── Hooks.java 注入代码统一入口
└── Legacy.java 1.8.9 专用(LWJGL 2)
```
+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)
## 阅读前提
+424
View File
@@ -0,0 +1,424 @@
# 世界内渲染与鼠标输入
本文记录两件事:
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_3InputScreen`(输入状态记录在 `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_3Input` 内部):
```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 订阅 EventKey 并驱动 ClientInput
│ ├── KeyCodes.java 统一的按键编号(1.8.9 LWJGL 2)+ GLFW 转换
│ ├── 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
│ └── V26_2InputScreen.java 26.2 空 Screen
├── event/
│ ├── facade/InputEvents.java 输入门面(1.8.9 注入代码)
│ ├── facade/KeyEvents.java 按键事件统一投递到 EventBus
│ └── impl/EventKey.java 按键事件(统一使用 1.8.9 key code)
└── hook/impl/
├── GuiInputHook.java 1.8.9 GuiScreen 输入 / 按键 Hook
└── KeyPressHook.java 1.8.9 KeyBinding#onTick / 26.2 KeyboardHandler#keyPress 按键 Hook
```
行为:
- M 键在**世界内**打开空 GUI;再次按下关闭。
- 所有 `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 关闭:`GuiScreen#keyTyped(char, int)` → `InputEvents.onKeyTyped` → 同一条 EventBus 链路 → `requestClose()`
- 26.2:`KeyboardHandler#keyPress(long, int, KeyEvent)` 全局 Hook → `InputEvents.onGlfwKeyPressed` → 键码转换 → 同一条 EventBus 链路。行走、无界面时也能收到按键,不再依赖 tick 轮询。
- 其他功能可以直接 `@Subscribe` `EventKey` 读取按键,不需要再改注入代码。
- 打开 / 关闭都只在 tick 末尾(`EventTickPost` → `ClientInput.applyPending`)真正执行。
- 原因:如果在键盘循环里直接打开 Screen,同一个 M 事件会立刻被 `currentScreen.handleKeyboardInput()` 再处理一次,导致刚打开就关闭。
- 自动重复事件:1.8.9 通过 `Keyboard.isRepeatEvent()` 过滤,26.2 只处理 GLFW action == 1(press),按住 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(不打包)
```
+91
View File
@@ -0,0 +1,91 @@
import java.security.MessageDigest
def downloadFiles = [
[
name: 'Minecraft26.2.jar',
url: 'https://piston-data.mojang.com/v1/objects/2dc72797acbc1b63fc16a11c4ac393605f453754/client.jar',
path: 'libraries/minecraft/Minecraft26.2.jar',
sha1: '2dc72797acbc1b63fc16a11c4ac393605f453754'
],
[
name: 'brigadier-1.3.10.jar',
url: 'https://libraries.minecraft.net/com/mojang/brigadier/1.3.10/brigadier-1.3.10.jar',
path: 'libraries/minecraft/com/mojang/brigadier/1.3.10/brigadier-1.3.10.jar',
sha1: 'd15b53a14cf20fdcaa98f731af5dda654452c010'
]
]
def downloadDependencies = tasks.register('downloadDependencies') {
outputs.files(downloadFiles.collect {
rootProject.file(it.path)
})
doLast {
downloadFiles.each { dependency ->
File target = rootProject.file(dependency.path)
if (target.exists()) {
String checksum = MessageDigest.getInstance('SHA-1')
.digest(target.bytes)
.encodeHex()
.toString()
if (checksum == dependency.sha1) {
println "[OrangeX] Already downloaded: ${dependency.name}"
return
}
}
target.parentFile.mkdirs()
File temp = new File(target.parentFile, target.name + '.tmp')
try {
println "[OrangeX] Downloading: ${dependency.name}"
def connection = new URL(dependency.url).openConnection()
connection.connectTimeout = 15000
connection.readTimeout = 120000
connection.inputStream.withCloseable { input ->
temp.withOutputStream { output ->
output << input
}
}
String checksum = MessageDigest.getInstance('SHA-1')
.digest(temp.bytes)
.encodeHex()
.toString()
if (checksum != dependency.sha1) {
throw new GradleException(
"SHA-1 mismatch: ${dependency.name}"
)
}
if (!temp.renameTo(target)) {
throw new GradleException(
"Failed to move: ${dependency.name}"
)
}
println "[OrangeX] Downloaded: ${dependency.name}"
} finally {
temp.delete()
}
}
}
}
tasks.named('build') {
dependsOn downloadDependencies
}
rootProject.subprojects {
tasks.withType(JavaCompile).configureEach {
dependsOn downloadDependencies
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
#Thu Oct 22 20:28:16 CST 2026
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+1
View File
@@ -0,0 +1 @@
minecraft/
Binary file not shown.