Compare commits

...
5 Commits
Author SHA1 Message Date
xiaozhou233 8b9dbce0f7 Refactor: Make runtime detection extensible and Java 8 compatible
Split the runtime package into small, single-purpose pieces so new loaders and Minecraft versions can be added by registration instead of editing control flow.

- Add LoaderProbe registry for mod loader detection

- Add VersionSignatureRegistry/VersionSignature and move structural version signatures out of VersionDetector

- Add VersionIdSource list for Forge/NeoForge metadata readers

- Extract ModernVersionDetector and CandidateClassLoaders

- Replace MinecraftVersion's mutable static id with RuntimeInfo.versionId

- Target Java 8 with source/target 1.8 and --release 8 on JDK 9+

- Add docs/adding-minecraft-versions.md
2026-11-04 01:04:50 +08:00
xiaozhou233 789303c665 Refactor: Move Minecraft runtime detection into OrangeX
Move the full runtime package from Loader to OrangeX (cn.xiaozhou233.orangex.runtime), including loader/version detection, probes and utils.

- OrangeX.start() now detects and stores RuntimeInfo, and prints runtime debug info

- Loader keeps only a self-contained GameClassLoaderResolver for bootstrapping the Minecraft ClassLoader; entry flow is otherwise unchanged

- Move gson dependency to OrangeX with shadow relocation; drop it from Loader
2026-11-04 00:45:58 +08:00
xiaozhou233 34fc410a0c Feat: Add default JuiceAgent config
Configure the built-in jar loader to load Loader.jar and call Loader.entry.
2026-10-27 20:12:42 +08:00
xiaozhou233 faa84b14d0 Feat: Add Injector and injection packaging
- Add Injector module, built to out/injector.jar
- Add packageAll chain producing out/injection.zip from out/tmp
- Copy resources and natives into out/tmp with a flat layout
2026-10-27 20:12:37 +08:00
xiaozhou233 60baa8d1ef Refactor: Detect Minecraft runtime in Loader
- Add runtime detection package for class loader, loader type and version
- Probe vanilla, Forge, NeoForge, Fabric and MCP installations
- Read 26.x versions from version.json and support Forge version lookups
- Unify structural probing in MinecraftProbe and use the game class loader for reflection
- Shade gson into the loader jar under a relocated package
- Restore OrangeX injection using the detected class loader
2026-10-27 20:12:31 +08:00
40 changed files with 1732 additions and 8 deletions

No files matched your search

+1
View File
@@ -8,6 +8,7 @@
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/Injector" />
<option value="$PROJECT_DIR$/Loader" />
<option value="$PROJECT_DIR$/Minecraft1.8.8" />
<option value="$PROJECT_DIR$/OrangeX" />
+17
View File
@@ -0,0 +1,17 @@
<component name="ProjectRunConfigurationManager">
<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="WORKING_DIRECTORY" value="$PROJECT_DIR$/out" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="cn.xiaozhou233.orangex.injector.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true" />
<option name="RunConfigurationTask" enabled="true" run_configuration_name="OrangeX-Client [packageAll]" run_configuration_type="GradleRunConfiguration" />
</method>
</configuration>
</component>
+31
View File
@@ -0,0 +1,31 @@
plugins {
id 'java'
}
group = 'cn.xiaozhou233.orangex.injector'
version = 'unspecified'
repositories {
mavenCentral()
}
dependencies {
testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
}
test {
useJUnitPlatform()
}
tasks.named('jar') {
destinationDirectory = rootProject.layout.projectDirectory.dir('out')
archiveFileName = 'injector.jar'
manifest {
attributes 'Main-Class': 'cn.xiaozhou233.orangex.injector.Main'
}
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
}
@@ -0,0 +1,22 @@
package cn.xiaozhou233.juiceagent.injector;
public class Injector {
/*
* @param pid process id
* @param path libinject path
*/
public native static boolean inject(int pid, String path);
/*
* @param pid process id
* @param path libinject path
* @param configDir config directory
*/
public native static boolean inject(int pid, String path, String configDir);
/*
* @param keyword window title keyword
* @return windows with title containing keyword
*/
public static native WindowInfo[] findWindowsByTitle(String keyword);
}
@@ -0,0 +1,16 @@
package cn.xiaozhou233.juiceagent.injector;
public class WindowInfo {
public String title;
public int pid;
public WindowInfo(String title, int pid) {
this.title = title;
this.pid = pid;
}
@Override
public String toString() {
return String.format("Title: %-30s | PID: %d", title, pid);
}
}
@@ -0,0 +1,39 @@
package cn.xiaozhou233.orangex.injector;
import java.io.*;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class FileUtils {
public static void unzip(InputStream zipInputStream, File destDir) throws IOException {
if (!destDir.exists()) {
destDir.mkdirs(); // 创建目标目录
}
try (ZipInputStream zipIn = new ZipInputStream(zipInputStream)) {
ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
File outFile = new File(destDir, entry.getName());
if (entry.isDirectory()) {
outFile.mkdirs(); // 创建目录
} else {
File parent = outFile.getParentFile();
if (!parent.exists()) {
parent.mkdirs(); // 创建父目录
}
try (BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(outFile.toPath()))) {
byte[] buffer = new byte[4096];
int read;
while ((read = zipIn.read(buffer)) != -1) {
bos.write(buffer, 0, read);
}
}
}
zipIn.closeEntry();
}
}
}
}
@@ -0,0 +1,95 @@
package cn.xiaozhou233.orangex.injector;
import cn.xiaozhou233.juiceagent.injector.Injector;
import cn.xiaozhou233.juiceagent.injector.WindowInfo;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static String orangexPath = new File(System.getProperty("user.home") + "/.orangex").getAbsolutePath();
private static int pid = -1;
public static void main(String[] args) {
System.out.println("================");
System.out.println("OrangeX Injector v1.0.0");
System.out.println("OrangeX Path: " + orangexPath);
System.out.println("================");
// Unzip injection
File zipFile = new File("./injection.zip");
if (!zipFile.exists()) {
System.err.println("injection.zip not found!");
}
try (InputStream zipStream = new FileInputStream(zipFile)) {
FileUtils.unzip(zipStream, new File(orangexPath));
System.out.println("Done!");
} catch (IOException e) {
e.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);
}
}
+5 -1
View File
@@ -12,9 +12,13 @@ repositories {
dependencies {
implementation files("../libraries/JuiceAgent-API-1.4.1+build.1.jar")
// Source: https://mvnrepository.com/artifact/org.projectlombok/lombok
compileOnly 'org.projectlombok:lombok:1.18.48'
annotationProcessor 'org.projectlombok:lombok:1.18.48'
}
tasks.named('shadowJar') {
destinationDirectory = rootProject.layout.projectDirectory.dir('out/tmp')
archiveFileName = "${project.name}.jar"
}
}
@@ -1,6 +1,7 @@
package cn.xiaozhou233.orangex.loader;
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
import cn.xiaozhou233.orangex.loader.classloader.GameClassLoaderResolver;
import java.io.File;
@@ -15,6 +16,9 @@ public class Loader {
public static void entry() {
System.out.println("OrangeX-Loader " + VERSION + " loaded!");
// Resolve the Minecraft ClassLoader (runtime detection itself lives in OrangeX)
ClassLoader gameClassLoader = GameClassLoaderResolver.resolve();
// Find client thread
for (Thread t : Thread.getAllStackTraces().keySet()) {
if ("Client thread".equals(t.getName())) {
@@ -26,8 +30,13 @@ public class Loader {
throw new IllegalStateException("Cannot find Minecraft client thread");
}
// Get Minecraft ClassLoader
minecraftClassLoader = clientThread.getContextClassLoader();
// Get Minecraft ClassLoader (prefer the resolved game class loader)
minecraftClassLoader = gameClassLoader != null
? gameClassLoader
: clientThread.getContextClassLoader();
if (minecraftClassLoader == null) {
throw new IllegalStateException("Cannot find Minecraft ClassLoader");
}
System.out.println("Minecraft ClassLoader: " + minecraftClassLoader);
// Dev Only: Load JuiceAgent
@@ -60,4 +69,4 @@ public class Loader {
public static boolean isDevEnvironment() {
return Boolean.getBoolean("orangex.dev");
}
}
}
@@ -0,0 +1,91 @@
package cn.xiaozhou233.orangex.loader.classloader;
/**
* Loader-side bootstrap resolver: only resolves the Minecraft game class loader,
* which is required before OrangeX can be injected. Full runtime detection
* (loader type / Minecraft version) lives in OrangeX.
*/
public final class GameClassLoaderResolver {
public static ClassLoader resolve() {
ClassLoader loader = findGameThreadLoader();
if (loader != null) {
return loader;
}
loader = findMinecraftLoader(Thread.currentThread().getContextClassLoader());
if (loader != null) {
return loader;
}
return Thread.currentThread().getContextClassLoader();
}
private static ClassLoader findGameThreadLoader() {
// Client thread wins over render thread, regardless of thread iteration order
ClassLoader clientLoader = null;
ClassLoader renderLoader = null;
try {
for (Thread thread : Thread.getAllStackTraces().keySet()) {
String name = thread.getName();
if ("Client thread".equals(name)) {
if (clientLoader == null) {
clientLoader = thread.getContextClassLoader();
}
} else if ("Render thread".equals(name)) {
if (renderLoader == null) {
renderLoader = thread.getContextClassLoader();
}
}
}
} catch (Throwable ignored) {
}
return clientLoader != null ? clientLoader : renderLoader;
}
private static ClassLoader findMinecraftLoader(ClassLoader candidate) {
if (candidate == null) {
return null;
}
String[] minecraftClasses = {
"net.minecraft.client.Minecraft",
"net.minecraft.class_310"
};
Class<?> minecraftClass = findClass(candidate, minecraftClasses);
if (minecraftClass != null) {
ClassLoader minecraftLoader = minecraftClass.getClassLoader();
return minecraftLoader == null ? candidate : minecraftLoader;
}
return null;
}
private static Class<?> findClass(ClassLoader loader, String... names) {
if (loader == null || names == null) {
return null;
}
for (String name : names) {
if (name == null || name.isEmpty()) {
continue;
}
String binaryName = name.indexOf('/') >= 0 ? name.replace('/', '.') : name;
try {
return Class.forName(binaryName, false, loader);
} catch (Throwable ignored) {
}
}
return null;
}
private GameClassLoaderResolver() {
}
}
+7
View File
@@ -14,9 +14,16 @@ dependencies {
// Source: https://mvnrepository.com/artifact/org.projectlombok/lombok
compileOnly 'org.projectlombok:lombok:1.18.48'
annotationProcessor 'org.projectlombok:lombok:1.18.48'
// Source: https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation 'com.google.code.gson:gson:2.15.0'
}
tasks.named('shadowJar') {
destinationDirectory = rootProject.layout.projectDirectory.dir('out/tmp')
archiveFileName = "${project.name}.jar"
}
shadowJar {
relocate 'com.google.gson', 'cn.xiaozhou233.orangex.shaded.gson'
}
@@ -1,20 +1,28 @@
package cn.xiaozhou233.orangex;
import cn.xiaozhou233.orangex.runtime.RuntimeDetector;
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
import lombok.Getter;
public class OrangeX {
@Getter
private static final OrangeX instance = new OrangeX();
@Getter
private RuntimeInfo runtimeInfo;
public OrangeX() {
System.out.println("OrangeX <init> start!");
}
public void start() {
System.out.println("OrangeX start!");
runtimeInfo = RuntimeDetector.detect();
RuntimeDetector.debug(runtimeInfo);
}
public void stop() {
System.out.println("OrangeX stop!");
}
}
}
@@ -0,0 +1,75 @@
package cn.xiaozhou233.orangex.runtime;
import cn.xiaozhou233.orangex.runtime.classloader.GameClassLoaderResolver;
import cn.xiaozhou233.orangex.runtime.loader.LoaderDetector;
import cn.xiaozhou233.orangex.runtime.loader.LoaderType;
import cn.xiaozhou233.orangex.runtime.version.MinecraftVersion;
import cn.xiaozhou233.orangex.runtime.version.VersionDetector;
/**
* Entry point for Minecraft runtime detection.
*
* <p>Each step has a single owner, so the pipeline stays easy to extend:</p>
* <ol>
* <li>{@link GameClassLoaderResolver} - find the game class loader.</li>
* <li>{@link LoaderDetector} - identify the mod loader.</li>
* <li>{@link VersionDetector} - resolve the Minecraft version.</li>
* </ol>
*/
public final class RuntimeDetector {
public static RuntimeInfo detect() {
ClassLoader classLoader = GameClassLoaderResolver.resolve();
LoaderType loaderType = LoaderDetector.detect(classLoader);
int versionId = VersionDetector.detectId(classLoader, loaderType);
return new RuntimeInfo(
classLoader,
loaderType,
MinecraftVersion.fromId(versionId),
versionId
);
}
public static void debug(RuntimeInfo runtime) {
System.out.println("======== Minecraft Runtime Info ========");
if (runtime == null) {
System.out.println("RuntimeInfo: null");
System.out.println("========================================");
return;
}
ClassLoader loader = runtime.getMinecraftClassLoader();
MinecraftVersion version = runtime.getMinecraftVersion();
System.out.println("Minecraft ClassLoader: " + loader);
System.out.println("Context ClassLoader (current thread): "
+ Thread.currentThread().getContextClassLoader());
printHierarchy(loader);
System.out.println("Loader Type: "
+ (runtime.getLoaderType() == null ? "UNKNOWN" : runtime.getLoaderType().name()));
System.out.println("Minecraft Version: "
+ (version == null ? "UNKNOWN" : version.name())
+ " (version id " + runtime.getVersionId() + ")");
System.out.println("========================================");
}
private static void printHierarchy(ClassLoader loader) {
if (loader == null) {
return;
}
StringBuilder hierarchy = new StringBuilder(loader.getClass().getName());
ClassLoader parent = loader.getParent();
while (parent != null) {
hierarchy.append(" -> ").append(parent.getClass().getName());
parent = parent.getParent();
}
System.out.println("ClassLoader Hierarchy: " + hierarchy);
}
private RuntimeDetector() {
}
}
@@ -0,0 +1,28 @@
package cn.xiaozhou233.orangex.runtime;
import cn.xiaozhou233.orangex.runtime.loader.LoaderType;
import cn.xiaozhou233.orangex.runtime.version.MinecraftVersion;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Immutable result of runtime detection.
*/
@Getter
@AllArgsConstructor
public final class RuntimeInfo {
private final ClassLoader minecraftClassLoader;
private final LoaderType loaderType;
private final MinecraftVersion minecraftVersion;
/**
* OrangeX internal version id. Kept even when {@link #minecraftVersion} is
* unknown, so diagnostics can still show what was detected.
*/
private final int versionId;
public boolean isKnown() {
return !minecraftVersion.isUnknown();
}
}
@@ -0,0 +1,38 @@
package cn.xiaozhou233.orangex.runtime.classloader;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Collects every class loader that may define Minecraft classes.
*
* <p>The primary loader is tried first, so detection stays deterministic when
* several loaders can see the same classes.</p>
*/
public final class CandidateClassLoaders {
public static Set<ClassLoader> of(ClassLoader primary) {
Set<ClassLoader> loaders = new LinkedHashSet<>();
add(loaders, primary);
add(loaders, Thread.currentThread().getContextClassLoader());
add(loaders, CandidateClassLoaders.class.getClassLoader());
try {
add(loaders, ClassLoader.getSystemClassLoader());
} catch (SecurityException ignored) {
// Security manager may forbid system loader lookup.
}
return loaders;
}
private static void add(Set<ClassLoader> loaders, ClassLoader loader) {
if (loader != null) {
loaders.add(loader);
}
}
private CandidateClassLoaders() {
}
}
@@ -0,0 +1,67 @@
package cn.xiaozhou233.orangex.runtime.classloader;
import cn.xiaozhou233.orangex.runtime.probe.ClassProbe;
public final class GameClassLoaderResolver {
public static ClassLoader resolve() {
ClassLoader loader = findGameThreadLoader();
if (loader != null) {
return loader;
}
loader = findMinecraftLoader(Thread.currentThread().getContextClassLoader());
if (loader != null) {
return loader;
}
return Thread.currentThread().getContextClassLoader();
}
private static ClassLoader findGameThreadLoader() {
// Client thread wins over render thread, regardless of thread iteration order
ClassLoader clientLoader = null;
ClassLoader renderLoader = null;
try {
for (Thread thread : Thread.getAllStackTraces().keySet()) {
String name = thread.getName();
if ("Client thread".equals(name)) {
if (clientLoader == null) {
clientLoader = thread.getContextClassLoader();
}
} else if ("Render thread".equals(name)) {
if (renderLoader == null) {
renderLoader = thread.getContextClassLoader();
}
}
}
} catch (Throwable ignored) {
}
return clientLoader != null ? clientLoader : renderLoader;
}
private static ClassLoader findMinecraftLoader(ClassLoader candidate) {
if (candidate == null) {
return null;
}
String[] minecraftClasses = {
"net.minecraft.client.Minecraft",
"net.minecraft.class_310"
};
Class<?> minecraftClass = ClassProbe.find(candidate, minecraftClasses);
if (minecraftClass != null) {
ClassLoader minecraftLoader = minecraftClass.getClassLoader();
return minecraftLoader == null ? candidate : minecraftLoader;
}
return null;
}
private GameClassLoaderResolver() {
}
}
@@ -0,0 +1,27 @@
package cn.xiaozhou233.orangex.runtime.loader;
import cn.xiaozhou233.orangex.runtime.probe.ClassProbe;
/**
* Matches a loader when at least one of its marker classes is present.
*/
public final class ClassPresenceLoaderProbe implements LoaderProbe {
private final LoaderType type;
private final String[] markers;
public ClassPresenceLoaderProbe(LoaderType type, String... markers) {
this.type = type;
this.markers = markers.clone();
}
@Override
public LoaderType type() {
return type;
}
@Override
public boolean matches(ClassLoader loader) {
return ClassProbe.exists(loader, markers);
}
}
@@ -0,0 +1,50 @@
package cn.xiaozhou233.orangex.runtime.loader;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Identifies the mod loader by running an ordered list of {@link LoaderProbe}s.
*
* <p>To support a new mod loader, add a probe to {@link #PROBES} and a matching
* value to {@link LoaderType}.</p>
*/
public final class LoaderDetector {
/**
* Order matters:
* <ol>
* <li>NeoForge before Forge, because NeoForge is a Forge fork.</li>
* <li>MCP before VANILLA, because MCP is a deobfuscated environment.</li>
* </ol>
*/
private static final List<LoaderProbe> PROBES = Collections.unmodifiableList(Arrays.<LoaderProbe>asList(
new ClassPresenceLoaderProbe(LoaderType.NEOFORGE,
"net.neoforged.fml.ModList",
"net.neoforged.fml.loading.FMLLoader"),
new ClassPresenceLoaderProbe(LoaderType.FORGE,
"net.minecraftforge.fml.common.Loader",
"net.minecraftforge.fml.loading.FMLLoader"),
new ClassPresenceLoaderProbe(LoaderType.FABRIC,
"net.fabricmc.loader.api.FabricLoader"),
new McpLoaderProbe()
));
public static LoaderType detect(ClassLoader loader) {
if (loader == null) {
return LoaderType.UNKNOWN;
}
for (LoaderProbe probe : PROBES) {
if (probe.matches(loader)) {
return probe.type();
}
}
return LoaderType.VANILLA;
}
private LoaderDetector() {
}
}
@@ -0,0 +1,11 @@
package cn.xiaozhou233.orangex.runtime.loader;
/**
* One way to recognize a mod loader. Probes are checked in registration order.
*/
public interface LoaderProbe {
LoaderType type();
boolean matches(ClassLoader loader);
}
@@ -0,0 +1,10 @@
package cn.xiaozhou233.orangex.runtime.loader;
public enum LoaderType {
VANILLA,
MCP,
FORGE,
NEOFORGE,
FABRIC,
UNKNOWN
}
@@ -0,0 +1,30 @@
package cn.xiaozhou233.orangex.runtime.loader;
import cn.xiaozhou233.orangex.runtime.probe.ClassProbe;
/**
* MCP is a deobfuscated development environment: it exposes real class names
* but no mod loader.
*/
public final class McpLoaderProbe implements LoaderProbe {
@Override
public LoaderType type() {
return LoaderType.MCP;
}
@Override
public boolean matches(ClassLoader loader) {
Class<?> minecraftClass = ClassProbe.find(loader, "net.minecraft.client.Minecraft");
if (minecraftClass == null) {
return false;
}
try {
minecraftClass.getDeclaredMethod("getMinecraft");
return true;
} catch (Throwable ignored) {
return false;
}
}
}
@@ -0,0 +1,24 @@
/**
* Minecraft runtime detection.
*
* <p>Detection flows in a fixed order:</p>
* <ol>
* <li>{@link cn.xiaozhou233.orangex.runtime.classloader.GameClassLoaderResolver}
* finds the game class loader.</li>
* <li>{@link cn.xiaozhou233.orangex.runtime.loader.LoaderDetector}
* identifies the mod loader.</li>
* <li>{@link cn.xiaozhou233.orangex.runtime.version.VersionDetector}
* resolves the internal version id: loader metadata, then 26.x
* {@code version.json}, then structural signatures.</li>
* </ol>
*
* <p>Extending detection:</p>
* <ul>
* <li>New mod loader: add a {@code LoaderProbe} to {@code LoaderDetector}.</li>
* <li>New Minecraft version: add a {@code VersionSignature} to
* {@code VersionSignatureRegistry} (and an enum value if needed).</li>
* <li>New loader version metadata: add a {@code VersionIdSource} to
* {@code VersionIdSources}.</li>
* </ul>
*/
package cn.xiaozhou233.orangex.runtime;
@@ -0,0 +1,41 @@
package cn.xiaozhou233.orangex.runtime.probe;
/**
* Small reflection helper for checking whether classes are visible to a loader.
*
* <p>Accepts both binary names ({@code net.minecraft.client.Minecraft}) and
* internal names ({@code net/minecraft/client/Minecraft}).</p>
*/
public final class ClassProbe {
public static boolean exists(ClassLoader loader, String... names) {
return find(loader, names) != null;
}
public static Class<?> find(ClassLoader loader, String... names) {
if (loader == null || names == null) {
return null;
}
for (String name : names) {
if (name == null || name.isEmpty()) {
continue;
}
try {
return Class.forName(toBinaryName(name), false, loader);
} catch (Throwable ignored) {
// Missing classes are expected while probing.
}
}
return null;
}
private static String toBinaryName(String name) {
return name.indexOf('/') >= 0 ? name.replace('/', '.') : name;
}
private ClassProbe() {
}
}
@@ -0,0 +1,77 @@
package cn.xiaozhou233.orangex.runtime.probe;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* Matches a {@link MinecraftSignature} against a class loader.
*/
public final class MinecraftProbe {
private final MinecraftSignature signature;
public MinecraftProbe(MinecraftSignature signature) {
this.signature = signature;
}
/**
* The game class and every anchor must be defined by the same class loader,
* otherwise classes inherited from a parent loader can produce false
* positives.
*/
public boolean matches(ClassLoader loader) {
Class<?> minecraftClass = ClassProbe.find(loader, signature.minecraftClass());
if (minecraftClass == null) {
return false;
}
ClassLoader definingLoader = minecraftClass.getClassLoader();
if (definingLoader == null) {
return false;
}
for (String anchor : signature.anchors()) {
Class<?> anchorClass = ClassProbe.find(definingLoader, anchor);
if (anchorClass == null || anchorClass.getClassLoader() != definingLoader) {
return false;
}
}
return matchesStructure(minecraftClass);
}
private boolean matchesStructure(Class<?> minecraftClass) {
try {
if (!matchesGetter(minecraftClass)) {
return false;
}
return matchesInstanceField(minecraftClass);
} catch (ReflectiveOperationException | SecurityException | LinkageError e) {
return false;
}
}
private boolean matchesGetter(Class<?> minecraftClass) throws NoSuchMethodException {
String getterName = signature.instanceGetter();
if (getterName == null || getterName.isEmpty()) {
return true;
}
Method getter = minecraftClass.getDeclaredMethod(getterName);
return Modifier.isStatic(getter.getModifiers())
&& getter.getReturnType() == minecraftClass;
}
private boolean matchesInstanceField(Class<?> minecraftClass) throws NoSuchFieldException {
String fieldName = signature.instanceField();
if (fieldName == null || fieldName.isEmpty()) {
// Some Minecraft versions do not expose a singleton field.
return true;
}
Field instance = minecraftClass.getDeclaredField(fieldName);
return Modifier.isStatic(instance.getModifiers())
&& instance.getType() == minecraftClass;
}
}
@@ -0,0 +1,65 @@
package cn.xiaozhou233.orangex.runtime.probe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Declarative description of the Minecraft entry class for one mapping set.
*
* <p>A version is recognized by locating {@link #minecraftClass()} and checking
* that its singleton getter/field and a set of anchor classes all belong to the
* same class loader. A signature therefore proves both the version and the
* class loader that owns the game classes.</p>
*/
public final class MinecraftSignature {
private final String minecraftClass;
private final String instanceGetter;
private final String instanceField;
private final List<String> anchors;
/**
* @param minecraftClass game entry class, binary or internal name
* @param instanceGetter static getter returning the singleton, or {@code null}
* @param instanceField static singleton field, or {@code null}
* @param anchors classes that must be defined by the same loader
*/
public MinecraftSignature(String minecraftClass,
String instanceGetter,
String instanceField,
List<String> anchors) {
this.minecraftClass = minecraftClass;
this.instanceGetter = instanceGetter;
this.instanceField = instanceField;
this.anchors = Collections.unmodifiableList(new ArrayList<String>(anchors));
}
public static MinecraftSignature of(String minecraftClass,
String instanceGetter,
String instanceField,
String... anchors) {
return new MinecraftSignature(
minecraftClass,
instanceGetter,
instanceField,
Arrays.asList(anchors));
}
public String minecraftClass() {
return minecraftClass;
}
public String instanceGetter() {
return instanceGetter;
}
public String instanceField() {
return instanceField;
}
public List<String> anchors() {
return anchors;
}
}
@@ -0,0 +1,77 @@
package cn.xiaozhou233.orangex.runtime.utils;
import cn.xiaozhou233.orangex.runtime.version.MinecraftVersion;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
/**
* Reads metadata bundled with the running Minecraft client.
*/
public final class MinecraftUtils {
/**
* Reads {@code /version.json} and maps the 26.x version family to an
* internal version id.
*
* @return the internal id, or {@link MinecraftVersion#UNKNOWN_ID} when the
* metadata is missing or does not describe a 26.x client
*/
public static int readModernVersionId(Class<?> minecraftClass) {
try (InputStream stream = minecraftClass.getResourceAsStream("/version.json")) {
if (stream == null) {
return MinecraftVersion.UNKNOWN_ID;
}
JsonElement element = JsonParser.parseReader(new InputStreamReader(
stream, StandardCharsets.UTF_8));
if (!element.isJsonObject()) {
return MinecraftVersion.UNKNOWN_ID;
}
JsonObject version = element.getAsJsonObject();
int javaVersion = getInteger(version, "java_version");
if (javaVersion != Integer.MIN_VALUE && javaVersion < 25) {
return MinecraftVersion.UNKNOWN_ID;
}
String id = getString(version, "id");
String name = getString(version, "name");
if (id == null || !id.equals(name)) {
return MinecraftVersion.UNKNOWN_ID;
}
if (isFamily(id, "26.1")) {
return MinecraftVersion.V26_1.getId();
}
if (isFamily(id, "26.2")) {
return MinecraftVersion.V26_2.getId();
}
return MinecraftVersion.UNKNOWN_ID;
} catch (Exception | LinkageError ignored) {
return MinecraftVersion.UNKNOWN_ID;
}
}
private static boolean isFamily(String id, String family) {
return id.startsWith(family)
&& (id.length() == family.length() || id.charAt(family.length()) == '.');
}
private static String getString(JsonObject object, String name) {
JsonElement value = object.get(name);
return value != null && value.isJsonPrimitive() ? value.getAsString() : null;
}
private static int getInteger(JsonObject object, String name) {
JsonElement value = object.get(name);
return value != null && value.isJsonPrimitive() ? value.getAsInt() : Integer.MIN_VALUE;
}
private MinecraftUtils() {
}
}
@@ -0,0 +1,36 @@
package cn.xiaozhou233.orangex.runtime.utils;
import java.lang.reflect.Field;
public class ReflectUtils {
public static Object readStaticField(String className, String fieldName) throws Exception {
return readStaticField(null, className, fieldName);
}
/**
* @param loader the class loader used to resolve the owner class; when
* {@code null} the caller's class loader is used
*/
public static Object readStaticField(ClassLoader loader, String className, String fieldName) throws Exception {
Class<?> owner = loadClass(loader, className);
Field field;
try {
field = owner.getField(fieldName);
}
catch (NoSuchFieldException ignored) {
field = owner.getDeclaredField(fieldName);
}
field.setAccessible(true);
return field.get(null);
}
/**
* @param loader the class loader used to resolve the class; when
* {@code null} the caller's class loader is used
*/
public static Class<?> loadClass(ClassLoader loader, String className) throws ClassNotFoundException {
return loader == null
? Class.forName(className)
: Class.forName(className, false, loader);
}
}
@@ -0,0 +1,52 @@
package cn.xiaozhou233.orangex.runtime.version;
/**
* Parses Forge/NeoForge version strings into OrangeX internal version ids.
*
* <p>Some Forge lines use ids that differ from Minecraft's own numbering, so a
* couple of values are remapped explicitly. Any other value is accepted only
* when it matches a known {@link MinecraftVersion}.</p>
*/
public final class ForgeVersionParser {
private static final int NOT_FOUND = -1;
public static int parse(Object value) {
if (value == null) {
return NOT_FOUND;
}
String text = String.valueOf(value).trim();
int start = 0;
while (start < text.length() && !Character.isDigit(text.charAt(start))) {
start++;
}
int end = start;
while (end < text.length() && Character.isDigit(text.charAt(end))) {
end++;
}
if (start == end) {
return NOT_FOUND;
}
try {
int parsed = Integer.parseInt(text.substring(start, end));
if (parsed == 62) {
return MinecraftVersion.V26_1.getId();
}
if (parsed == 65) {
return MinecraftVersion.V26_2.getId();
}
return MinecraftVersion.fromId(parsed).isUnknown() ? NOT_FOUND : parsed;
} catch (NumberFormatException ignored) {
return NOT_FOUND;
}
}
private ForgeVersionParser() {
}
}
@@ -0,0 +1,54 @@
package cn.xiaozhou233.orangex.runtime.version;
import lombok.Getter;
/**
* Minecraft versions supported by OrangeX.
*
* <p>The numbers are OrangeX's internal version ids, <strong>not</strong>
* Minecraft network protocol numbers (for example, 1.8.9 is id 15 here, while
* its network protocol is 47).</p>
*/
@Getter
public enum MinecraftVersion {
V1_7_10(13),
V1_8_9(15),
V1_12_2(23),
V1_14_4(28),
V1_16_5(35),
V1_16_5_ACTUAL(36),
V1_17(37),
V1_20_1(47),
V1_20_6(50),
V1_21_0(51),
V1_21_1(52),
V1_21_4(54),
V1_21_5(55),
V1_21_6(56),
V1_21_10(60),
V1_21_11(61),
V26_1(100),
V26_2(110),
UNKNOWN(0);
public static final int UNKNOWN_ID = 0;
private final int id;
MinecraftVersion(int id) {
this.id = id;
}
public boolean isUnknown() {
return this == UNKNOWN;
}
public static MinecraftVersion fromId(int id) {
for (MinecraftVersion version : values()) {
if (version.id == id) {
return version;
}
}
return UNKNOWN;
}
}
@@ -0,0 +1,75 @@
package cn.xiaozhou233.orangex.runtime.version;
import cn.xiaozhou233.orangex.runtime.classloader.CandidateClassLoaders;
import cn.xiaozhou233.orangex.runtime.probe.ClassProbe;
import cn.xiaozhou233.orangex.runtime.probe.MinecraftProbe;
import cn.xiaozhou233.orangex.runtime.probe.MinecraftSignature;
import cn.xiaozhou233.orangex.runtime.utils.MinecraftUtils;
/**
* Detects the 26.x line from class structure plus the bundled
* {@code version.json} metadata.
*
* <p>This runs before structural signatures: once a 26.x client is confirmed,
* older NeoForge signatures must not be considered (they share class names).</p>
*/
public final class ModernVersionDetector {
private static final String MINECRAFT_CLASS = "net/minecraft/client/Minecraft";
private static final MinecraftProbe MINECRAFT_PROBE = new MinecraftProbe(
MinecraftSignature.of(MINECRAFT_CLASS, "getInstance", "instance"));
public static int detect(ClassLoader primaryLoader) {
for (ClassLoader loader : CandidateClassLoaders.of(primaryLoader)) {
int versionId = detectIn(loader);
if (versionId != MinecraftVersion.UNKNOWN_ID) {
return versionId;
}
}
return MinecraftVersion.UNKNOWN_ID;
}
private static int detectIn(ClassLoader loader) {
Class<?> minecraftClass = resolveClass(loader, MINECRAFT_CLASS);
if (minecraftClass == null) {
return MinecraftVersion.UNKNOWN_ID;
}
ClassLoader definingLoader = minecraftClass.getClassLoader();
if (definingLoader == null || !MINECRAFT_PROBE.matches(loader)) {
return MinecraftVersion.UNKNOWN_ID;
}
if (!hasExpectedHierarchy(definingLoader)) {
return MinecraftVersion.UNKNOWN_ID;
}
return MinecraftUtils.readModernVersionId(minecraftClass);
}
private static boolean hasExpectedHierarchy(ClassLoader loader) {
Class<?> clientLevel = resolveClass(loader, "net/minecraft/client/multiplayer/ClientLevel");
Class<?> localPlayer = resolveClass(loader, "net/minecraft/client/player/LocalPlayer");
Class<?> abstractClientPlayer = resolveClass(loader, "net/minecraft/client/player/AbstractClientPlayer");
Class<?> level = resolveClass(loader, "net/minecraft/world/level/Level");
return clientLevel != null
&& localPlayer != null
&& abstractClientPlayer != null
&& level != null
&& clientLevel.getSuperclass() == level
&& localPlayer.getSuperclass() == abstractClientPlayer;
}
private static Class<?> resolveClass(ClassLoader loader, String internalName) {
try {
return Class.forName(internalName.replace('/', '.'), false, loader);
} catch (ClassNotFoundException | LinkageError | SecurityException e) {
return null;
}
}
private ModernVersionDetector() {
}
}
@@ -0,0 +1,33 @@
package cn.xiaozhou233.orangex.runtime.version;
import cn.xiaozhou233.orangex.runtime.loader.LoaderType;
/**
* Resolves the internal Minecraft version id.
*
* <p>Detection order, from most to least reliable:</p>
* <ol>
* <li>Loader-provided Forge/NeoForge metadata.</li>
* <li>The 26.x {@code version.json} family.</li>
* <li>Structural class signatures.</li>
* </ol>
*/
public final class VersionDetector {
public static int detectId(ClassLoader loader, LoaderType loaderType) {
int versionId = VersionIdSources.resolve(loader);
if (versionId != MinecraftVersion.UNKNOWN_ID) {
return versionId;
}
versionId = ModernVersionDetector.detect(loader);
if (versionId != MinecraftVersion.UNKNOWN_ID) {
return versionId;
}
return VersionSignatureRegistry.detect(loader, loaderType).getId();
}
private VersionDetector() {
}
}
@@ -0,0 +1,17 @@
package cn.xiaozhou233.orangex.runtime.version;
/**
* Reads an internal Minecraft version id from loader-provided metadata.
*
* <p>Sources are intentionally small and independent so new loader versions can
* be supported by adding one entry to {@link VersionIdSources}.</p>
*/
@FunctionalInterface
public interface VersionIdSource {
/**
* @return an internal version id, or {@link MinecraftVersion#UNKNOWN_ID}
* when this source has no answer
*/
int resolve(ClassLoader loader);
}
@@ -0,0 +1,99 @@
package cn.xiaozhou233.orangex.runtime.version;
import cn.xiaozhou233.orangex.runtime.utils.ReflectUtils;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Ordered readers for Forge/NeoForge version metadata.
*
* <p>The first source that returns a known id wins. Every source is fail-safe:
* missing classes, fields or methods simply fall through to the next one.</p>
*/
public final class VersionIdSources {
private static final List<VersionIdSource> SOURCES =
Collections.unmodifiableList(Arrays.<VersionIdSource>asList(
VersionIdSources::legacyForgeMinorVersion,
VersionIdSources::fmlLoaderForgeVersion,
VersionIdSources::forgeVersionField,
VersionIdSources::fmlVersionInfoForgeVersion
));
public static int resolve(ClassLoader loader) {
for (VersionIdSource source : SOURCES) {
int versionId = source.resolve(loader);
if (versionId != MinecraftVersion.UNKNOWN_ID) {
return versionId;
}
}
return MinecraftVersion.UNKNOWN_ID;
}
/**
* Legacy Forge already exposes an internal-style version id.
*/
private static int legacyForgeMinorVersion(ClassLoader loader) {
try {
Object minorVersion = ReflectUtils.readStaticField(loader,
"net.minecraftforge.common.ForgeVersion", "minorVersion");
if (minorVersion instanceof Number) {
return ((Number) minorVersion).intValue();
}
return MinecraftVersion.UNKNOWN_ID;
} catch (Throwable ignored) {
return MinecraftVersion.UNKNOWN_ID;
}
}
/**
* Modern Forge / NeoForge: {@code FMLLoader.forgeVersion}.
*/
private static int fmlLoaderForgeVersion(ClassLoader loader) {
try {
Object forgeVersion = ReflectUtils.readStaticField(loader,
"net.minecraftforge.fml.loading.FMLLoader", "forgeVersion");
return parse(forgeVersion);
} catch (Throwable ignored) {
return MinecraftVersion.UNKNOWN_ID;
}
}
/**
* Newer Forge: {@code ForgeVersion.forgeVersion}.
*/
private static int forgeVersionField(ClassLoader loader) {
try {
Object forgeVersion = ReflectUtils.readStaticField(loader,
"net.minecraftforge.common.ForgeVersion", "forgeVersion");
return parse(forgeVersion);
} catch (Throwable ignored) {
return MinecraftVersion.UNKNOWN_ID;
}
}
/**
* Newest Forge: {@code FMLLoader.versionInfo().forgeVersion()}.
*/
private static int fmlVersionInfoForgeVersion(ClassLoader loader) {
try {
Class<?> fmlLoader = ReflectUtils.loadClass(loader,
"net.minecraftforge.fml.loading.FMLLoader");
Object versionInfo = fmlLoader.getMethod("versionInfo").invoke(null);
Object forgeVersion = versionInfo.getClass().getMethod("forgeVersion").invoke(versionInfo);
return parse(forgeVersion);
} catch (Throwable ignored) {
return MinecraftVersion.UNKNOWN_ID;
}
}
private static int parse(Object forgeVersion) {
int parsed = ForgeVersionParser.parse(forgeVersion);
return parsed >= 0 ? parsed : MinecraftVersion.UNKNOWN_ID;
}
private VersionIdSources() {
}
}
@@ -0,0 +1,55 @@
package cn.xiaozhou233.orangex.runtime.version;
import cn.xiaozhou233.orangex.runtime.loader.LoaderType;
import cn.xiaozhou233.orangex.runtime.probe.MinecraftProbe;
import cn.xiaozhou233.orangex.runtime.probe.MinecraftSignature;
/**
* One recognizable form of a Minecraft version.
*
* <p>A version can have several signatures (for example vanilla obfuscated
* names, Fabric intermediary names and NeoForge Mojang mappings). Matching is
* intentionally conservative: the registry only accepts a version when exactly
* one version matches, so overlapping class names cannot produce a guess.</p>
*/
public final class VersionSignature {
private final MinecraftVersion version;
private final LoaderType requiredLoader;
private final MinecraftProbe probe;
public VersionSignature(MinecraftVersion version,
LoaderType requiredLoader,
MinecraftSignature signature) {
this.version = version;
this.requiredLoader = requiredLoader;
this.probe = new MinecraftProbe(signature);
}
/**
* A signature that is valid for any mod loader.
*/
public static VersionSignature anyLoader(MinecraftVersion version,
MinecraftSignature signature) {
return new VersionSignature(version, null, signature);
}
/**
* A signature that only applies to one mod loader (for example NeoForge or
* Fabric mapping sets).
*/
public static VersionSignature forLoader(LoaderType loader,
MinecraftVersion version,
MinecraftSignature signature) {
return new VersionSignature(version, loader, signature);
}
public MinecraftVersion version() {
return version;
}
public boolean matches(ClassLoader loader, LoaderType loaderType) {
return (requiredLoader == null || requiredLoader == loaderType)
&& probe.matches(loader);
}
}
@@ -0,0 +1,117 @@
package cn.xiaozhou233.orangex.runtime.version;
import cn.xiaozhou233.orangex.runtime.classloader.CandidateClassLoaders;
import cn.xiaozhou233.orangex.runtime.loader.LoaderType;
import cn.xiaozhou233.orangex.runtime.probe.MinecraftSignature;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static cn.xiaozhou233.orangex.runtime.loader.LoaderType.FABRIC;
import static cn.xiaozhou233.orangex.runtime.loader.LoaderType.NEOFORGE;
import static cn.xiaozhou233.orangex.runtime.version.MinecraftVersion.*;
/**
* Registry of structural version signatures.
*
* <p><strong>To add a Minecraft version:</strong> add the enum value to
* {@link MinecraftVersion} and one signature below. For a brand-new version
* family (for example a new version.json scheme), also update
* {@link ModernVersionDetector}.</p>
*
* <p>Matching is conservative: if two different versions match, the result is
* {@link MinecraftVersion#UNKNOWN}. This prevents overlapping mapping sets
* (such as adjacent NeoForge versions) from silently resolving to the wrong
* version.</p>
*/
public final class VersionSignatureRegistry {
private static final List<VersionSignature> SIGNATURES =
Collections.unmodifiableList(Arrays.<VersionSignature>asList(
// Vanilla, obfuscated client classes
VersionSignature.anyLoader(V1_8_9, obf("ave", "A", "S", "bew", "adm")),
VersionSignature.anyLoader(V1_12_2, obf("bib", "z", "R", "bud", "amu")),
VersionSignature.anyLoader(V1_16_5_ACTUAL, obf("djz", "C", "F", "dwt", "dzm", "dzj", "brx")),
VersionSignature.anyLoader(V1_20_1, obf("enn", "N", "F", "few", "fiy", "fiv", "cmm")),
VersionSignature.anyLoader(V1_20_6, obf("ffh", "Q", "E", "fxx", "gcs", "gcp", "dca")),
VersionSignature.anyLoader(V1_21_1, obf("fgo", "Q", "E", "fzf", "geb", "gdy", "dcw")),
VersionSignature.anyLoader(V1_21_11, obf("gfj", "V", "A", "hif", "hnh", "hne", "dwo")),
// MCP development environment (real 1.8.9 names, no mod loader)
VersionSignature.anyLoader(V1_8_9, mojang(
"net.minecraft.client.Minecraft", "getMinecraft", "theMinecraft",
"net.minecraft.client.entity.EntityPlayerSP",
"net.minecraft.client.gui.GuiIngame",
"net.minecraft.client.renderer.EntityRenderer",
"net.minecraft.client.network.NetHandlerPlayClient")),
// NeoForge uses Mojang mappings
VersionSignature.forLoader(NEOFORGE, V1_20_1, mojang(
"net/minecraft/client/Minecraft", "getInstance", "instance",
"net/minecraft/client/multiplayer/ClientLevel",
"net/minecraft/client/player/LocalPlayer",
"net/minecraft/client/player/AbstractClientPlayer",
"net/minecraft/world/level/Level")),
VersionSignature.forLoader(NEOFORGE, V1_21_1, mojang(
"net/minecraft/client/Minecraft", "getInstance", "instance",
"net/minecraft/client/multiplayer/ClientLevel",
"net/minecraft/client/player/LocalPlayer",
"net/minecraft/client/player/AbstractClientPlayer",
"net/minecraft/world/level/Level",
"net/minecraft/world/item/component/ItemContainerContents")),
// Fabric uses intermediary names
VersionSignature.forLoader(FABRIC, V1_21_11, intermediary(
"net/minecraft/class_310", "method_1551", "field_1700",
"net/minecraft/class_638", "net/minecraft/class_746",
"net/minecraft/class_742", "net/minecraft/class_1937",
"com/mojang/blaze3d/buffers/GpuBuffer",
"com/mojang/blaze3d/systems/CommandEncoder"))
));
public static MinecraftVersion detect(ClassLoader primaryLoader, LoaderType loaderType) {
MinecraftVersion match = null;
for (ClassLoader loader : CandidateClassLoaders.of(primaryLoader)) {
for (VersionSignature signature : SIGNATURES) {
if (!signature.matches(loader, loaderType)) {
continue;
}
if (match == null) {
match = signature.version();
} else if (match != signature.version()) {
// Two different versions match: refuse to guess.
return MinecraftVersion.UNKNOWN;
}
}
}
return match == null ? MinecraftVersion.UNKNOWN : match;
}
private static MinecraftSignature obf(String minecraftClass,
String instanceGetter,
String instanceField,
String... anchors) {
return MinecraftSignature.of(minecraftClass, instanceGetter, instanceField, anchors);
}
private static MinecraftSignature mojang(String minecraftClass,
String instanceGetter,
String instanceField,
String... anchors) {
return MinecraftSignature.of(minecraftClass, instanceGetter, instanceField, anchors);
}
private static MinecraftSignature intermediary(String minecraftClass,
String instanceGetter,
String instanceField,
String... anchors) {
return MinecraftSignature.of(minecraftClass, instanceGetter, instanceField, anchors);
}
private VersionSignatureRegistry() {
}
}
+48 -2
View File
@@ -3,6 +3,9 @@ plugins {
}
def outputDir = layout.projectDirectory.dir('out/tmp')
def distDir = layout.projectDirectory.dir('out')
def resourcesDir = layout.projectDirectory.dir('resources')
def nativesDir = layout.projectDirectory.dir('natives')
tasks.register('cleanOut') {
group = 'build'
@@ -12,14 +15,57 @@ tasks.register('cleanOut') {
}
}
tasks.register('packageAll') {
tasks.register('prepareInjection') {
group = 'build'
description = 'Builds the shaded Loader and OrangeX jars into out/tmp'
description = 'Copies resources and natives into out/tmp (both flattened)'
dependsOn cleanOut
dependsOn ':Loader:shadowJar', ':OrangeX:shadowJar'
doLast {
copy {
from resourcesDir
into outputDir
exclude '**/.gitkeep'
}
copy {
from nativesDir
into outputDir
}
}
}
tasks.register('injectionZip', Zip) {
group = 'build'
description = 'Zips out/tmp into out/injection.zip'
dependsOn prepareInjection
destinationDirectory = distDir
archiveFileName = 'injection.zip'
from outputDir
}
tasks.register('packageAll') {
group = 'build'
description = 'Builds Loader, OrangeX and Injector, then zips out/tmp into out/injection.zip'
dependsOn cleanOut
dependsOn ':Loader:shadowJar', ':OrangeX:shadowJar', ':Injector:jar'
dependsOn injectionZip
}
subprojects {
plugins.withId('java') {
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
if (JavaVersion.current().isJava9Compatible()) {
// Fail fast if a post-Java-8 API is used.
options.release = 8
}
}
}
tasks.matching { it.name == 'shadowJar' }.configureEach {
mustRunAfter rootProject.tasks.named('cleanOut')
}
+157
View File
@@ -0,0 +1,157 @@
# 添加 Minecraft 版本支持
本文说明如何为 OrangeX 增加一个新的 Minecraft 版本。大多数版本只需要两步:注册内部版本 ID、注册结构签名。
## 检测流程
`cn.xiaozhou233.orangex.runtime` 按以下顺序检测版本,前一步成功就返回:
1. **加载器元数据** — `VersionIdSources` 读取 Forge/NeoForge 暴露的版本号。
2. **26.x 版本族** — `ModernVersionDetector` 读取客户端自带的 `version.json`。
3. **结构签名** — `VersionSignatureRegistry` 通过类名、单例 getter/field 和锚点类识别版本。
因此,普通版本只需要修改结构签名;只有新的版本族或新的加载器版本号规则才需要动前两步。
## 1. 添加内部版本 ID
在 `runtime/version/MinecraftVersion.java` 中添加枚举值:
```java
V1_21_10(60),
```
注意:
- 这里的数字是 **OrangeX 内部版本 ID**,不是 Minecraft 网络协议号。
- ID 一旦发布就不要再修改或复用,否则会破坏已有的版本判断和存档/配置兼容性。
- `ForgeVersionParser` 会用这个枚举校验 Forge 版本号,所以新版本 ID 也会自动生效。
## 2. 添加结构签名
在 `runtime/version/VersionSignatureRegistry.java` 的 `SIGNATURES` 列表中注册签名。
### 2.1 Vanilla(混淆类名)
```java
VersionSignature.anyLoader(V1_21_10, obf(
"obfuscatedMinecraftClass", "getterName", "instanceField",
"anchorClass1", "anchorClass2", "anchorClass3")),
```
### 2.2 MCP / 开发环境(真实类名)
```java
VersionSignature.anyLoader(V1_8_9, mojang(
"net.minecraft.client.Minecraft", "getMinecraft", "theMinecraft",
"net.minecraft.client.entity.EntityPlayerSP")),
```
### 2.3 Fabric(intermediary 类名)
```java
VersionSignature.forLoader(FABRIC, V1_21_11, intermediary(
"net/minecraft/class_310", "method_1551", "field_1700",
"net/minecraft/class_638", "net/minecraft/class_746")),
```
### 2.4 NeoForge(Mojang 映射)
```java
VersionSignature.forLoader(NEOFORGE, V1_21_1, mojang(
"net/minecraft/client/Minecraft", "getInstance", "instance",
"net/minecraft/client/multiplayer/ClientLevel",
"net/minecraft/client/player/LocalPlayer")),
```
### 参数说明
| 参数 | 说明 |
|---|---|
| `minecraftClass` | Minecraft 主类。支持 `a.b.C` 和 `a/b/C` 两种写法。 |
| `instanceGetter` | 返回单例的静态方法名;没有就传 `null`。 |
| `instanceField` | 保存单例的静态字段名;没有就传 `null`。 |
| `anchors` | 锚点类。必须和 Minecraft 主类由**同一个 ClassLoader** 定义。 |
### 锚点选择规则
- 选目标版本**独有**的类,优先选该版本新增内容对应的类。
- 锚点必须存在于运行时,不能只存在于开发环境。
- 不要选父 ClassLoader 提供的类,否则 `MinecraftProbe` 会判定不匹配。
- 签名之间不能重叠:**如果两个不同版本同时匹配,检测结果会变成 `UNKNOWN`**,这是有意的防误判策略。
## 3. 新版本族(`version.json`)
如果新版本使用 `id == name` 的版本族命名(例如 26.x),并且没有稳定的混淆类名可探测:
1. 在 `MinecraftVersion` 中添加对应 ID。
2. 在 `utils/MinecraftUtils.java` 的 `readModernVersionId` 中识别新的版本族前缀:
```java
if (isFamily(id, "26.3")) {
return MinecraftVersion.V26_3.getId();
}
```
3. 如有需要,在 `ModernVersionDetector` 中补充该类版本族的类结构检查。
## 4. 新的 Forge 版本号规则
如果 Forge/NeoForge 提供了新的版本信息来源:
1. 在 `VersionIdSources` 中添加一个 `VersionIdSource`,并加入 `SOURCES` 列表。
2. 如果版本号字符串有新的映射规则,修改 `ForgeVersionParser.parse`。
来源方法必须保持 fail-safe:找不到类、字段或方法时返回 `MinecraftVersion.UNKNOWN_ID`,让后续来源继续尝试。
## 5. 验证
构建:
```bash
./gradlew :OrangeX:shadowJar
```
启动带 OrangeX 的客户端,检查日志:
```text
Loader Type: FORGE
Minecraft Version: V1_21_10 (version id 60)
```
也可以直接调用:
```java
RuntimeInfo info = RuntimeDetector.detect();
RuntimeDetector.debug(info);
```
排查建议:
| 现象 | 可能原因 |
|---|---|
| `UNKNOWN (version id 0)` | 签名没匹配上:锚点类名错误、类不存在,或 ClassLoader 不一致。 |
| 检测成旧版本 | 旧版本签名也匹配了目标版本:给新版本签名增加独有锚点,避免重叠。 |
| 检测成新版本但实际是旧版本 | 锚点在旧版本中已经存在:换一个真正新增的锚点。 |
| Fabric/NeoForge 下不匹配 | 缺少对应的 `forLoader(...)` 签名,或 `LoaderType` 判断错误。 |
建议分别验证 Vanilla、Fabric、NeoForge 三种环境,并确认检测结果唯一。
## 6. Checklist
- [ ] `MinecraftVersion` 中的内部 ID 唯一。
- [ ] 至少注册了一条结构签名。
- [ ] 锚点类与 Minecraft 主类由同一个 ClassLoader 定义。
- [ ] 目标版本与相邻版本的签名不会同时匹配。
- [ ] Fabric/NeoForge 使用了正确的 `forLoader(...)`。
- [ ] 新版本族已更新 `MinecraftUtils` / `ModernVersionDetector`。
- [ ] 已在真实客户端中验证 `Loader Type` 和 `Minecraft Version` 输出。
## 附:添加新的 Mod 加载器
版本检测之外,加载器识别也使用注册表:
1. 在 `loader/LoaderType.java` 中添加枚举值。
2. 在 `loader/LoaderDetector.java` 的 `PROBES` 中注册 `LoaderProbe`:
- 如果只需检查 marker 类,使用 `ClassPresenceLoaderProbe`。
- 如果需要结构判断,实现 `LoaderProbe`。
3. 如果新加载器需要专属版本签名,在 `VersionSignatureRegistry` 中使用 `VersionSignature.forLoader(...)`。
+3
View File
@@ -0,0 +1,3 @@
# Placeholder so the resources directory is tracked by git.
# Files put here are flattened into the injection zip (e.g. config.toml ends up
# next to the jars in ~/.orangex).
+19
View File
@@ -0,0 +1,19 @@
# See config.md for more information https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/config.md
[JuiceAgent]
Version = 2
JuiceAgentNativeLibraryPath = ""
[JarLoader]
# Mode: BuiltIn, CustomJar
# BuiltIn: Use the built-in jar loader (recommended, support JuiceAgent-API ( https://github.com/xiaozhou233/JuiceAgent#juiceagent-api ))
# CustomJar: Load the Jar directly, without using JuiceAgent-API
# For more information, please refer to the documentation: https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/advanced.md#load-custom-api--directly-load-jar
Enabled = true
Mode = "BuiltIn"
# InjectionDir only works when Mode is BuiltIn
InjectionDir = "./injection"
JarPath = "./Loader.jar"
EntryClass = "cn.xiaozhou233.orangex.loader.Loader"
EntryMethod = "entry"
+2 -1
View File
@@ -1,4 +1,5 @@
rootProject.name = 'OrangeX-Client'
include 'Loader'
include 'OrangeX'
include 'Minecraft1.8.8'
include 'Injector'
include 'Minecraft1.8.8'