Compare commits

...
10 Commits
Author SHA1 Message Date
xiaozhou233 4effbc36f5 Docs: Add development guides for modules and wrappers
- Add docs/README.md with the documentation index, reading order and
  layer responsibilities
- Add adding-modules.md covering module registration, lifecycle, events,
  Value settings, config persistence and the NoJumpDelay example
- Add reflection-and-mappings.md covering MCP/SRG names, MappingResolver,
  ReflectionSupport and the common reflection pitfalls
- Add adding-wrapper-capabilities.md walking through a new Player wrapper
  from API to module usage, with NoJumpDelay as the worked example
- Update adding-wrapper-versions.md to match the real createPlayer
  signature, the current directory layout and the provider checklist
- Link the development docs from README.md
2026-11-10 22:00:15 +08:00
xiaozhou233 9fa0176bd2 Feat: Add NoJumpDelay module
- Add a cross-version Player wrapper that clears the client jump cooldown:
  jumpTicks on 1.8.9 and noJumpDelay on 26.2
- Resolve the player field and cooldown field through MappingResolver so
  vanilla, Forge and MCP runtimes all work
- Dispatch the new capability through WrapperProvider, WrapperRegistry and
  MinecraftFactory, and create it during OrangeX startup
- Clear the cooldown in EventTickPre so the next jump can start on the
  first landing tick while the jump key is held
- Register the module and add a setInt helper to ReflectionSupport
2026-11-10 21:54:17 +08:00
xiaozhou233 8f314e1f5c Feat: Persist module settings to named config files
- Add ConfigManager, Config and ConfigSerializer with JSON storage,
  validated names, sorted listings and atomic temp-file writes
- Serialize module enabled state and typed values; ignore unknown or
  invalid entries so a malformed file cannot break a module
- Track dirty state from value and module changes, then save on GUI
  close and JVM shutdown instead of only when the GUI is closed
- Remember the last loaded config and refuse to delete the active one
- Snapshot in-memory state before loading and roll back on failure;
  back up unreadable files so the client still has a writable config
- Key modules by class name while still reading legacy display-name
  configs, so renaming a module keeps its stored settings
- Initialise the config manager during OrangeX startup
2026-11-10 20:53:48 +08:00
xiaozhou233 30fde895b6 Docs: README.md 2026-11-10 15:00:21 +08:00
xiaozhou233 ed7fa13e7f Fix: Interpolate world positions with the frame's partial tick
- Pass the 1.8.9 HUD method's partial tick through the render hook into
  EventRender2D instead of reading Timer.renderPartialTicks reflectively
- Let WorldView.snapshot() take that value so ESP projection matches the
  rendered world and no longer advances in 20 Hz steps
- Keep the reflected timer read as a fallback and warn once when it cannot
  be resolved instead of silently interpolating with 0
2026-11-10 13:47:55 +08:00
xiaozhou233 d8a46a1b70 Feat: Show module settings as a page in the ClickGUI content area
- Replace the floating SettingsWindow with an inline settings page
- Return to the module list via the back button or a category click
- Scroll the module list and the settings page with the mouse wheel
- Share module row geometry through ContentList and add a scrollbar
  helper
- Bail out of scroll input when the content fits
2026-11-10 13:26:19 +08:00
xiaozhou233 09de736269 Feat: Add mouse wheel scrolling to client input
- Queue wheel notches in ClientInput for the next frame
- Forward wheel deltas from the 1.8.9 screen and 26.2 input screen
- Hook GuiScreen#handleMouseInput after vanilla, guarded so a
  missing method never disables the other input injections
- Shrink HUD module font size to 10
2026-11-10 13:12:22 +08:00
xiaozhou233 d9075831e3 Feat: Add entity kind and invisibility filters to ESP
- WorldView now captures every entity instead of players only and no longer applies gameplay filtering.

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

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

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

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

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

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

- Fix 26.2 glyph snapping: shared baseline, thin-stroke visibility and even horizontal spacing
2026-11-08 15:24:42 +08:00
61 changed files with 5528 additions and 44 deletions

No files matched your search

@@ -1,5 +1,6 @@
package cn.xiaozhou233.orangex;
import cn.xiaozhou233.orangex.config.ConfigManager;
import cn.xiaozhou233.orangex.event.impl.EventKey;
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
import cn.xiaozhou233.orangex.event.impl.EventTickPre;
@@ -13,11 +14,17 @@ import cn.xiaozhou233.orangex.runtime.RuntimeDetector;
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
import cn.xiaozhou233.orangex.wrapper.MinecraftFactory;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.Player;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import lombok.Getter;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.io.File;
public class OrangeX {
public static String OrangeXPath = new File(System.getProperty("user.home")+"/.orangex").getAbsolutePath();
@Getter
private static final OrangeX instance = new OrangeX();
@Getter
@@ -33,8 +40,15 @@ public class OrangeX {
private Render2DManager render2DManager;
@Getter
private ModuleManager moduleManager = new ModuleManager();
@Getter
private ConfigManager configManager;
@Getter
private Minecraft minecraft;
@Getter
private WorldView worldView;
@Getter
private Player player;
public OrangeX() {
System.out.println("OrangeX <init> start!");
@@ -52,6 +66,27 @@ public class OrangeX {
this.minecraft = minecraft;
System.out.println(minecraft.getMinecraft());
try {
this.worldView = MinecraftFactory.createWorld(
runtimeInfo, MappingManager.getResolver(), minecraft);
} catch (Throwable throwable) {
// The client must keep running even when a version cannot expose
// world data; world-dependent modules simply stay inactive.
System.err.println("[OrangeX] World wrapper unavailable: "
+ throwable.getMessage());
throwable.printStackTrace();
}
try {
this.player = MinecraftFactory.createPlayer(
runtimeInfo, MappingManager.getResolver(), minecraft);
} catch (Throwable throwable) {
// Player-dependent modules stay inactive when this fails.
System.err.println("[OrangeX] Player wrapper unavailable: "
+ throwable.getMessage());
throwable.printStackTrace();
}
render2DManager = new Render2DManager(
runtimeInfo, MappingManager.getResolver(), minecraft.getMinecraft());
System.out.println("[OrangeX] Font backend: " + render2DManager.getBackendName());
@@ -62,6 +97,9 @@ public class OrangeX {
moduleManager.init();
configManager = new ConfigManager(new File(OrangeXPath, "configs/"), moduleManager);
configManager.init();
HookManager.getINSTANCE().applyAll();
}
@@ -0,0 +1,37 @@
package cn.xiaozhou233.orangex.config;
import lombok.Getter;
import java.io.File;
public class Config {
private final ConfigManager manager;
@Getter
private final String name;
@Getter
private final File file;
public Config(ConfigManager manager, String name, File file) {
this.manager = manager;
this.name = name;
this.file = file;
}
public boolean load() {
return manager.load(name);
}
public boolean save() {
return manager.save(name);
}
public boolean exists() {
return file.isFile();
}
@Override
public String toString() {
return name;
}
}
@@ -0,0 +1,462 @@
package cn.xiaozhou233.orangex.config;
import cn.xiaozhou233.orangex.config.impl.JsonConfigSerializer;
import cn.xiaozhou233.orangex.modules.ModuleManager;
import cn.xiaozhou233.orangex.value.Value;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
public class ConfigManager {
private static final Pattern VALID_NAME =
Pattern.compile("[a-zA-Z0-9_-]+");
private static final String EXTENSION = ".json";
private static final String TEMP_SUFFIX = ".json.tmp";
private static final String BACKUP_SUFFIX = ".json.bak";
private static final String CURRENT_FILE = "current.txt";
private static final String DEFAULT_CONFIG = "default";
private final File directory;
private final ModuleManager moduleManager;
private final ConfigSerializer serializer;
private final Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
private Config currentConfig;
private volatile boolean dirty;
private boolean initialised;
public ConfigManager(File directory, ModuleManager moduleManager) {
this(directory, moduleManager, new JsonConfigSerializer());
}
public ConfigManager(
File directory,
ModuleManager moduleManager,
ConfigSerializer serializer
) {
this.directory = directory;
this.moduleManager = moduleManager;
this.serializer = serializer;
}
public synchronized void init() {
ensureDirectory();
if (!getFile(DEFAULT_CONFIG).isFile()) {
create(DEFAULT_CONFIG);
}
// Track any later value change so the client can persist settings even
// when the user never opens the config screen.
Value.setGlobalChangeHook(this::markDirty);
String name = readCurrentName();
if (name == null || getConfig(name) == null) {
name = DEFAULT_CONFIG;
}
if (!load(name)) {
// Never leave an unreadable file in place: keep a backup and start
// over from the current (default) state.
backupUnreadable(name);
create(name);
if (!load(name)) {
System.err.println(
"[OrangeX] Could not restore config '" + name + "'");
}
}
if (!initialised) {
initialised = true;
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
saveIfDirty();
} catch (Throwable throwable) {
System.err.println(
"[OrangeX] Failed to save config on shutdown: "
+ throwable.getMessage());
}
}, "OrangeX Config Save"));
}
}
/**
* Creates a config file from the current in-memory module state, so a new
* preset starts out identical to what the user currently sees.
*/
public synchronized Config create(String name) {
validateName(name);
File file = getFile(name);
if (file.exists()) {
throw new IllegalArgumentException(
"Config already exists: " + name);
}
Config config = new Config(this, name, file);
if (!save(name)) {
throw new IllegalStateException(
"Failed to create config: " + name);
}
return config;
}
public synchronized boolean load(String name) {
Config config = getConfig(name);
if (config == null) {
return false;
}
// Do not silently drop unsaved changes when switching presets.
if (!isCurrent(name) && dirty && currentConfig != null && !save()) {
System.err.println(
"[OrangeX] Refusing to switch config: changes to '"
+ currentConfig.getName() + "' could not be saved");
return false;
}
File file = config.getFile();
boolean wasDirty = dirty;
// Snapshot the live state so a malformed file cannot leave modules
// half-restored.
JsonObject snapshot = serializer.serialize(moduleManager);
try (FileReader reader = new FileReader(file)) {
JsonObject json = JsonParser.parseReader(reader).getAsJsonObject();
int version = json.has("version")
? json.get("version").getAsInt()
: 1;
if (version != ConfigSerializer.CURRENT_VERSION) {
throw new IllegalStateException(
"Unsupported config version: " + version);
}
serializer.deserialize(moduleManager, json);
currentConfig = config;
dirty = false;
writeCurrentName(name);
return true;
} catch (Exception e) {
System.err.println(
"[OrangeX] Failed to load config '" + name + "': " + e.getMessage());
try {
serializer.deserialize(moduleManager, snapshot);
} catch (Exception rollback) {
System.err.println(
"[OrangeX] Failed to restore previous state: "
+ rollback.getMessage());
}
dirty = wasDirty;
return false;
}
}
public synchronized boolean save() {
if (currentConfig == null) {
return false;
}
return save(currentConfig.getName());
}
/**
* Persists the current module state under {@code name}.
*
* @return {@code true} when the file was written.
*/
public synchronized boolean save(String name) {
validateName(name);
File file = getFile(name);
File tempFile = new File(directory, name + TEMP_SUFFIX);
JsonObject json = serializer.serialize(moduleManager);
try {
ensureDirectory();
try (FileWriter writer = new FileWriter(tempFile)) {
gson.toJson(json, writer);
}
try {
Files.move(
tempFile.toPath(),
file.toPath(),
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE
);
} catch (IOException e) {
Files.move(
tempFile.toPath(),
file.toPath(),
StandardCopyOption.REPLACE_EXISTING
);
}
if (currentConfig != null
&& currentConfig.getName().equalsIgnoreCase(name)) {
dirty = false;
}
return true;
} catch (IOException e) {
tempFile.delete();
System.err.println(
"[OrangeX] Failed to save config '" + name + "': "
+ e.getMessage());
return false;
}
}
/**
* Saves only when values or module states changed since the last load or
* save. Used by periodic/GUI/shutdown save hooks.
*/
public synchronized boolean saveIfDirty() {
if (!dirty || currentConfig == null) {
return false;
}
return save();
}
public synchronized boolean delete(String name) {
Config config = getConfig(name);
if (config == null) {
return false;
}
// Deleting the active config would leave the client with nowhere to
// save to; require the caller to load another config first.
if (isCurrent(name)) {
System.err.println(
"[OrangeX] Refusing to delete the active config: " + name);
return false;
}
boolean deleted = config.getFile().delete();
if (deleted && name.equalsIgnoreCase(readCurrentName())) {
clearCurrentName();
}
return deleted;
}
public synchronized boolean rename(String oldName, String newName) {
validateName(oldName);
validateName(newName);
if (oldName.equalsIgnoreCase(newName)) {
// A pure case change cannot be represented reliably on
// case-insensitive file systems.
return false;
}
Config oldConfig = getConfig(oldName);
if (oldConfig == null || getFile(newName).exists()) {
return false;
}
File newFile = getFile(newName);
try {
Files.move(
oldConfig.getFile().toPath(),
newFile.toPath()
);
if (isCurrent(oldName)) {
currentConfig = new Config(this, newName, newFile);
writeCurrentName(newName);
}
return true;
} catch (IOException e) {
System.err.println(
"[OrangeX] Failed to rename config: " + e.getMessage());
return false;
}
}
public Config getConfig(String name) {
if (name == null) {
return null;
}
File file = getFile(name);
if (!file.isFile()) {
return null;
}
return new Config(this, name, file);
}
public Config getCurrentConfig() {
return currentConfig;
}
public boolean isDirty() {
return dirty;
}
public void markDirty() {
dirty = true;
}
public synchronized List<Config> getConfigs() {
File[] files = directory.listFiles(
(dir, name) -> name.toLowerCase(Locale.ROOT).endsWith(EXTENSION)
);
if (files == null) {
return Collections.emptyList();
}
List<Config> configs = new ArrayList<>();
for (File file : files) {
String name = file.getName();
name = name.substring(0, name.length() - EXTENSION.length());
if (VALID_NAME.matcher(name).matches()) {
configs.add(new Config(this, name, file));
}
}
configs.sort(Comparator.comparing(
Config::getName, String.CASE_INSENSITIVE_ORDER));
return configs;
}
public File getDirectory() {
return directory;
}
private boolean isCurrent(String name) {
return currentConfig != null
&& currentConfig.getName().equalsIgnoreCase(name);
}
private File getFile(String name) {
validateName(name);
return new File(directory, name + EXTENSION);
}
private void validateName(String name) {
if (name == null || !VALID_NAME.matcher(name).matches()) {
throw new IllegalArgumentException(
"Invalid config name: " + name);
}
}
private void ensureDirectory() {
if (!directory.exists() && !directory.mkdirs()) {
throw new IllegalStateException(
"Failed to create config directory: " + directory);
}
}
/**
* @return the last config that was successfully loaded, or {@code null}.
*/
private String readCurrentName() {
File file = new File(directory, CURRENT_FILE);
if (!file.isFile()) {
return null;
}
try {
String name = new String(
Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8)
.trim();
return VALID_NAME.matcher(name).matches() ? name : null;
} catch (IOException e) {
return null;
}
}
private void writeCurrentName(String name) {
try {
Files.write(
new File(directory, CURRENT_FILE).toPath(),
name.getBytes(StandardCharsets.UTF_8)
);
} catch (IOException e) {
System.err.println(
"[OrangeX] Failed to remember current config: "
+ e.getMessage());
}
}
private void clearCurrentName() {
File file = new File(directory, CURRENT_FILE);
if (file.isFile() && !file.delete()) {
System.err.println(
"[OrangeX] Failed to clear current config marker");
}
}
private void backupUnreadable(String name) {
File file = getFile(name);
if (!file.isFile()) {
return;
}
File backup = new File(directory, name + BACKUP_SUFFIX);
try {
Files.move(
file.toPath(),
backup.toPath(),
StandardCopyOption.REPLACE_EXISTING
);
System.err.println(
"[OrangeX] Backed up unreadable config to " + backup);
} catch (IOException e) {
System.err.println(
"[OrangeX] Failed to back up config '" + name + "': "
+ e.getMessage());
}
}
}
@@ -0,0 +1,14 @@
package cn.xiaozhou233.orangex.config;
import cn.xiaozhou233.orangex.modules.ModuleManager;
import com.google.gson.JsonObject;
public interface ConfigSerializer {
/** On-disk format version shared by the manager and the serializer. */
int CURRENT_VERSION = 1;
JsonObject serialize(ModuleManager moduleManager);
void deserialize(ModuleManager moduleManager, JsonObject json);
}
@@ -0,0 +1,68 @@
package cn.xiaozhou233.orangex.config.impl;
import cn.xiaozhou233.orangex.config.ConfigSerializer;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.modules.ModuleManager;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class JsonConfigSerializer implements ConfigSerializer {
@Override
public JsonObject serialize(ModuleManager moduleManager) {
JsonObject root = new JsonObject();
JsonObject modules = new JsonObject();
root.addProperty("version", CURRENT_VERSION);
for (Module module : moduleManager.getAllModules()) {
JsonObject moduleJson = new JsonObject();
moduleJson.addProperty("enabled", module.isEnabled());
moduleJson.add("values", module.valuesToJson());
modules.add(module.getConfigKey(), moduleJson);
}
root.add("modules", modules);
return root;
}
@Override
public void deserialize(ModuleManager moduleManager, JsonObject json) {
if (json == null || !json.has("modules")
|| !json.get("modules").isJsonObject()) {
return;
}
JsonObject modules = json.getAsJsonObject("modules");
for (Module module : moduleManager.getAllModules()) {
JsonElement element = modules.get(module.getConfigKey());
// Older configs keyed modules by display name.
if (element == null) {
element = modules.get(module.getName());
}
if (element == null || !element.isJsonObject()) {
continue;
}
JsonObject moduleJson = element.getAsJsonObject();
// Restore values before enabling the module.
if (moduleJson.has("values")
&& moduleJson.get("values").isJsonObject()) {
module.valuesFromJson(moduleJson.getAsJsonObject("values"));
}
if (moduleJson.has("enabled")
&& moduleJson.get("enabled").isJsonPrimitive()
&& moduleJson.get("enabled").getAsJsonPrimitive().isBoolean()) {
module.setEnabled(moduleJson.get("enabled").getAsBoolean());
}
}
}
}
@@ -17,10 +17,19 @@ public final class Render2DEvents {
* screen too, so the hook must pass this through.
*/
public static void fire(Object platformContext, boolean inWorld) {
fire(platformContext, inWorld, Float.NaN);
}
/**
* @param partialTicks the partial tick the game rendered this frame with.
* {@link Float#NaN} when the hook cannot supply it.
*/
public static void fire(Object platformContext, boolean inWorld,
float partialTicks) {
try {
Render2DManager manager = OrangeX.getInstance().getRender2DManager();
if (manager != null) {
manager.fire(platformContext, inWorld);
manager.fire(platformContext, inWorld, partialTicks);
}
} catch (Throwable throwable) {
if (!failureLogged) {
@@ -15,10 +15,16 @@ public class EventRender2D {
private final Render2D render2D;
private final boolean inWorld;
private final float partialTicks;
public EventRender2D(Render2D render2D, boolean inWorld) {
this(render2D, inWorld, Float.NaN);
}
public EventRender2D(Render2D render2D, boolean inWorld, float partialTicks) {
this.render2D = render2D;
this.inWorld = inWorld;
this.partialTicks = partialTicks;
}
public Render2D getRender2D() {
@@ -31,4 +37,16 @@ public class EventRender2D {
public boolean isInWorld() {
return inWorld;
}
/**
* The partial tick the game used for this frame's world render, i.e. the
* interpolation factor between the previous and the current tick.
*
* <p>Feature code must use this value instead of reading a timer of its own
* so projected world positions line up with the rendered world. It is
* {@link Float#NaN} when the hook could not supply one.</p>
*/
public float getPartialTicks() {
return partialTicks;
}
}
@@ -67,6 +67,16 @@ public final class GuiInputHook extends ClassHook {
// The empty screen is an overlay: it must not pause singleplayer.
injectAfter(ctClass, "doesGuiPauseGame", "()Z",
"if (orangexbridge.Hooks.isOurScreen($0)) { $_ = false; }");
// Wheel scrolling for the ClickGUI. Injecting after vanilla keeps its
// mouse-button dispatch intact; the wheel event is still readable.
try {
injectAfter(ctClass, "handleMouseInput", "()V",
"orangexbridge.Legacy.forwardScroll($0);");
} catch (Throwable ignored) {
// Scrolling is optional: never let it disable the input hooks
// above on a runtime where this method cannot be resolved.
}
}
private void injectBefore(CtClass ctClass, String name,
@@ -101,7 +101,8 @@ public final class Render2DHook extends ClassHook {
throw new IllegalStateException(
"No (F)V HUD method found in " + ctClass.getName());
}
method.insertAfter("orangexbridge.Hooks.render2d(null, true);");
method.insertAfter(
"orangexbridge.Hooks.render2d(null, true, $1);");
return;
} else {
MappingMethod target = resolver.mapMethod(
@@ -112,7 +113,10 @@ public final class Render2DHook extends ClassHook {
methodDescriptor = target.getTargetDescriptor();
}
CtMethod method = ctClass.getMethod(methodName, methodDescriptor);
method.insertAfter("orangexbridge.Hooks.render2d(null, true);");
// $1 is the frame's partial tick: pass it through so features
// interpolate world positions exactly like the world render.
method.insertAfter(
"orangexbridge.Hooks.render2d(null, true, $1);");
break;
}
case V26_2: {
@@ -21,6 +21,7 @@ public final class ClientInput {
private static volatile boolean leftDown;
private static volatile boolean rightDown;
private static volatile boolean middleDown;
private static double scrollAmount;
private static boolean started;
private static boolean pendingOpen;
@@ -111,6 +112,29 @@ public final class ClientInput {
}
}
/**
* Queues a wheel notch for the next frame. Positive is one notch up.
*/
public static synchronized void onMouseScroll(double amount) {
if (amount != 0.0) {
scrollAmount += amount;
}
}
public static void onMouseScroll(double x, double y, double amount) {
onMouseMove(x, y);
onMouseScroll(amount);
}
/**
* @return the wheel amount accumulated since the previous call.
*/
public static synchronized double consumeScroll() {
double amount = scrollAmount;
scrollAmount = 0.0;
return amount;
}
public static void reset() {
if (open) {
System.out.println("[OrangeX] Input screen closed");
@@ -119,6 +143,7 @@ public final class ClientInput {
leftDown = false;
rightDown = false;
middleDown = false;
scrollAmount = 0.0;
}
public static boolean isOpen() {
@@ -1,5 +1,6 @@
package cn.xiaozhou233.orangex.input.internal.v1_8_9;
import cn.xiaozhou233.orangex.event.facade.InputEvents;
import cn.xiaozhou233.orangex.hook.ClassPoolUtils;
import cn.xiaozhou233.orangex.hook.HookManager;
import cn.xiaozhou233.orangex.hook.JuiceAgentBridge;
@@ -272,13 +273,29 @@ public final class V1_8_9Input implements VersionInput {
}
/**
* Used by injected {@code GuiScreen}/{@code KeyBinding} code to ignore
* LWJGL auto-repeat events.
* Used by injected {@code GuiScreen} code to ignore LWJGL auto-repeat
* events.
*/
public static boolean isRepeatEvent() {
return Keyboard.isRepeatEvent();
}
/**
* Called after {@code GuiScreen#handleMouseInput} ran. The wheel event is
* still readable at this point and must not consume the vanilla mouse
* button dispatch.
*/
public static void forwardScroll(Object screen) {
if (!InputEvents.isOurInputScreen(screen)) {
return;
}
int wheel = Mouse.getEventDWheel();
if (wheel != 0) {
ClientInput.onMouseScroll(wheel > 0 ? 1.0 : -1.0);
}
}
@Override
public double getGuiMouseX() {
Object screen = shellScreen;
@@ -63,7 +63,7 @@ public final class V26_2InputScreen extends Screen {
@Override
public boolean mouseScrolled(double x, double y,
double scrollX, double scrollY) {
ClientInput.onMouseMove(x, y);
ClientInput.onMouseScroll(x, y, scrollY);
return true;
}
}
@@ -1,6 +1,7 @@
package cn.xiaozhou233.orangex.modules;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.config.ConfigManager;
import cn.xiaozhou233.orangex.input.KeyCodes;
import cn.xiaozhou233.orangex.value.BooleanValue;
import cn.xiaozhou233.orangex.value.KeybindValue;
@@ -64,6 +65,14 @@ public abstract class Module {
return addValue(new ModeValue(name, defaultMode, modes));
}
/**
* Stable key used for persistence. Keeping the class name instead of the
* display name means renamed modules keep their stored settings.
*/
public String getConfigKey() {
return getClass().getName();
}
public Value<?> getValue(String name) {
return valueMap.get(name);
}
@@ -126,6 +135,7 @@ public abstract class Module {
if (this.enabled == setEnabled) return;
this.enabled = setEnabled;
markConfigDirty();
if (this.enabled) {
if (OrangeX.getInstance().getEventBus().isRegistered(this))
@@ -144,4 +154,11 @@ public abstract class Module {
setEnabled(!this.enabled);
}
private void markConfigDirty() {
ConfigManager configManager = OrangeX.getInstance().getConfigManager();
if (configManager != null) {
configManager.markDirty();
}
}
}
@@ -2,7 +2,9 @@ package cn.xiaozhou233.orangex.modules;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.event.impl.EventKey;
import cn.xiaozhou233.orangex.modules.impl.movement.NoJumpDelay;
import cn.xiaozhou233.orangex.modules.impl.render.ClickGUI;
import cn.xiaozhou233.orangex.modules.impl.render.ESP;
import cn.xiaozhou233.orangex.modules.impl.render.HUD;
import org.greenrobot.eventbus.Subscribe;
@@ -26,6 +28,8 @@ public class ModuleManager {
public void registerAll() {
register(new HUD());
register(new ClickGUI());
register(new ESP());
register(new NoJumpDelay());
}
public void register(Module module) {
@@ -0,0 +1,43 @@
package cn.xiaozhou233.orangex.modules.impl.movement;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.event.impl.EventTickPre;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.modules.ModuleCategory;
import cn.xiaozhou233.orangex.wrapper.api.Player;
import org.greenrobot.eventbus.Subscribe;
/**
* Removes the client-side jump cooldown.
*
* <p>Vanilla keeps a short timer after every jump before the next one can
* start. Clearing it before the player tick lets holding the jump key trigger
* a new jump as soon as the player touches the ground again.</p>
*/
public class NoJumpDelay extends Module {
private boolean warned;
public NoJumpDelay() {
super("NoJumpDelay", ModuleCategory.MOVEMENT);
}
@Subscribe
public void onTickPre(EventTickPre event) {
Player player = OrangeX.getInstance().getPlayer();
if (player == null) {
return;
}
try {
player.clearJumpDelay();
} catch (Throwable throwable) {
// Do not retry a broken reflection lookup on every single tick.
if (!warned) {
warned = true;
System.err.println("[NoJumpDelay] Failed to clear jump delay: "
+ throwable.getMessage());
}
}
}
}
@@ -1,11 +1,13 @@
package cn.xiaozhou233.orangex.modules.impl.render;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
import cn.xiaozhou233.orangex.event.impl.EventTickPre;
import cn.xiaozhou233.orangex.input.ClientInput;
import cn.xiaozhou233.orangex.input.KeyCodes;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.modules.ModuleCategory;
import cn.xiaozhou233.orangex.ui.clickgui.ClickGuiRender;
import org.greenrobot.eventbus.Subscribe;
/**
@@ -33,6 +35,7 @@ public class ClickGUI extends Module {
return;
}
justEnabled = true;
ClickGuiRender.reset();
// Defer opening to EventTickPost: opening inside the keyboard callback
// would let the same RSHIFT event reach the new screen and close it.
ClientInput.requestOpen();
@@ -41,7 +44,11 @@ public class ClickGUI extends Module {
@Override
protected void onDisable() {
justEnabled = false;
ClickGuiRender.reset();
ClientInput.requestClose();
if (OrangeX.getInstance().getConfigManager() != null) {
OrangeX.getInstance().getConfigManager().saveIfDirty();
}
super.onDisable();
}
@@ -65,8 +72,6 @@ public class ClickGUI extends Module {
return;
}
// TODO: draw the ClickGUI here.
// Cursor: ClientInput.getMouseX() / getMouseY()
// Buttons: ClientInput.isLeftDown() / isRightDown() / isMiddleDown()
ClickGuiRender.render(event);
}
}
@@ -0,0 +1,288 @@
package cn.xiaozhou233.orangex.modules.impl.render;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.modules.ModuleCategory;
import cn.xiaozhou233.orangex.render.api.FontRenderer;
import cn.xiaozhou233.orangex.render.api.Render2D;
import cn.xiaozhou233.orangex.value.BooleanValue;
import cn.xiaozhou233.orangex.value.ModeValue;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import cn.xiaozhou233.orangex.wrapper.common.EntityTarget;
import cn.xiaozhou233.orangex.wrapper.common.ScreenPoint;
import cn.xiaozhou233.orangex.wrapper.common.Vec3;
import cn.xiaozhou233.orangex.wrapper.common.WorldSnapshot;
import org.greenrobot.eventbus.Subscribe;
import java.awt.Color;
import java.util.List;
import java.util.Locale;
/**
* 2D ESP: projects entities to the screen and draws a box, name, distance and
* health bar around each one.
*
* <p>All drawing happens in GUI pixel space through {@link Render2D}, so it
* works with both the 1.8.9 and the modern font backends. World data comes
* from the cross-version {@link WorldView} wrapper, never from game classes
* directly. The wrapper reports every entity; the target-type filters below
* decide which kinds are drawn.</p>
*/
public class ESP extends Module {
private static final float NAME_FONT_SIZE = 9.0F;
private static final double NAME_GAP = 2.0D;
private static final double BOX_PADDING = 0.5D;
private static final double CORNER_LENGTH = 4.0D;
private static final double HEALTH_BAR_WIDTH = 2.0D;
private static final double HEALTH_BAR_GAP = 2.0D;
private static final double MIN_BOX_HEIGHT = 2.0D;
private static final double MIN_BOX_WIDTH = 2.0D;
private static final int ORANGE = 0xFFFF8A00;
private static final int FILL_ALPHA = 32;
private static final int HEALTH_BACKGROUND = 0x80000000;
private final BooleanValue players = addBoolean("Players", true);
private final BooleanValue localPlayer = addBoolean("Local Player", false);
private final BooleanValue monsters = addBoolean("Monsters", false);
private final BooleanValue animals = addBoolean("Animals", false);
private final BooleanValue villagers = addBoolean("Villagers", false);
private final BooleanValue others = addBoolean("Others", false);
private final BooleanValue invisible = addBoolean("Invisible", false);
private final BooleanValue box = addBoolean("Box", true);
private final BooleanValue fill = addBoolean("Fill", true);
private final BooleanValue health = addBoolean("Health", true);
private final BooleanValue name = addBoolean("Name", true);
private final BooleanValue distance = addBoolean("Distance", true);
private final ModeValue style = addMode("Style", "Box", "Box", "Corners");
private final ModeValue colorMode = addMode("Color", "Orange", "Orange", "Health", "Rainbow");
public ESP() {
super("ESP", ModuleCategory.RENDER);
}
@Subscribe
public void onRender2D(EventRender2D event) {
if (!event.isInWorld()) {
return;
}
WorldView world = OrangeX.getInstance().getWorldView();
if (world == null) {
return;
}
WorldSnapshot snapshot;
try {
snapshot = world.snapshot(event.getPartialTicks());
} catch (Throwable throwable) {
// A broken wrapper must not kill the whole HUD frame.
System.err.println("[ESP] Failed to read world snapshot: "
+ throwable.getMessage());
return;
}
if (snapshot == null) {
return;
}
Render2D graphics = event.getRender2D();
int screenWidth = graphics.getWidth();
int screenHeight = graphics.getHeight();
FontRenderer font = graphics.getFont(NAME_FONT_SIZE);
double fontHeight = font.getStringHeight();
List<EntityTarget> targets = snapshot.getTargets();
for (int index = 0; index < targets.size(); index++) {
EntityTarget target = targets.get(index);
if (!isTargetEnabled(target)) {
continue;
}
renderTarget(graphics, font, fontHeight, snapshot, target, index,
screenWidth, screenHeight);
}
}
/**
* Target filters live here rather than in the world wrapper so the same
* snapshot can feed future features (tracers, nametags, ...) without each
* of them re-implementing the rules.
*/
private boolean isTargetEnabled(EntityTarget target) {
// Invisible entities are their own category: they are drawn only when
// "Invisible" is enabled, no matter which kind filters are on. Turn
// every kind filter off and keep only this one on for an invisible-only
// ESP.
if (target.isLocalPlayer()) {
return localPlayer.isEnabled()
&& (!target.isInvisible() || invisible.isEnabled());
}
if (target.isInvisible()) {
return invisible.isEnabled();
}
switch (target.getKind()) {
case PLAYER:
return players.isEnabled();
case MONSTER:
return monsters.isEnabled();
case ANIMAL:
return animals.isEnabled();
case VILLAGER:
return villagers.isEnabled();
case OTHER:
default:
return others.isEnabled();
}
}
private void renderTarget(Render2D graphics,
FontRenderer font,
double fontHeight,
WorldSnapshot snapshot,
EntityTarget target,
int index,
int screenWidth,
int screenHeight) {
if (target.getHeight() <= 0.0D) {
return;
}
Vec3 feet = target.getPosition();
Vec3 head = new Vec3(feet.getX(), feet.getY() + target.getHeight(), feet.getZ());
ScreenPoint feetPoint = snapshot.project(feet, screenWidth, screenHeight);
ScreenPoint headPoint = snapshot.project(head, screenWidth, screenHeight);
if (!feetPoint.isVisible() || !headPoint.isVisible()) {
return;
}
double boxHeight = feetPoint.getY() - headPoint.getY();
if (boxHeight < MIN_BOX_HEIGHT) {
return;
}
double boxWidth = Math.max(MIN_BOX_WIDTH,
boxHeight * (target.getWidth() / target.getHeight()));
double centerX = (feetPoint.getX() + headPoint.getX()) * 0.5D;
double left = centerX - boxWidth * 0.5D;
double top = headPoint.getY();
int color = color(target, index);
if (fill.isEnabled()) {
graphics.fillRect(left, top, boxWidth, boxHeight,
(color & 0x00FFFFFF) | (FILL_ALPHA << 24));
}
if (box.isEnabled()) {
if (style.is("Corners")) {
drawCorners(graphics, left, top, boxWidth, boxHeight, color);
} else {
graphics.drawRect(left - BOX_PADDING, top - BOX_PADDING,
boxWidth + BOX_PADDING * 2.0D,
boxHeight + BOX_PADDING * 2.0D,
1.0D, color);
}
}
if (health.isEnabled()) {
drawHealthBar(graphics, target, left - HEALTH_BAR_GAP, top, boxHeight);
}
String label = label(target);
if (label == null) {
return;
}
double textWidth = font.getStringWidth(label);
double textY = top - fontHeight - NAME_GAP;
font.drawStringWithShadow(label, centerX - textWidth * 0.5D, textY, color);
}
private void drawCorners(Render2D graphics, double left, double top,
double width, double height, int color) {
double length = Math.min(CORNER_LENGTH, Math.min(width, height) * 0.5D);
if (length <= 0.0D) {
return;
}
double right = left + width;
double bottom = top + height;
// Top-left
graphics.fillRect(left, top, length, 1.0D, color);
graphics.fillRect(left, top, 1.0D, length, color);
// Top-right
graphics.fillRect(right - length, top, length, 1.0D, color);
graphics.fillRect(right - 1.0D, top, 1.0D, length, color);
// Bottom-left
graphics.fillRect(left, bottom - 1.0D, length, 1.0D, color);
graphics.fillRect(left, bottom - length, 1.0D, length, color);
// Bottom-right
graphics.fillRect(right - length, bottom - 1.0D, length, 1.0D, color);
graphics.fillRect(right - 1.0D, bottom - length, 1.0D, length, color);
}
private void drawHealthBar(Render2D graphics, EntityTarget target,
double x, double top, double height) {
if (target.getMaxHealth() <= 0.0F) {
return;
}
float fraction = target.getHealth() / target.getMaxHealth();
fraction = Math.max(0.0F, Math.min(1.0F, fraction));
double filled = height * fraction;
graphics.fillRect(x, top, HEALTH_BAR_WIDTH, height, HEALTH_BACKGROUND);
graphics.fillRect(x, top + height - filled, HEALTH_BAR_WIDTH, filled,
healthColor(fraction));
}
private String label(EntityTarget target) {
String nameText = name.isEnabled() ? target.getName() : null;
String distanceText = distance.isEnabled()
? String.format(Locale.ROOT, "%.1fm", target.getDistance())
: null;
if (nameText == null) {
return distanceText;
}
if (distanceText == null) {
return nameText;
}
return nameText + " " + distanceText;
}
private int color(EntityTarget target, int index) {
if (colorMode.is("Health")) {
float fraction = target.getMaxHealth() <= 0.0F
? 1.0F
: target.getHealth() / target.getMaxHealth();
return healthColor(Math.max(0.0F, Math.min(1.0F, fraction)));
}
if (colorMode.is("Rainbow")) {
float hue = ((System.currentTimeMillis() % 4000L) / 4000.0F)
+ index * 0.05F;
return Color.HSBtoRGB(hue - (float) Math.floor(hue), 0.85F, 1.0F);
}
return ORANGE;
}
private int healthColor(float fraction) {
return Color.HSBtoRGB(0.33F * fraction, 0.85F, 1.0F);
}
}
@@ -18,7 +18,7 @@ public class HUD extends Module {
private static final float RAINBOW_CYCLE = 6000f;
private static final int LOGO_FONT_SIZE = 22;
private static final int MODULE_FONT_SIZE = 14;
private static final int MODULE_FONT_SIZE = 10;
private static final int LOGO_START_X = 5;
private static final int LOGO_START_Y = 5;
@@ -36,7 +36,7 @@ public final class Render2DManager {
}
public void fire(Object platformContext) {
fire(platformContext, true);
fire(platformContext, true, Float.NaN);
}
/**
@@ -45,6 +45,15 @@ public final class Render2DManager {
* event is dropped unless {@link #isRenderInMenus()} is on.
*/
public void fire(Object platformContext, boolean inWorld) {
fire(platformContext, inWorld, Float.NaN);
}
/**
* @param partialTicks the partial tick the game rendered this frame with,
* or {@link Float#NaN} when the caller has none.
*/
public void fire(Object platformContext, boolean inWorld,
float partialTicks) {
if (!inWorld && !renderInMenus) {
return;
}
@@ -60,7 +69,7 @@ public final class Render2DManager {
Render2D context = backend.createRender2D(fonts, platformContext);
try {
eventBus.post(new EventRender2D(context, inWorld));
eventBus.post(new EventRender2D(context, inWorld, partialTicks));
} finally {
context.flush();
}
@@ -11,6 +11,18 @@ import java.lang.reflect.Method;
*/
final class V26_2GlyphDrawer implements GlyphDrawer {
/**
* Maximum distance (in logical pixels) that still counts as "sitting on the
* baseline" rather than being a descender or a raised glyph.
*
* <p>The atlas is packed with 2x oversampling, so a normal glyph's baked
* bottom is 0.25/0.75px away from the baseline. 26.2 blits use integer
* coordinates, and rounding those offsets per glyph made some letters drop
* onto the next pixel while their neighbours stayed put. Snapping
* near-baseline bottoms to one shared value keeps a line visually level.</p>
*/
private static final double BASELINE_SNAP = 0.9;
private final Object extractor;
private final Method innerBlit;
private final Object guiPipeline;
@@ -28,12 +40,36 @@ final class V26_2GlyphDrawer implements GlyphDrawer {
return;
}
int x0 = (int) Math.round(penX + glyph.getX0() * scale);
int y0 = (int) Math.round(baseline + glyph.getY0() * scale);
int x1 = (int) Math.round(penX + glyph.getX1() * scale);
int y1 = (int) Math.round(baseline + glyph.getY1() * scale);
if (x1 <= x0 || y1 <= y0) {
return;
// Snap both horizontal edges the same way (downwards). Rounding each
// edge independently made neighbouring glyphs drift apart or together
// by one pixel, which is most visible around narrow letters such as I.
int x0 = (int) Math.floor(penX + glyph.getX0() * scale + 0.0001);
int x1 = (int) Math.floor(penX + glyph.getX1() * scale + 0.0001);
// Anchor both edges to one rounded baseline so every glyph in a line
// shares the same pixel origin.
int base = (int) Math.round(baseline);
// Round the top down: curved letters (C, G, o...) overshoot the flat
// cap/x-height by half a pixel in the atlas. Rounding split them onto
// different rows, which made "CLICK GUI" look uneven.
int y0 = base + (int) Math.floor(glyph.getY0() * scale + 0.0001);
double bottomOffset = glyph.getY1() * scale;
int y1;
if (bottomOffset >= 0.0 && bottomOffset < BASELINE_SNAP) {
// Normal letter/punctuation: sit exactly on the baseline.
y1 = base;
} else {
// Descenders (g, p, y...) and raised glyphs keep their offset.
y1 = base + (int) Math.round(bottomOffset);
}
// Thin strokes (l, I, | ...) can be narrower than one GUI pixel at high
// GUI scales. Keep them visible with at least one pixel.
if (x1 <= x0) {
x1 = x0 + 1;
}
if (y1 <= y0) {
y1 = y0 + 1;
}
V26_2FontTexture fontTexture = (V26_2FontTexture) texture;
@@ -49,3 +85,4 @@ final class V26_2GlyphDrawer implements GlyphDrawer {
}
}
}
@@ -0,0 +1,53 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* Smooths hover and toggle values for ClickGUI elements.
*
* <p>Keys are compared by identity so equal-but-distinct modules or values do
* not share an animation.</p>
*/
public final class ClickGuiAnimator {
private static final float HOVER_SPEED = 14.0f;
private static final float STATE_SPEED = 16.0f;
private final Map<Object, Float> hoverAnimations =
new IdentityHashMap<Object, Float>();
private final Map<Object, Float> stateAnimations =
new IdentityHashMap<Object, Float>();
public float hover(Object key, boolean hovered, float delta) {
if (!hoverAnimations.containsKey(key)) {
hoverAnimations.put(key, 0.0f);
}
return animate(hoverAnimations, key, hovered ? 1.0f : 0.0f,
delta, HOVER_SPEED);
}
public float state(Object key, boolean state, float delta) {
return animate(stateAnimations, key, state ? 1.0f : 0.0f,
delta, STATE_SPEED);
}
private static float animate(Map<Object, Float> animations, Object key,
float target, float delta, float speed) {
Float stored = animations.get(key);
float current = stored == null ? target : stored.floatValue();
if (Math.abs(target - current) < 0.001f) {
animations.put(key, target);
return target;
}
float factor = 1.0f - (float) Math.exp(-speed * delta);
float next = current + (target - current) * factor;
if (Math.abs(target - next) < 0.002f) {
next = target;
}
animations.put(key, next);
return next;
}
}
@@ -0,0 +1,87 @@
package cn.xiaozhou233.orangex.ui.clickgui;
/**
* Immutable geometry for one ClickGUI frame.
*
* <p>The panel keeps its own bounds and category-row height; this class turns
* them into the positions and sizes used by the individual renderers.</p>
*/
public final class ClickGuiLayout {
private final float x;
private final float y;
private final float width;
private final float height;
private final float categoryRowHeight;
private final int screenWidth;
private final int screenHeight;
public ClickGuiLayout(float x, float y, float width, float height,
float categoryRowHeight, int screenWidth,
int screenHeight) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.categoryRowHeight = categoryRowHeight;
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
}
public float x() {
return x;
}
public float y() {
return y;
}
public float width() {
return width;
}
public float height() {
return height;
}
public float categoryRowHeight() {
return categoryRowHeight;
}
public int screenWidth() {
return screenWidth;
}
public int screenHeight() {
return screenHeight;
}
public float contentX() {
return x + ClickGuiStyle.SIDEBAR_CARD_X
+ ClickGuiStyle.SIDEBAR_WIDTH + 14.0f;
}
public float contentWidth() {
return x + width - 12.0f - contentX();
}
public float listTop() {
return y + ClickGuiStyle.HEADER_HEIGHT + 38.0f;
}
public float listBottom() {
return y + height - 8.0f;
}
public float categoryRowX() {
return x + ClickGuiStyle.SIDEBAR_CARD_X + 6.0f;
}
public float categoryRowWidth() {
return ClickGuiStyle.SIDEBAR_WIDTH - 12.0f;
}
public float categoryRowTop() {
return y + ClickGuiStyle.SIDEBAR_CARD_Y + 9.0f;
}
}
@@ -0,0 +1,48 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.modules.ModuleCategory;
import cn.xiaozhou233.orangex.value.KeybindValue;
import cn.xiaozhou233.orangex.value.Value;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Module and category helpers shared by the ClickGUI renderers.
*/
public final class ClickGuiModules {
private ClickGuiModules() {
}
public static List<Value<?>> settingsOf(Module module) {
List<Value<?>> settings = new ArrayList<Value<?>>();
for (Value<?> value : module.getVisibleValues()) {
// The module keybind is shown on the collapsed row instead.
if (!(value instanceof KeybindValue)) {
settings.add(value);
}
}
return settings;
}
/**
* Allocation-free variant of {@link #settingsOf(Module)} for rows that only
* need to know whether a settings page can be opened.
*/
public static boolean hasSettings(Module module) {
for (Value<?> value : module.getVisibleValues()) {
if (!(value instanceof KeybindValue)) {
return true;
}
}
return false;
}
public static String displayName(ModuleCategory category) {
String name = category.name();
return name.substring(0, 1) + name.substring(1).toLowerCase(Locale.ROOT);
}
}
@@ -0,0 +1,65 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
import cn.xiaozhou233.orangex.input.ClientInput;
/**
* Renders and drives the ClickGUI while the empty input screen is open.
*
* <p>The input screen only records the raw mouse state in
* {@link ClientInput}; this class turns button transitions into component
* callbacks and then renders {@link MainPanel}.</p>
*/
public final class ClickGuiRender {
private static final MainPanel MAIN_PANEL = new MainPanel();
private static boolean lastLeftDown;
private static boolean lastRightDown;
private ClickGuiRender() {
}
public static void render(EventRender2D event) {
if (!ClientInput.isOpen()) {
reset();
return;
}
float mouseX = (float) ClientInput.getMouseX();
float mouseY = (float) ClientInput.getMouseY();
boolean leftDown = ClientInput.isLeftDown();
boolean rightDown = ClientInput.isRightDown();
if (leftDown && !lastLeftDown) {
MAIN_PANEL.mouseClicked(mouseX, mouseY, 0);
}
if (rightDown && !lastRightDown) {
MAIN_PANEL.mouseClicked(mouseX, mouseY, 1);
}
if (leftDown && lastLeftDown) {
MAIN_PANEL.mouseDragged(mouseX, mouseY, 0);
}
if (!leftDown && lastLeftDown) {
MAIN_PANEL.mouseReleased(mouseX, mouseY, 0);
}
if (!rightDown && lastRightDown) {
MAIN_PANEL.mouseReleased(mouseX, mouseY, 1);
}
MAIN_PANEL.render(event);
lastLeftDown = leftDown;
lastRightDown = rightDown;
}
/**
* Drops transient input state. Called when the GUI closes or reopens so a
* button held across screens does not produce a stale drag.
*/
public static void reset() {
MAIN_PANEL.resetInteraction();
lastLeftDown = false;
lastRightDown = false;
}
}
@@ -0,0 +1,137 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.render.api.FontRenderer;
import cn.xiaozhou233.orangex.render.api.Render2D;
import cn.xiaozhou233.orangex.render.font.FontFamily;
/**
* Shared colours, metrics and drawing primitives for the ClickGUI.
*
* <p>All colours are ARGB and all coordinates are Minecraft GUI pixels.</p>
*/
public final class ClickGuiStyle {
/**
* Font family used only by the ClickGUI. Other screens keep using the
* globally configured default family.
*/
public static final FontFamily FONT_FAMILY = FontFamily.MONTSERRAT;
public static final float DESIGN_WIDTH = 448f;
public static final float DESIGN_HEIGHT = 306f;
public static final float MARGIN = 12f;
public static final float PANEL_RADIUS = 9f;
public static final float HEADER_HEIGHT = 46f;
public static final float SIDEBAR_WIDTH = 112f;
public static final float SIDEBAR_CARD_X = 10f;
public static final float SIDEBAR_CARD_Y = HEADER_HEIGHT + 8f;
public static final float CATEGORY_HEIGHT = 26f;
public static final float CATEGORY_GAP = 2f;
public static final float MODULE_HEIGHT = 27f;
public static final float MODULE_GAP = 3f;
public static final float TOGGLE_WIDTH = 26f;
public static final float TOGGLE_HEIGHT = 12f;
public static final float SMALL_TOGGLE_WIDTH = 20f;
public static final float SMALL_TOGGLE_HEIGHT = 9f;
public static final int COLOR_PANEL = 0xF218181D;
public static final int COLOR_BORDER = 0xFF2C2C37;
public static final int COLOR_TEXT = 0xFFEDEDF2;
public static final int COLOR_TEXT_DIM = 0xFF9A9AA8;
public static final int COLOR_TEXT_MUTED = 0xFF61616F;
public static final int COLOR_ACCENT = 0xFFFF8A3D;
public static final int COLOR_ACCENT_RGB = 0x00FF8A3D;
public static final int COLOR_DIVIDER = 0xFF272730;
public static final int COLOR_SIDEBAR_BG = 0xFF15151A;
public static final int COLOR_SIDEBAR_BORDER = 0xFF24242C;
public static final int COLOR_SWITCH_OFF = 0xFF34343F;
public static final int COLOR_KNOB_OFF = 0xFF9A9AA8;
public static final int COLOR_SCROLLBAR = 0x40FFFFFF;
private ClickGuiStyle() {
}
public static FontRenderer font(Render2D graphics, float size) {
return graphics.getFont(FONT_FAMILY, size);
}
public static FontRenderer font(Render2D graphics, float size, boolean bold) {
return graphics.getFont(FONT_FAMILY, size, bold);
}
public static void drawSwitch(Render2D graphics, float switchX, float switchY,
float switchWidth, float switchHeight,
float progress) {
int track = lerpColor(COLOR_SWITCH_OFF, COLOR_ACCENT, progress);
graphics.fillRoundedRect(switchX, switchY, switchWidth, switchHeight,
switchHeight / 2.0f, track);
float knobSize = switchHeight - 4.0f;
float knobX = switchX + 2.0f
+ (switchWidth - knobSize - 4.0f) * progress;
int knob = lerpColor(COLOR_KNOB_OFF, 0xFFFFFFFF, progress);
graphics.fillRoundedRect(knobX, switchY + 2.0f, knobSize, knobSize,
knobSize / 2.0f, knob);
}
public static double centeredY(FontRenderer font, float top, float height) {
return top + (height - font.getStringHeight()) / 2.0;
}
/**
* Draws a thin scrollbar for a scrollable list. Nothing is drawn while the
* content fits, so short lists look unchanged.
*/
public static void drawScrollbar(Render2D graphics, double x, double top,
double viewHeight, double contentHeight,
double scroll) {
if (contentHeight <= viewHeight + 0.5) {
return;
}
double thumbHeight = Math.max(18.0,
viewHeight * (viewHeight / contentHeight));
double maxScroll = contentHeight - viewHeight;
double progress = maxScroll <= 0.0 ? 0.0
: clamp((float) (scroll / maxScroll), 0.0f, 1.0f);
double thumbY = top + (viewHeight - thumbHeight) * progress;
graphics.fillRoundedRect(x, thumbY, 2.0, thumbHeight, 1.0,
COLOR_SCROLLBAR);
}
public static boolean isInside(double mouseX, double mouseY,
double x, double y,
double width, double height) {
return mouseX >= x && mouseX <= x + width
&& mouseY >= y && mouseY <= y + height;
}
public static float clamp(float value, float min, float max) {
return Math.max(min, Math.min(max, value));
}
public static int argb(int alpha, int rgb) {
int clamped = Math.max(0, Math.min(255, alpha));
return (clamped << 24) | (rgb & 0x00FFFFFF);
}
public static int lerpColor(int from, int to, float progress) {
float t = clamp(progress, 0.0f, 1.0f);
int a = lerpChannel(from >>> 24, to >>> 24, t);
int r = lerpChannel(from >> 16, to >> 16, t);
int g = lerpChannel(from >> 8, to >> 8, t);
int b = lerpChannel(from, to, t);
return (a << 24) | (r << 16) | (g << 8) | b;
}
private static int lerpChannel(int from, int to, float t) {
int fromChannel = from & 0xFF;
int toChannel = to & 0xFF;
return Math.round(fromChannel + (toChannel - fromChannel) * t);
}
}
@@ -0,0 +1,78 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.modules.Module;
import java.util.List;
/**
* Row geometry for the module list.
*
* <p>Module rows are evenly sized, so a row's position is just its index times
* the row stride minus the scroll offset. The renderer and the input code share
* this class so both always agree on where a row is.</p>
*/
public final class ContentList {
private final ClickGuiLayout layout;
private final List<Module> modules;
private float scroll;
public ContentList(ClickGuiLayout layout, List<Module> modules,
float scroll) {
this.layout = layout;
this.modules = modules;
this.scroll = scroll;
}
public List<Module> modules() {
return modules;
}
public float scroll() {
return scroll;
}
public void scrollBy(float amount) {
scroll += amount;
}
/**
* Clamps the scroll offset to the current content, so switching category
* never leaves the list overscrolled.
*/
public void clampScroll() {
scroll = ClickGuiStyle.clamp(scroll, 0.0f, maxScroll());
}
public float rowStride() {
return ClickGuiStyle.MODULE_HEIGHT + ClickGuiStyle.MODULE_GAP;
}
public float rowTop(int index) {
return layout.listTop() + index * rowStride() - scroll;
}
public float contentHeight() {
return modules.isEmpty() ? 0.0f
: modules.size() * rowStride() - ClickGuiStyle.MODULE_GAP;
}
public float maxScroll() {
return Math.max(0.0f,
contentHeight() - (layout.listBottom() - layout.listTop()));
}
/**
* @return the index of the module row under {@code mouseY}, or {@code -1}.
*/
public int moduleIndexAt(float mouseY) {
for (int i = 0; i < modules.size(); i++) {
float top = rowTop(i);
if (mouseY >= top && mouseY <= top + ClickGuiStyle.MODULE_HEIGHT) {
return i;
}
}
return -1;
}
}
@@ -0,0 +1,133 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.modules.ModuleCategory;
import cn.xiaozhou233.orangex.render.api.FontRenderer;
import cn.xiaozhou233.orangex.render.api.Render2D;
import cn.xiaozhou233.orangex.value.KeybindValue;
import java.util.List;
/**
* Draws the module list for the selected category.
*
* <p>Right-clicking a module opens its settings page in this same content area
* (see {@link SettingsSection}). The list scrolls with the wheel and shows a
* scrollbar when it does not fit.</p>
*/
public final class ContentRenderer {
private ContentRenderer() {
}
public static void draw(Render2D graphics, ClickGuiLayout layout,
ContentList rows, ModuleCategory category,
ClickGuiAnimator animator, float delta,
double mouseX, double mouseY) {
float y = layout.y();
float contentX = layout.contentX();
float contentWidth = layout.contentWidth();
List<Module> modules = rows.modules();
FontRenderer title = ClickGuiStyle.font(graphics, 13.0f, true);
title.drawString(ClickGuiModules.displayName(category), contentX,
y + ClickGuiStyle.HEADER_HEIGHT + 10,
ClickGuiStyle.COLOR_TEXT);
FontRenderer meta = ClickGuiStyle.font(graphics, 8.0f);
String metaText = modules.size()
+ (modules.size() == 1 ? " MODULE" : " MODULES");
meta.drawString(metaText,
contentX + contentWidth - meta.getStringWidth(metaText),
y + ClickGuiStyle.HEADER_HEIGHT + 14,
ClickGuiStyle.COLOR_TEXT_MUTED);
graphics.fillRect(contentX, y + ClickGuiStyle.HEADER_HEIGHT + 30,
contentWidth, 1, ClickGuiStyle.COLOR_DIVIDER);
float listTop = layout.listTop();
float listBottom = layout.listBottom();
graphics.enableScissor(contentX - 2, listTop - 2,
contentWidth + 4, listBottom - listTop + 4);
if (modules.isEmpty()) {
FontRenderer empty = ClickGuiStyle.font(graphics, 9.0f);
String text = "No modules here yet";
empty.drawString(text,
contentX + (contentWidth - empty.getStringWidth(text)) / 2.0,
listTop + 14, ClickGuiStyle.COLOR_TEXT_MUTED);
} else {
for (int i = 0; i < modules.size(); i++) {
Module module = modules.get(i);
float rowY = rows.rowTop(i);
if (rowY > listBottom
|| rowY + ClickGuiStyle.MODULE_HEIGHT < listTop) {
continue;
}
boolean hovered = mouseY >= listTop && mouseY <= listBottom
&& ClickGuiStyle.isInside(mouseX, mouseY, contentX,
rowY, contentWidth, ClickGuiStyle.MODULE_HEIGHT);
float hover = animator.hover(module, hovered, delta);
drawModuleRow(graphics, layout, module, rowY, hover, animator,
delta);
}
}
graphics.disableScissor();
ClickGuiStyle.drawScrollbar(graphics, contentX + contentWidth - 3,
listTop, listBottom - listTop, rows.contentHeight(),
rows.scroll());
}
private static void drawModuleRow(Render2D graphics, ClickGuiLayout layout,
Module module, float rowY, float hover,
ClickGuiAnimator animator, float delta) {
float contentX = layout.contentX();
float contentWidth = layout.contentWidth();
float rowRight = contentX + contentWidth;
float moduleHeight = ClickGuiStyle.MODULE_HEIGHT;
int background = module.isEnabled()
? ClickGuiStyle.argb((int) (14.0f + 14.0f * hover),
ClickGuiStyle.COLOR_ACCENT_RGB)
: ClickGuiStyle.argb((int) (6.0f + 10.0f * hover),
0x00FFFFFF);
graphics.fillRoundedRect(contentX, rowY, contentWidth, moduleHeight,
5, background);
if (module.isEnabled()) {
graphics.fillRoundedRect(contentX + 2, rowY + 8, 2.0f,
moduleHeight - 16, 1.0f, ClickGuiStyle.COLOR_ACCENT);
}
FontRenderer name = ClickGuiStyle.font(graphics, 10.0f,
module.isEnabled());
name.drawString(module.getName(), contentX + 10,
ClickGuiStyle.centeredY(name, rowY, moduleHeight),
module.isEnabled() ? ClickGuiStyle.COLOR_TEXT
: ClickGuiStyle.COLOR_TEXT_DIM);
KeybindValue keybind = module.getKeybind();
if (keybind.isBound()) {
FontRenderer keyFont = ClickGuiStyle.font(graphics, 8.0f);
String key = KeyNames.keyName(keybind.getKey());
keyFont.drawString(key,
rowRight - ClickGuiStyle.TOGGLE_WIDTH - 18
- keyFont.getStringWidth(key),
ClickGuiStyle.centeredY(keyFont, rowY, moduleHeight),
ClickGuiStyle.COLOR_TEXT_MUTED);
}
float toggleX = rowRight - ClickGuiStyle.TOGGLE_WIDTH - 10;
float toggleY = rowY + (moduleHeight - ClickGuiStyle.TOGGLE_HEIGHT)
/ 2.0f;
ClickGuiStyle.drawSwitch(graphics, toggleX, toggleY,
ClickGuiStyle.TOGGLE_WIDTH, ClickGuiStyle.TOGGLE_HEIGHT,
animator.state(module, module.isEnabled(), delta));
}
}
@@ -0,0 +1,114 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.input.KeyCodes;
/**
* Maps raw GLFW-style key codes to the short labels shown in the ClickGUI.
*/
public final class KeyNames {
private KeyNames() {
}
public static String keyName(int key) {
if (key == KeyCodes.NONE) {
return "NONE";
}
switch (key) {
case 1: return "ESC";
case 2: return "1";
case 3: return "2";
case 4: return "3";
case 5: return "4";
case 6: return "5";
case 7: return "6";
case 8: return "7";
case 9: return "8";
case 10: return "9";
case 11: return "0";
case 12: return "MINUS";
case 13: return "EQUAL";
case 14: return "BACKSPACE";
case 15: return "TAB";
case 16: return "Q";
case 17: return "W";
case 18: return "E";
case 19: return "R";
case 20: return "T";
case 21: return "Y";
case 22: return "U";
case 23: return "I";
case 24: return "O";
case 25: return "P";
case 26: return "[";
case 27: return "]";
case 28: return "ENTER";
case 29: return "LCTRL";
case 30: return "A";
case 31: return "S";
case 32: return "D";
case 33: return "F";
case 34: return "G";
case 35: return "H";
case 36: return "J";
case 37: return "K";
case 38: return "L";
case 39: return ";";
case 40: return "'";
case 41: return "`";
case 42: return "LSHIFT";
case 43: return "\\";
case 44: return "Z";
case 45: return "X";
case 46: return "C";
case 47: return "V";
case 48: return "B";
case 49: return "N";
case 50: return "M";
case 51: return ",";
case 52: return ".";
case 53: return "/";
case 54: return "RSHIFT";
case 55: return "NUMPAD*";
case 56: return "LALT";
case 57: return "SPACE";
case 58: return "CAPS";
case 69: return "NUMLOCK";
case 70: return "SCROLL";
case 74: return "NUMPAD-";
case 78: return "NUMPAD+";
case 82: return "NUMPAD0";
case 79: return "NUMPAD1";
case 80: return "NUMPAD2";
case 81: return "NUMPAD3";
case 75: return "NUMPAD4";
case 76: return "NUMPAD5";
case 77: return "NUMPAD6";
case 71: return "NUMPAD7";
case 72: return "NUMPAD8";
case 73: return "NUMPAD9";
case 87: return "F11";
case 88: return "F12";
case 157: return "RCTRL";
case 184: return "RALT";
case 200: return "UP";
case 203: return "LEFT";
case 208: return "DOWN";
case 205: return "RIGHT";
case 210: return "INSERT";
case 211: return "DELETE";
case 199: return "HOME";
case 207: return "END";
case 201: return "PAGE UP";
case 209: return "PAGE DOWN";
default:
break;
}
if (key >= 59 && key <= 68) {
return "F" + (key - 58);
}
return "KEY " + key;
}
}
@@ -0,0 +1,314 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
import cn.xiaozhou233.orangex.input.ClientInput;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.modules.ModuleCategory;
import cn.xiaozhou233.orangex.modules.ModuleManager;
import cn.xiaozhou233.orangex.render.api.Render2D;
import cn.xiaozhou233.orangex.ui.clickgui.component.Component;
import cn.xiaozhou233.orangex.value.Value;
import java.util.Collections;
import java.util.List;
/**
* The main ClickGUI window.
*
* <p>A single rounded window with a category sidebar on the left and the
* selected category's modules on the right. Left-clicking a module toggles it;
* right-clicking a module swaps the content area to its settings page, which is
* left with the back button next to the module name. The window itself can be
* dragged by its header.</p>
*
* <p>All coordinates are Minecraft GUI pixels. Input is polled from
* {@link ClientInput} because the empty input screen does not forward
* callbacks to this class directly. This class owns the window state and input
* routing; drawing is delegated to the renderer classes in this package.</p>
*/
public final class MainPanel extends Component {
private static final ModuleCategory[] CATEGORIES = ModuleCategory.values();
/** Pixels scrolled per wheel notch. */
private static final float SCROLL_STEP = 24.0f;
private final ModuleManager moduleManager =
OrangeX.getInstance().getModuleManager();
private final ClickGuiAnimator animator = new ClickGuiAnimator();
private ModuleCategory selectedCategory = ModuleCategory.RENDER;
/** Module whose settings page replaces the list, or {@code null}. */
private Module settingsModule;
private float scrollOffset;
private boolean hasPosition;
private boolean dragging;
private float dragOffsetX;
private float dragOffsetY;
private int screenWidth = 854;
private int screenHeight = 480;
private float categoryRowHeight = ClickGuiStyle.CATEGORY_HEIGHT;
private long lastFrameNanos;
@Override
public void render(EventRender2D event) {
Render2D graphics = event.getRender2D();
updateBounds(graphics);
ClickGuiLayout layout = layout();
applyScroll(layout);
float delta = updateDelta();
double mouseX = ClientInput.getMouseX();
double mouseY = ClientInput.getMouseY();
PanelChrome.drawShadow(graphics, layout);
graphics.fillRoundedRect(layout.x(), layout.y(), layout.width(),
layout.height(), ClickGuiStyle.PANEL_RADIUS, 1.0,
ClickGuiStyle.COLOR_PANEL, ClickGuiStyle.COLOR_BORDER);
PanelChrome.drawHeader(graphics, layout);
SidebarRenderer.draw(graphics, layout, selectedCategory,
moduleManager.getAllModules(), animator, delta, mouseX, mouseY);
if (settingsModule == null) {
ContentRenderer.draw(graphics, layout, contentList(layout),
selectedCategory, animator, delta, mouseX, mouseY);
} else {
SettingsSection.draw(graphics, layout, settingsModule,
settingsOf(), scrollOffset, animator, delta, mouseX, mouseY);
}
}
@Override
public void mouseClicked(float mouseX, float mouseY, int button) {
if (!ClickGuiStyle.isInside(mouseX, mouseY, x, y, width, height)) {
return;
}
if (ClickGuiStyle.isInside(mouseX, mouseY, x, y, width,
ClickGuiStyle.HEADER_HEIGHT)) {
if (button == 0) {
dragging = true;
dragOffsetX = mouseX - x;
dragOffsetY = mouseY - y;
}
return;
}
ClickGuiLayout layout = layout();
ModuleCategory category = categoryAt(layout, mouseX, mouseY);
if (category != null) {
if (category != selectedCategory) {
selectedCategory = category;
}
closeSettings();
return;
}
if (settingsModule != null) {
handleSettingsClick(layout, mouseX, mouseY, button);
return;
}
handleContentClick(layout, mouseX, mouseY, button);
}
@Override
public void mouseDragged(float mouseX, float mouseY, int button) {
if (!dragging || button != 0) {
return;
}
float maxX = Math.max(4.0f, screenWidth - width - 4.0f);
float maxY = Math.max(4.0f, screenHeight - height - 4.0f);
x = ClickGuiStyle.clamp(mouseX - dragOffsetX, 4.0f, maxX);
y = ClickGuiStyle.clamp(mouseY - dragOffsetY, 4.0f, maxY);
// 26.2 glyph blits snap to whole pixels; a fractional panel origin
// makes every glyph round independently while dragging. Keep the
// window on the pixel grid so text moves as one stable block.
x = Math.round(x);
y = Math.round(y);
hasPosition = true;
}
@Override
public void mouseReleased(float mouseX, float mouseY, int button) {
if (button == 0) {
dragging = false;
}
}
public void resetInteraction() {
dragging = false;
closeSettings();
}
/* ------------------------------------------------------------------ */
/* Interaction */
/* ------------------------------------------------------------------ */
private boolean handleContentClick(ClickGuiLayout layout, float mouseX,
float mouseY, int button) {
if (mouseY < layout.listTop() || mouseY > layout.listBottom()) {
return false;
}
if (mouseX < layout.contentX()
|| mouseX > layout.contentX() + layout.contentWidth()) {
return false;
}
ContentList rows = contentList(layout);
int moduleIndex = rows.moduleIndexAt(mouseY);
if (moduleIndex < 0) {
return false;
}
Module module = rows.modules().get(moduleIndex);
if (button == 0) {
module.toggle();
} else if (button == 1 && ClickGuiModules.hasSettings(module)) {
settingsModule = module;
scrollOffset = 0.0f;
}
return true;
}
private boolean handleSettingsClick(ClickGuiLayout layout, float mouseX,
float mouseY, int button) {
if (button == 0 && SettingsSection.isBackButton(layout, mouseX,
mouseY)) {
closeSettings();
return true;
}
List<Value<?>> settings = settingsOf();
int index = SettingsSection.rowIndexAt(layout, settings, scrollOffset,
mouseY);
if (index >= 0) {
SettingsSection.click(settings, index, button);
return true;
}
return false;
}
private void closeSettings() {
settingsModule = null;
scrollOffset = 0.0f;
}
private ModuleCategory categoryAt(ClickGuiLayout layout, float mouseX,
float mouseY) {
float rowX = layout.categoryRowX();
float rowWidth = layout.categoryRowWidth();
float rowY = layout.categoryRowTop();
float rowHeight = layout.categoryRowHeight();
for (ModuleCategory category : CATEGORIES) {
if (ClickGuiStyle.isInside(mouseX, mouseY, rowX, rowY,
rowWidth, rowHeight)) {
return category;
}
rowY += rowHeight + ClickGuiStyle.CATEGORY_GAP;
}
return null;
}
/* ------------------------------------------------------------------ */
/* Layout helpers */
/* ------------------------------------------------------------------ */
private ClickGuiLayout layout() {
return new ClickGuiLayout(x, y, width, height, categoryRowHeight,
screenWidth, screenHeight);
}
private ContentList contentList(ClickGuiLayout layout) {
return new ContentList(layout, modulesOf(selectedCategory),
scrollOffset);
}
private List<Value<?>> settingsOf() {
return settingsModule == null
? Collections.<Value<?>>emptyList()
: ClickGuiModules.settingsOf(settingsModule);
}
/**
* Applies this frame's wheel input to whichever list is visible and keeps
* its offset inside the content.
*/
private void applyScroll(ClickGuiLayout layout) {
double wheel = ClientInput.consumeScroll();
float step = (float) -wheel * SCROLL_STEP;
if (settingsModule != null) {
scrollOffset = ClickGuiStyle.clamp(scrollOffset + step, 0.0f,
SettingsSection.maxScroll(layout, settingsOf()));
return;
}
ContentList rows = contentList(layout);
if (wheel != 0.0) {
rows.scrollBy(step);
}
rows.clampScroll();
scrollOffset = rows.scroll();
}
private void updateBounds(Render2D graphics) {
screenWidth = graphics.getWidth();
screenHeight = graphics.getHeight();
width = Math.min(ClickGuiStyle.DESIGN_WIDTH,
Math.max(280.0f, screenWidth - ClickGuiStyle.MARGIN * 2.0f));
height = Math.min(ClickGuiStyle.DESIGN_HEIGHT,
Math.max(220.0f, screenHeight - ClickGuiStyle.MARGIN * 2.0f));
// Keep all seven category rows inside the sidebar card even when the
// panel is compressed by a small GUI-scaled screen.
float cardHeight = height - ClickGuiStyle.HEADER_HEIGHT - 16.0f;
float availableRows = cardHeight - 18.0f;
float rowHeight = (availableRows
- (CATEGORIES.length - 1) * ClickGuiStyle.CATEGORY_GAP)
/ CATEGORIES.length;
categoryRowHeight = Math.max(12.0f,
Math.min(ClickGuiStyle.CATEGORY_HEIGHT, rowHeight));
if (!hasPosition) {
x = (screenWidth - width) / 2.0f;
y = (screenHeight - height) / 2.0f;
hasPosition = true;
}
x = ClickGuiStyle.clamp(x, 4.0f,
Math.max(4.0f, screenWidth - width - 4.0f));
y = ClickGuiStyle.clamp(y, 4.0f,
Math.max(4.0f, screenHeight - height - 4.0f));
x = Math.round(x);
y = Math.round(y);
}
private float updateDelta() {
long now = System.nanoTime();
if (lastFrameNanos == 0L) {
lastFrameNanos = now;
return 0.016f;
}
float delta = (now - lastFrameNanos) / 1_000_000_000.0f;
lastFrameNanos = now;
return ClickGuiStyle.clamp(delta, 0.0f, 0.1f);
}
private List<Module> modulesOf(ModuleCategory category) {
return moduleManager.getModulesByCategory(category);
}
}
@@ -0,0 +1,48 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.render.api.FontRenderer;
import cn.xiaozhou233.orangex.render.api.Render2D;
/**
* Draws the parts of the window that never change with the selected category:
* the drop shadow and the header.
*/
public final class PanelChrome {
private PanelChrome() {
}
public static void drawShadow(Render2D graphics, ClickGuiLayout layout) {
float x = layout.x();
float y = layout.y();
float width = layout.width();
float height = layout.height();
graphics.fillRoundedRect(x - 4, y + 3, width + 8, height + 6,
ClickGuiStyle.PANEL_RADIUS + 4, 0x1C000000);
graphics.fillRoundedRect(x - 2, y + 1, width + 4, height + 3,
ClickGuiStyle.PANEL_RADIUS + 2, 0x26000000);
}
public static void drawHeader(Render2D graphics, ClickGuiLayout layout) {
float x = layout.x();
float y = layout.y();
float width = layout.width();
FontRenderer logo = ClickGuiStyle.font(graphics, 16.0f, true);
String brand = "Orange";
double brandX = x + 16;
double brandY = y + 9;
logo.drawString(brand, brandX, brandY, ClickGuiStyle.COLOR_TEXT);
logo.drawString("X", brandX + logo.getStringWidth(brand), brandY,
ClickGuiStyle.COLOR_ACCENT);
FontRenderer subtitle = ClickGuiStyle.font(graphics, 7.5f, true);
subtitle.drawString("CLICK GUI", x + 17, y + 28,
ClickGuiStyle.COLOR_TEXT_MUTED);
graphics.fillRect(x + 14, y + ClickGuiStyle.HEADER_HEIGHT - 1,
width - 28, 1, ClickGuiStyle.COLOR_DIVIDER);
}
}
@@ -0,0 +1,217 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.render.api.FontRenderer;
import cn.xiaozhou233.orangex.render.api.Render2D;
import cn.xiaozhou233.orangex.value.BooleanValue;
import cn.xiaozhou233.orangex.value.ModeValue;
import cn.xiaozhou233.orangex.value.Value;
import java.util.List;
/**
* The settings page shown in the content area of {@link MainPanel}.
*
* <p>Opening a module's settings replaces the module list instead of spawning a
* separate window. The page keeps the list's scroll viewport and is left with
* the back button drawn next to the module name.</p>
*/
public final class SettingsSection {
/** Height of one settings row. */
public static final float ROW_HEIGHT = 22f;
private static final float BACK_SIZE = 16f;
private static final float BACK_GAP = 6f;
private static final Object BACK_HOVER_KEY = new Object();
private SettingsSection() {
}
/**
* @return the total height of the rows, which may exceed the visible list.
*/
public static float contentHeight(List<Value<?>> settings) {
return settings.size() * ROW_HEIGHT;
}
public static float maxScroll(ClickGuiLayout layout, List<Value<?>> settings) {
return Math.max(0.0f,
contentHeight(settings)
- (layout.listBottom() - layout.listTop()));
}
public static void draw(Render2D graphics, ClickGuiLayout layout,
Module module, List<Value<?>> settings, float scroll,
ClickGuiAnimator animator, float delta,
double mouseX, double mouseY) {
float contentX = layout.contentX();
float contentWidth = layout.contentWidth();
float headerY = layout.y() + ClickGuiStyle.HEADER_HEIGHT;
drawBackButton(graphics, layout, animator, delta, mouseX, mouseY);
FontRenderer title = ClickGuiStyle.font(graphics, 13.0f, true);
title.drawString(module.getName(),
contentX + BACK_SIZE + BACK_GAP + 4,
headerY + 10, ClickGuiStyle.COLOR_TEXT);
FontRenderer meta = ClickGuiStyle.font(graphics, 8.0f);
String metaText = "SETTINGS";
meta.drawString(metaText,
contentX + contentWidth - meta.getStringWidth(metaText),
headerY + 14, ClickGuiStyle.COLOR_TEXT_MUTED);
graphics.fillRect(contentX, headerY + 30, contentWidth, 1,
ClickGuiStyle.COLOR_DIVIDER);
float listTop = layout.listTop();
float listBottom = layout.listBottom();
graphics.enableScissor(contentX - 2, listTop - 2,
contentWidth + 4, listBottom - listTop + 4);
float rowY = listTop - scroll;
for (Value<?> value : settings) {
if (rowY + ROW_HEIGHT >= listTop && rowY <= listBottom) {
drawRow(graphics, layout, value, rowY, animator, delta,
mouseX, mouseY);
}
rowY += ROW_HEIGHT;
}
graphics.disableScissor();
ClickGuiStyle.drawScrollbar(graphics, contentX + contentWidth - 3,
listTop, listBottom - listTop, contentHeight(settings), scroll);
}
private static void drawBackButton(Render2D graphics, ClickGuiLayout layout,
ClickGuiAnimator animator, float delta,
double mouseX, double mouseY) {
float backX = layout.contentX();
float backY = backTop(layout);
boolean hovered = ClickGuiStyle.isInside(mouseX, mouseY, backX, backY,
BACK_SIZE, BACK_SIZE);
float hover = animator.hover(BACK_HOVER_KEY, hovered, delta);
if (hover > 0.01f) {
graphics.fillRoundedRect(backX, backY, BACK_SIZE, BACK_SIZE, 4,
ClickGuiStyle.argb((int) (22.0f * hover),
ClickGuiStyle.COLOR_ACCENT_RGB));
}
FontRenderer arrow = ClickGuiStyle.font(graphics, 9.0f, true);
arrow.drawCenteredString("<", backX + BACK_SIZE / 2.0,
ClickGuiStyle.centeredY(arrow, backY, BACK_SIZE),
hovered ? ClickGuiStyle.COLOR_ACCENT
: ClickGuiStyle.COLOR_TEXT_MUTED);
}
private static void drawRow(Render2D graphics, ClickGuiLayout layout,
Value<?> value, float rowY,
ClickGuiAnimator animator, float delta,
double mouseX, double mouseY) {
float rowLeft = layout.contentX();
float rowWidth = layout.contentWidth();
boolean hovered = mouseY >= layout.listTop()
&& mouseY <= layout.listBottom()
&& ClickGuiStyle.isInside(mouseX, mouseY, rowLeft, rowY,
rowWidth, ROW_HEIGHT);
float hover = animator.hover(value, hovered, delta);
if (hover > 0.01f) {
graphics.fillRoundedRect(rowLeft, rowY, rowWidth, ROW_HEIGHT, 4,
ClickGuiStyle.argb((int) (10.0f * hover), 0x00FFFFFF));
}
FontRenderer label = ClickGuiStyle.font(graphics, 9.0f);
label.drawString(value.getName(), rowLeft + 8,
ClickGuiStyle.centeredY(label, rowY, ROW_HEIGHT),
ClickGuiStyle.COLOR_TEXT_DIM);
float right = rowLeft + rowWidth - 8;
if (value instanceof BooleanValue) {
BooleanValue booleanValue = (BooleanValue) value;
float toggleWidth = ClickGuiStyle.SMALL_TOGGLE_WIDTH;
float toggleHeight = ClickGuiStyle.SMALL_TOGGLE_HEIGHT;
ClickGuiStyle.drawSwitch(graphics,
right - toggleWidth,
rowY + (ROW_HEIGHT - toggleHeight) / 2.0f,
toggleWidth, toggleHeight,
animator.state(value, booleanValue.isEnabled(), delta));
} else if (value instanceof ModeValue) {
ModeValue modeValue = (ModeValue) value;
FontRenderer modeFont = ClickGuiStyle.font(graphics, 9.0f);
String text = "< " + modeValue.getMode() + " >";
double pillWidth = modeFont.getStringWidth(text) + 10;
double pillX = right - pillWidth;
graphics.fillRoundedRect(pillX, rowY + 4, pillWidth,
ROW_HEIGHT - 8, 4,
ClickGuiStyle.argb(16, 0x00FFFFFF));
modeFont.drawString(text, pillX + 5,
ClickGuiStyle.centeredY(modeFont, rowY, ROW_HEIGHT),
ClickGuiStyle.COLOR_ACCENT);
} else {
FontRenderer valueFont = ClickGuiStyle.font(graphics, 9.0f);
String text = String.valueOf(value.getValue());
valueFont.drawString(text, right - valueFont.getStringWidth(text),
ClickGuiStyle.centeredY(valueFont, rowY, ROW_HEIGHT),
ClickGuiStyle.COLOR_TEXT_MUTED);
}
}
public static boolean isBackButton(ClickGuiLayout layout, double mouseX,
double mouseY) {
return ClickGuiStyle.isInside(mouseX, mouseY, layout.contentX(),
backTop(layout), BACK_SIZE, BACK_SIZE);
}
/**
* @return the index of the settings row under {@code mouseY}, or {@code -1}
* when the pointer is between rows.
*/
public static int rowIndexAt(ClickGuiLayout layout,
List<Value<?>> settings, float scroll,
float mouseY) {
if (mouseY < layout.listTop() || mouseY > layout.listBottom()) {
return -1;
}
float local = mouseY - (layout.listTop() - scroll);
int index = (int) Math.floor(local / ROW_HEIGHT);
return index >= 0 && index < settings.size() ? index : -1;
}
/**
* Applies a click to one settings row. Left-click toggles or advances,
* right-click steps a mode back; other value types are display-only.
*/
public static void click(List<Value<?>> settings, int index, int button) {
if (index < 0 || index >= settings.size()) {
return;
}
if (button != 0 && button != 1) {
return;
}
Value<?> value = settings.get(index);
if (value instanceof BooleanValue) {
if (button == 0) {
((BooleanValue) value).toggle();
}
} else if (value instanceof ModeValue) {
if (button == 0) {
((ModeValue) value).next();
} else {
((ModeValue) value).previous();
}
}
}
private static float backTop(ClickGuiLayout layout) {
return layout.y() + ClickGuiStyle.HEADER_HEIGHT + 8.0f;
}
}
@@ -0,0 +1,86 @@
package cn.xiaozhou233.orangex.ui.clickgui;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.modules.ModuleCategory;
import cn.xiaozhou233.orangex.render.api.FontRenderer;
import cn.xiaozhou233.orangex.render.api.Render2D;
import java.util.List;
/**
* Draws the category card on the left of the ClickGUI window.
*/
public final class SidebarRenderer {
private static final ModuleCategory[] CATEGORIES = ModuleCategory.values();
private SidebarRenderer() {
}
public static void draw(Render2D graphics, ClickGuiLayout layout,
ModuleCategory selectedCategory, List<Module> modules,
ClickGuiAnimator animator, float delta,
double mouseX, double mouseY) {
float x = layout.x();
float y = layout.y();
float cardX = x + ClickGuiStyle.SIDEBAR_CARD_X;
float cardY = y + ClickGuiStyle.SIDEBAR_CARD_Y;
float cardWidth = ClickGuiStyle.SIDEBAR_WIDTH;
float cardHeight = layout.height() - ClickGuiStyle.HEADER_HEIGHT
- 16;
graphics.fillRoundedRect(cardX, cardY, cardWidth, cardHeight, 6,
1.0, ClickGuiStyle.COLOR_SIDEBAR_BG,
ClickGuiStyle.COLOR_SIDEBAR_BORDER);
int[] counts = new int[CATEGORIES.length];
for (Module module : modules) {
counts[module.getCategory().ordinal()]++;
}
float rowX = layout.categoryRowX();
float rowWidth = layout.categoryRowWidth();
float rowY = layout.categoryRowTop();
float rowHeight = layout.categoryRowHeight();
for (ModuleCategory category : CATEGORIES) {
boolean selected = category == selectedCategory;
boolean hovered = ClickGuiStyle.isInside(mouseX, mouseY, rowX, rowY,
rowWidth, rowHeight);
float hover = animator.hover(category, hovered, delta);
if (selected || hover > 0.01f) {
int alpha = selected
? (int) (22.0f + 10.0f * hover)
: (int) (10.0f * hover);
graphics.fillRoundedRect(rowX, rowY, rowWidth, rowHeight, 5,
ClickGuiStyle.argb(alpha,
ClickGuiStyle.COLOR_ACCENT_RGB));
}
if (selected) {
float barHeight = Math.max(4.0f, rowHeight - 12.0f);
graphics.fillRoundedRect(rowX + 3,
rowY + (rowHeight - barHeight) / 2.0f,
2.5f, barHeight, 1.25f, ClickGuiStyle.COLOR_ACCENT);
}
FontRenderer label = ClickGuiStyle.font(graphics, 10.0f, selected);
label.drawString(ClickGuiModules.displayName(category), rowX + 12,
ClickGuiStyle.centeredY(label, rowY, rowHeight),
selected ? ClickGuiStyle.COLOR_TEXT
: ClickGuiStyle.COLOR_TEXT_DIM);
String count = String.valueOf(counts[category.ordinal()]);
FontRenderer countFont = ClickGuiStyle.font(graphics, 8.0f);
countFont.drawString(count,
rowX + rowWidth - 10 - countFont.getStringWidth(count),
ClickGuiStyle.centeredY(countFont, rowY, rowHeight),
selected ? ClickGuiStyle.COLOR_ACCENT
: ClickGuiStyle.COLOR_TEXT_MUTED);
rowY += rowHeight + ClickGuiStyle.CATEGORY_GAP;
}
}
}
@@ -0,0 +1,51 @@
package cn.xiaozhou233.orangex.ui.clickgui.component;
import cn.xiaozhou233.orangex.event.impl.EventRender2D;
public abstract class Component {
protected float x;
protected float y;
protected float width;
protected float height;
protected boolean visible = true;
protected boolean enabled = true;
public abstract void render(EventRender2D event);
public void update() {
}
public void mouseClicked(float mouseX, float mouseY, int button) {
}
public void mouseReleased(float mouseX, float mouseY, int button) {
}
public void mouseDragged(float mouseX, float mouseY, int button) {
}
public void keyTyped(char character, int keyCode) {
}
public void setBounds(
float x,
float y,
float width,
float height
) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public boolean contains(float mouseX, float mouseY) {
return mouseX >= x
&& mouseX <= x + width
&& mouseY >= y
&& mouseY <= y + height;
}
}
@@ -17,6 +17,8 @@ import java.util.function.Supplier;
*/
public abstract class Value<T> {
private static volatile Runnable globalChangeHook;
private final String name;
private final T defaultValue;
@@ -47,11 +49,26 @@ public abstract class Value<T> {
return;
}
this.value = newValue;
if (changeListener != null) {
changeListener.accept(newValue);
try {
if (changeListener != null) {
changeListener.accept(newValue);
}
} finally {
Runnable hook = globalChangeHook;
if (hook != null) {
hook.run();
}
}
}
/**
* Registers a process-wide callback invoked whenever any value changes.
* Used by the config manager to track unsaved changes.
*/
public static void setGlobalChangeHook(Runnable hook) {
globalChangeHook = hook;
}
public T getDefaultValue() {
return defaultValue;
}
@@ -3,6 +3,8 @@ package cn.xiaozhou233.orangex.wrapper;
import cn.xiaozhou233.orangex.mapping.MappingResolver;
import cn.xiaozhou233.orangex.runtime.RuntimeInfo;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.Player;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import cn.xiaozhou233.orangex.wrapper.internal.WrapperContext;
import cn.xiaozhou233.orangex.wrapper.internal.WrapperRegistry;
@@ -19,6 +21,28 @@ public final class MinecraftFactory {
new WrapperContext(runtimeInfo, mappingResolver));
}
/**
* Creates the world/camera view that goes with an already created
* {@link Minecraft} wrapper.
*/
public static WorldView createWorld(RuntimeInfo runtimeInfo,
MappingResolver mappingResolver,
Minecraft minecraft) {
return WrapperRegistry.createWorld(
new WrapperContext(runtimeInfo, mappingResolver), minecraft);
}
/**
* Creates the local-player view that goes with an already created
* {@link Minecraft} wrapper.
*/
public static Player createPlayer(RuntimeInfo runtimeInfo,
MappingResolver mappingResolver,
Minecraft minecraft) {
return WrapperRegistry.createPlayer(
new WrapperContext(runtimeInfo, mappingResolver), minecraft);
}
private MinecraftFactory() {
}
}
@@ -0,0 +1,23 @@
package cn.xiaozhou233.orangex.wrapper.api;
/**
* Cross-version view of the local player.
*
* <p>Only capabilities that need version-specific reflection live here. The
* implementation reads the current player from the client on every call, so a
* wrapper instance survives world changes and reconnects.</p>
*/
public interface Player {
/**
* Clears the client-side jump cooldown.
*
* <p>Vanilla only starts a new jump when the local jump timer has run out,
* which is why holding the jump key produces a fixed jump interval. Zeroing
* the timer every tick removes that interval; the server still receives
* normal jump packets, so this is a client-side timing change only.</p>
*
* <p>Does nothing while no world/player is loaded.</p>
*/
void clearJumpDelay();
}
@@ -0,0 +1,36 @@
package cn.xiaozhou233.orangex.wrapper.api;
import cn.xiaozhou233.orangex.wrapper.common.WorldSnapshot;
/**
* Cross-version view of the rendered world: camera state and nearby entities.
*
* <p>Implementations read the game every time {@link #snapshot()} is called,
* so the result must only be used for the frame that produced it. Feature
* code (ESP, tracers, ...) should depend on this interface and on the
* {@code wrapper.common} value objects only. The snapshot is intentionally
* unfiltered; features decide which entity kinds they want to use.</p>
*/
public interface WorldView {
/**
* Captures the camera and entity list for the current frame.
*
* @param partialTicks the partial tick the game rendered this frame with,
* taken from {@code EventRender2D}. This is the only
* value that keeps projections aligned with the
* rendered world; {@link Float#NaN} lets the
* implementation resolve one itself.
* @return {@code null} while no level is loaded (title screen, loading).
*/
WorldSnapshot snapshot(float partialTicks);
/**
* @return whether a caller-supplied frame partial tick can be used. NaN and
* out-of-range values are rejected so a misbehaving hook never
* freezes entity interpolation.
*/
static boolean isUsablePartialTick(float partialTicks) {
return partialTicks >= 0.0F && partialTicks <= 1.0F;
}
}
@@ -0,0 +1,37 @@
package cn.xiaozhou233.orangex.wrapper.common;
/**
* Version-independent classification of an entity target.
*
* <p>The wrapper only reports what the game considers the entity to be;
* feature code decides which kinds it wants to render.</p>
*/
public enum EntityKind {
/**
* A player. Use {@link EntityTarget#isLocalPlayer()} to tell the local
* player apart from everyone else.
*/
PLAYER,
/**
* Hostile mobs such as zombies, skeletons, slimes and ghasts.
*/
MONSTER,
/**
* Passive creatures: animals, ambient creatures (bats), water creatures
* and golems.
*/
ANIMAL,
/**
* Villagers and wandering traders.
*/
VILLAGER,
/**
* Anything else: items, projectiles, paintings, experience orbs, ...
*/
OTHER
}
@@ -0,0 +1,104 @@
package cn.xiaozhou233.orangex.wrapper.common;
/**
* Version-independent snapshot of one entity that feature code can render
* (for example an ESP target).
*/
public final class EntityTarget {
private final String name;
private final Vec3 position;
private final double width;
private final double height;
private final float health;
private final float maxHealth;
private final double distance;
private final EntityKind kind;
private final boolean localPlayer;
private final boolean invisible;
public EntityTarget(String name,
Vec3 position,
double width,
double height,
float health,
float maxHealth,
double distance,
EntityKind kind,
boolean localPlayer,
boolean invisible) {
this.name = name;
this.position = position;
this.width = width;
this.height = height;
this.health = health;
this.maxHealth = maxHealth;
this.distance = distance;
this.kind = kind;
this.localPlayer = localPlayer;
this.invisible = invisible;
}
public String getName() {
return name;
}
/**
* Interpolated feet position of the entity.
*/
public Vec3 getPosition() {
return position;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
public float getHealth() {
return health;
}
public float getMaxHealth() {
return maxHealth;
}
/**
* Distance between the entity feet and the camera.
*/
public double getDistance() {
return distance;
}
public EntityKind getKind() {
return kind;
}
/**
* {@code true} when this target is the entity the camera belongs to.
*/
public boolean isLocalPlayer() {
return localPlayer;
}
/**
* {@code true} when the game reports the entity as invisible (invisibility
* potion, spectator, invisible armor stands, ...).
*/
public boolean isInvisible() {
return invisible;
}
@Override
public String toString() {
return "EntityTarget{name='" + name + "', kind=" + kind
+ ", localPlayer=" + localPlayer
+ ", invisible=" + invisible
+ ", position=" + position
+ ", health=" + health + "/" + maxHealth
+ ", distance=" + distance + "}";
}
}
@@ -0,0 +1,81 @@
package cn.xiaozhou233.orangex.wrapper.common;
/**
* Camera-independent perspective projection.
*
* <p>Minecraft treats the perspective FOV as a <em>vertical</em> angle in
* degrees and uses a conventional right-handed view: yaw {@code 0} looks
* towards {@code +Z}, positive yaw turns towards {@code -X}, and positive
* pitch looks down. Both the 1.8.9 and the modern clients share these
* conventions, so the same math works on every version.</p>
*/
public final class Projection {
/**
* Points closer than this are treated as behind the camera. It matches the
* near plane Minecraft uses for its perspective projection.
*/
private static final double NEAR_PLANE = 0.05D;
private static final float DEFAULT_FOV = 70.0F;
public static ScreenPoint project(Vec3 camera,
float yawDegrees,
float pitchDegrees,
float fovDegrees,
int screenWidth,
int screenHeight,
Vec3 point) {
if (camera == null || point == null
|| screenWidth <= 0 || screenHeight <= 0) {
return ScreenPoint.behind();
}
double yaw = Math.toRadians(yawDegrees);
double pitch = Math.toRadians(pitchDegrees);
double sinYaw = Math.sin(yaw);
double cosYaw = Math.cos(yaw);
double sinPitch = Math.sin(pitch);
double cosPitch = Math.cos(pitch);
// Camera basis (camera looks along -forward, forwards is +Z at yaw 0).
double forwardX = -sinYaw * cosPitch;
double forwardY = -sinPitch;
double forwardZ = cosYaw * cosPitch;
double rightX = -cosYaw;
double rightZ = -sinYaw;
double upX = -sinYaw * sinPitch;
double upY = cosPitch;
double upZ = cosYaw * sinPitch;
double dx = point.getX() - camera.getX();
double dy = point.getY() - camera.getY();
double dz = point.getZ() - camera.getZ();
double depth = dx * forwardX + dy * forwardY + dz * forwardZ;
if (depth <= NEAR_PLANE) {
return ScreenPoint.behind();
}
double x = dx * rightX + dz * rightZ;
double y = dx * upX + dy * upY + dz * upZ;
float fov = fovDegrees > 1.0F ? fovDegrees : DEFAULT_FOV;
double tanHalfFov = Math.tan(Math.toRadians(fov) * 0.5D);
double aspect = (double) screenWidth / (double) screenHeight;
double ndcX = x / (depth * tanHalfFov * aspect);
double ndcY = y / (depth * tanHalfFov);
double screenX = (ndcX + 1.0D) * 0.5D * screenWidth;
double screenY = (1.0D - ndcY) * 0.5D * screenHeight;
return new ScreenPoint(screenX, screenY, depth, true);
}
private Projection() {
}
}
@@ -0,0 +1,51 @@
package cn.xiaozhou233.orangex.wrapper.common;
/**
* A world position projected into 2D GUI pixel space.
*
* <p>{@link #isVisible()} is {@code false} when the point is behind the
* camera (or outside the near plane); callers must not draw such a point.</p>
*/
public final class ScreenPoint {
private final double x;
private final double y;
private final double depth;
private final boolean visible;
public ScreenPoint(double x, double y, double depth, boolean visible) {
this.x = x;
this.y = y;
this.depth = depth;
this.visible = visible;
}
public static ScreenPoint behind() {
return new ScreenPoint(0.0D, 0.0D, -1.0D, false);
}
public double getX() {
return x;
}
public double getY() {
return y;
}
/**
* Distance along the camera forward axis.
*/
public double getDepth() {
return depth;
}
public boolean isVisible() {
return visible;
}
@Override
public String toString() {
return "ScreenPoint{x=" + x + ", y=" + y + ", depth=" + depth
+ ", visible=" + visible + "}";
}
}
@@ -0,0 +1,62 @@
package cn.xiaozhou233.orangex.wrapper.common;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* One frame of world data: camera state plus the entity list.
*
* <p>Snapshots are immutable and are produced on the render thread, so the
* partial tick is read only once and every position in this object belongs to
* the same frame. Entries are not filtered by gameplay rules.</p>
*/
public final class WorldSnapshot {
private final Vec3 cameraPosition;
private final float cameraYaw;
private final float cameraPitch;
private final float fieldOfView;
private final List<EntityTarget> targets;
public WorldSnapshot(Vec3 cameraPosition,
float cameraYaw,
float cameraPitch,
float fieldOfView,
List<EntityTarget> targets) {
this.cameraPosition = cameraPosition;
this.cameraYaw = cameraYaw;
this.cameraPitch = cameraPitch;
this.fieldOfView = fieldOfView;
this.targets = Collections.unmodifiableList(
new ArrayList<EntityTarget>(targets));
}
public Vec3 getCameraPosition() {
return cameraPosition;
}
public float getCameraYaw() {
return cameraYaw;
}
public float getCameraPitch() {
return cameraPitch;
}
/**
* Vertical field of view in degrees.
*/
public float getFieldOfView() {
return fieldOfView;
}
public List<EntityTarget> getTargets() {
return targets;
}
public ScreenPoint project(Vec3 worldPoint, int screenWidth, int screenHeight) {
return Projection.project(cameraPosition, cameraYaw, cameraPitch,
fieldOfView, screenWidth, screenHeight, worldPoint);
}
}
@@ -0,0 +1,165 @@
package cn.xiaozhou233.orangex.wrapper.internal;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* Reflective lookup helpers shared by the version-specific wrappers.
*
* <p>This class intentionally knows nothing about Minecraft: version packages
* pass the resolved member names in. Lookups walk the class hierarchy because
* Minecraft frequently declares a member on a base class and stores an
* instance of a subclass.</p>
*/
public final class ReflectionSupport {
public static Field findField(Class<?> type, String name) {
if (type == null || name == null) {
return null;
}
for (Class<?> current = type; current != null; current = current.getSuperclass()) {
try {
Field field = current.getDeclaredField(name);
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
field.setAccessible(true);
return field;
} catch (NoSuchFieldException ignored) {
// Keep walking the superclass chain.
}
}
return null;
}
public static Field requireField(Class<?> type, String name, String ownerName) {
Field field = findField(type, name);
if (field == null) {
throw new IllegalStateException(
"Cannot find field '" + name + "' on " + ownerName);
}
return field;
}
public static Method findMethod(Class<?> type,
String name,
Class<?> returnType,
Class<?>... parameterTypes) {
if (type == null || name == null) {
return null;
}
for (Class<?> current = type; current != null; current = current.getSuperclass()) {
Method[] methods = current.getDeclaredMethods();
for (Method method : methods) {
if (!method.getName().equals(name)
|| Modifier.isStatic(method.getModifiers())
|| !sameParameters(method, parameterTypes)) {
continue;
}
if (returnType != null && !returnType.equals(method.getReturnType())) {
continue;
}
method.setAccessible(true);
return method;
}
}
return null;
}
public static Method requireMethod(Class<?> type,
String name,
Class<?> returnType,
String ownerName,
Class<?>... parameterTypes) {
Method method = findMethod(type, name, returnType, parameterTypes);
if (method == null) {
throw new IllegalStateException(
"Cannot find method '" + name + "' on " + ownerName);
}
return method;
}
public static Object get(Field field, Object target) {
try {
return field.get(target);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Cannot read field '" + field.getName() + "'", e);
}
}
public static double getDouble(Field field, Object target) {
try {
return field.getDouble(target);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Cannot read field '" + field.getName() + "'", e);
}
}
public static float getFloat(Field field, Object target) {
try {
return field.getFloat(target);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Cannot read field '" + field.getName() + "'", e);
}
}
public static int getInt(Field field, Object target) {
try {
return field.getInt(target);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Cannot read field '" + field.getName() + "'", e);
}
}
public static void setInt(Field field, Object target, int value) {
try {
field.setInt(target, value);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Cannot write field '" + field.getName() + "'", e);
}
}
public static boolean getBoolean(Field field, Object target) {
try {
return field.getBoolean(target);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
"Cannot read field '" + field.getName() + "'", e);
}
}
public static Object invoke(Method method, Object target, Object... arguments) {
try {
return method.invoke(target, arguments);
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(
"Cannot invoke method '" + method.getName() + "'", e);
}
}
private static boolean sameParameters(Method method, Class<?>[] parameterTypes) {
Class<?>[] actual = method.getParameterTypes();
if (actual.length != parameterTypes.length) {
return false;
}
for (int i = 0; i < actual.length; i++) {
if (!actual[i].equals(parameterTypes[i])) {
return false;
}
}
return true;
}
private ReflectionSupport() {
}
}
@@ -1,6 +1,8 @@
package cn.xiaozhou233.orangex.wrapper.internal;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.Player;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
/**
* Creates the wrappers for one Minecraft version.
@@ -18,4 +20,14 @@ public interface WrapperProvider {
* Creates the wrapper for {@code net.minecraft.client.Minecraft}.
*/
Minecraft createMinecraft(WrapperContext context);
/**
* Creates the world/camera view backed by the given client instance.
*/
WorldView createWorld(WrapperContext context, Minecraft minecraft);
/**
* Creates the local-player view backed by the given client instance.
*/
Player createPlayer(WrapperContext context, Minecraft minecraft);
}
@@ -2,6 +2,8 @@ package cn.xiaozhou233.orangex.wrapper.internal;
import cn.xiaozhou233.orangex.runtime.version.MinecraftVersion;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.Player;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import cn.xiaozhou233.orangex.wrapper.internal.v1_8_9.V1_8_9WrapperProvider;
import cn.xiaozhou233.orangex.wrapper.internal.v26_2.V26_2WrapperProvider;
@@ -45,6 +47,18 @@ public final class WrapperRegistry {
}
public static Minecraft createMinecraft(WrapperContext context) {
return provider(context).createMinecraft(context);
}
public static WorldView createWorld(WrapperContext context, Minecraft minecraft) {
return provider(context).createWorld(context, minecraft);
}
public static Player createPlayer(WrapperContext context, Minecraft minecraft) {
return provider(context).createPlayer(context, minecraft);
}
private static WrapperProvider provider(WrapperContext context) {
MinecraftVersion version = context.getRuntimeInfo().getMinecraftVersion();
WrapperProvider provider = PROVIDERS.get(version);
@@ -53,7 +67,7 @@ public final class WrapperRegistry {
"Unsupported Minecraft version: " + version);
}
return provider.createMinecraft(context);
return provider;
}
private WrapperRegistry() {
@@ -0,0 +1,82 @@
package cn.xiaozhou233.orangex.wrapper.internal.v1_8_9;
import cn.xiaozhou233.orangex.mapping.MappingClass;
import cn.xiaozhou233.orangex.mapping.MappingField;
import cn.xiaozhou233.orangex.mapping.MappingResolver;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.Player;
import cn.xiaozhou233.orangex.wrapper.internal.ReflectionSupport;
import java.lang.reflect.Field;
/**
* 1.8.9 implementation of {@link Player}.
*
* <p>The jump cooldown is {@code EntityLivingBase#jumpTicks}: vanilla sets it
* to 10 after a jump and only allows the next jump once it reaches 0. Setting
* it to 0 every tick removes the cooldown.</p>
*/
public final class V1_8_9Player implements Player {
private static final String MINECRAFT = "net/minecraft/client/Minecraft";
private static final String ENTITY_LIVING = "net/minecraft/entity/EntityLivingBase";
private static final String PLAYER_FIELD = "thePlayer";
private static final String JUMP_DELAY_FIELD = "jumpTicks";
private final Object minecraft;
private final Field playerField;
private final String jumpDelayFieldName;
private Field jumpDelayField;
public V1_8_9Player(MappingResolver resolver, Minecraft minecraft) {
this.minecraft = minecraft.getMinecraft();
MappingClass minecraftMapping = resolver.mapClass(MINECRAFT);
this.playerField = resolveField(
minecraftMapping, PLAYER_FIELD, this.minecraft.getClass());
this.jumpDelayFieldName = fieldName(
resolver.mapClass(ENTITY_LIVING), JUMP_DELAY_FIELD);
}
@Override
public void clearJumpDelay() {
Object localPlayer = ReflectionSupport.get(playerField, minecraft);
if (localPlayer == null) {
return;
}
// The player class is stable for the process, but the player instance
// is not, so only the field lookup is cached.
if (jumpDelayField == null) {
jumpDelayField = ReflectionSupport.requireField(
localPlayer.getClass(), jumpDelayFieldName, ENTITY_LIVING);
}
ReflectionSupport.setInt(jumpDelayField, localPlayer, 0);
}
private static Field resolveField(MappingClass owner,
String name,
Class<?> runtimeOwner) {
MappingField mapping = owner.getField(name);
if (mapping == null) {
throw new IllegalStateException(
"No mapping for field '" + name + "' on "
+ owner.getSourceName());
}
return ReflectionSupport.requireField(
runtimeOwner, mapping.getTargetName(), owner.getSourceName());
}
private static String fieldName(MappingClass owner, String name) {
MappingField mapping = owner.getField(name);
if (mapping == null) {
throw new IllegalStateException(
"No mapping for field '" + name + "' on "
+ owner.getSourceName());
}
return mapping.getTargetName();
}
}
@@ -0,0 +1,569 @@
package cn.xiaozhou233.orangex.wrapper.internal.v1_8_9;
import cn.xiaozhou233.orangex.mapping.MappingClass;
import cn.xiaozhou233.orangex.mapping.MappingField;
import cn.xiaozhou233.orangex.mapping.MappingMethod;
import cn.xiaozhou233.orangex.mapping.MappingResolver;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import cn.xiaozhou233.orangex.wrapper.common.EntityKind;
import cn.xiaozhou233.orangex.wrapper.common.EntityTarget;
import cn.xiaozhou233.orangex.wrapper.common.Vec3;
import cn.xiaozhou233.orangex.wrapper.common.WorldSnapshot;
import cn.xiaozhou233.orangex.wrapper.internal.ReflectionSupport;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 1.8.9 implementation of {@link WorldView}.
*
* <p>All names below are MCP (named) names and are translated through the
* active {@link MappingResolver}. The camera math mirrors
* {@code EntityRenderer#orientCamera}: the eye position of the render view
* entity plus an optional third-person offset along the camera forward
* vector.</p>
*/
public final class V1_8_9WorldView implements WorldView {
private static final String MINECRAFT = "net/minecraft/client/Minecraft";
private static final String GAME_SETTINGS = "net/minecraft/client/settings/GameSettings";
private static final String TIMER = "net/minecraft/util/Timer";
private static final String WORLD = "net/minecraft/world/World";
private static final String ENTITY = "net/minecraft/entity/Entity";
private static final String ENTITY_LIVING = "net/minecraft/entity/EntityLivingBase";
private static final String ENTITY_PLAYER = "net/minecraft/entity/player/EntityPlayer";
private static final String ENTITY_MONSTER = "net/minecraft/entity/monster/IMob";
private static final String ENTITY_ANIMAL = "net/minecraft/entity/passive/EntityAnimal";
private static final String ENTITY_AMBIENT = "net/minecraft/entity/passive/EntityAmbientCreature";
private static final String ENTITY_WATER = "net/minecraft/entity/passive/EntityWaterMob";
private static final String ENTITY_GOLEM = "net/minecraft/entity/monster/EntityGolem";
private static final String ENTITY_VILLAGER = "net/minecraft/entity/passive/EntityVillager";
private static final String ENTITY_RENDERER = "net/minecraft/client/renderer/EntityRenderer";
private static final float DEFAULT_FOV = 70.0F;
private static final float DEFAULT_THIRD_PERSON_DISTANCE = 4.0F;
private static final double FIRST_PERSON_OFFSET = 0.1D;
private final MappingResolver resolver;
private final Object minecraft;
private final Field worldField;
private final Field playerField;
private final Field viewEntityField;
private final Field timerField;
private final Field gameSettingsField;
private final Field entityRendererField;
private final String partialTicksName;
private final String loadedEntitiesName;
private final String thirdPersonViewName;
private final String fovSettingName;
private final String fovModifierMethodName;
private final String thirdPersonDistanceName;
private final String thirdPersonDistanceTempName;
private final String[] playerClassNames;
private final String[] monsterClassNames;
private final String[] animalClassNames;
private final String[] villagerClassNames;
private Field partialTicksField;
private boolean partialTicksWarningLogged;
private Field loadedEntitiesField;
private Field thirdPersonViewField;
private Field fovSettingField;
private Field thirdPersonDistanceField;
private Field thirdPersonDistanceTempField;
private Method fovModifierMethod;
private boolean optionalCameraFieldsResolved;
private final Map<Class<?>, EntityAccess> accessCache =
new HashMap<Class<?>, EntityAccess>();
public V1_8_9WorldView(MappingResolver resolver, Minecraft minecraft) {
this.resolver = resolver;
this.minecraft = minecraft.getMinecraft();
Class<?> minecraftClass = this.minecraft.getClass();
MappingClass minecraftMapping = resolver.mapClass(MINECRAFT);
this.worldField = resolveField(minecraftMapping, "theWorld", minecraftClass);
this.playerField = resolveField(minecraftMapping, "thePlayer", minecraftClass);
this.viewEntityField = resolveField(minecraftMapping, "renderViewEntity", minecraftClass);
this.timerField = resolveField(minecraftMapping, "timer", minecraftClass);
this.gameSettingsField = resolveField(minecraftMapping, "gameSettings", minecraftClass);
this.entityRendererField = resolveField(minecraftMapping, "entityRenderer", minecraftClass);
this.partialTicksName = fieldName(TIMER, "renderPartialTicks");
this.loadedEntitiesName = fieldName(WORLD, "loadedEntityList");
this.thirdPersonViewName = fieldName(GAME_SETTINGS, "thirdPersonView");
this.fovSettingName = fieldName(GAME_SETTINGS, "fovSetting");
this.fovModifierMethodName = methodName(
ENTITY_RENDERER, "getFOVModifier", "(FZ)F");
this.thirdPersonDistanceName = optionalFieldName(
ENTITY_RENDERER, "thirdPersonDistance");
this.thirdPersonDistanceTempName = optionalFieldName(
ENTITY_RENDERER, "thirdPersonDistanceTemp");
this.playerClassNames = classNames(ENTITY_PLAYER);
this.monsterClassNames = classNames(ENTITY_MONSTER);
this.animalClassNames = classNames(
ENTITY_ANIMAL, ENTITY_AMBIENT, ENTITY_WATER, ENTITY_GOLEM);
this.villagerClassNames = classNames(ENTITY_VILLAGER);
}
@Override
public WorldSnapshot snapshot(float partialTicks) {
Object world = ReflectionSupport.get(worldField, minecraft);
Object viewEntity = ReflectionSupport.get(viewEntityField, minecraft);
Object localPlayer = ReflectionSupport.get(playerField, minecraft);
if (world == null || viewEntity == null) {
return null;
}
// The render hook hands us the exact value the frame was rendered
// with. Only fall back to the timer when the caller has none, because a
// partial tick of 0 (or a stale one) makes every interpolated position
// advance in 20 Hz steps while the world renders smoothly.
float frameTicks = WorldView.isUsablePartialTick(partialTicks)
? partialTicks : partialTicks();
EntityAccess view = accessFor(viewEntity.getClass());
double eyeX = interpolate(view.posX, view.lastTickPosX, viewEntity, frameTicks);
double eyeY = interpolate(view.posY, view.lastTickPosY, viewEntity, frameTicks)
+ invokeFloat(view.eyeHeight, viewEntity);
double eyeZ = interpolate(view.posZ, view.lastTickPosZ, viewEntity, frameTicks);
float yaw = interpolateAngle(view.rotationYaw, view.prevRotationYaw,
viewEntity, frameTicks);
float pitch = interpolateAngle(view.rotationPitch, view.prevRotationPitch,
viewEntity, frameTicks);
int thirdPerson = thirdPersonView();
float cameraYaw = yaw;
float cameraPitch = pitch;
if (thirdPerson == 2) {
// Front view: the camera sits in front of the player and looks
// back, so both axes are mirrored.
cameraYaw = yaw + 180.0F;
cameraPitch = -pitch;
}
// Third person moves the camera back by the configured distance;
// first person sits 0.1 blocks behind the eye (EntityRenderer).
double cameraOffset = thirdPerson > 0
? thirdPersonDistance(frameTicks)
: FIRST_PERSON_OFFSET;
double yawRadians = Math.toRadians(cameraYaw);
double pitchRadians = Math.toRadians(cameraPitch);
double forwardX = -Math.sin(yawRadians) * Math.cos(pitchRadians);
double forwardY = -Math.sin(pitchRadians);
double forwardZ = Math.cos(yawRadians) * Math.cos(pitchRadians);
double cameraX = eyeX - forwardX * cameraOffset;
double cameraY = eyeY - forwardY * cameraOffset;
double cameraZ = eyeZ - forwardZ * cameraOffset;
float fov = fieldOfView(frameTicks);
List<EntityTarget> targets = collectTargets(
world, localPlayer, cameraX, cameraY, cameraZ, frameTicks);
return new WorldSnapshot(new Vec3(cameraX, cameraY, cameraZ),
cameraYaw, cameraPitch, fov, targets);
}
/**
* Captures every entity in the loaded entity list. No gameplay filtering
* happens here: feature code (for example the ESP module) decides which
* kinds it wants to show.
*/
private List<EntityTarget> collectTargets(Object world,
Object localPlayer,
double cameraX,
double cameraY,
double cameraZ,
float partialTicks) {
List<EntityTarget> targets = new ArrayList<EntityTarget>();
Field entitiesField = loadedEntitiesField(world.getClass());
if (entitiesField == null) {
return targets;
}
Object value = ReflectionSupport.get(entitiesField, world);
if (!(value instanceof List)) {
return targets;
}
for (Object entity : (List<?>) value) {
if (entity == null) {
continue;
}
EntityAccess access = accessFor(entity.getClass());
double x = interpolate(access.posX, access.lastTickPosX, entity, partialTicks);
double y = interpolate(access.posY, access.lastTickPosY, entity, partialTicks);
double z = interpolate(access.posZ, access.lastTickPosZ, entity, partialTicks);
double width = access.width == null ? 0.6D
: ReflectionSupport.getFloat(access.width, entity);
double height = access.height == null ? 1.8D
: ReflectionSupport.getFloat(access.height, entity);
double distance = distance(cameraX, cameraY, cameraZ, x, y, z);
boolean local = entity == localPlayer;
targets.add(new EntityTarget(
String.valueOf(ReflectionSupport.invoke(access.getName, entity)),
new Vec3(x, y, z),
width,
height,
access.getHealth == null ? 0.0F : invokeFloat(access.getHealth, entity),
access.getMaxHealth == null ? 0.0F : invokeFloat(access.getMaxHealth, entity),
distance,
classify(entity.getClass()),
local,
invokeBoolean(access.isInvisible, entity)));
}
return targets;
}
private EntityKind classify(Class<?> entityClass) {
if (matches(entityClass, playerClassNames)) {
return EntityKind.PLAYER;
}
if (matches(entityClass, villagerClassNames)) {
return EntityKind.VILLAGER;
}
if (matches(entityClass, monsterClassNames)) {
return EntityKind.MONSTER;
}
if (matches(entityClass, animalClassNames)) {
return EntityKind.ANIMAL;
}
return EntityKind.OTHER;
}
/**
* Checks the runtime class hierarchy (including interfaces) against a set
* of mapped class names. This avoids loading optional entity classes that
* may not exist on every runtime.
*/
private static boolean matches(Class<?> type, String[] classNames) {
if (type == null) {
return false;
}
String name = type.getName();
for (String className : classNames) {
if (name.equals(className)) {
return true;
}
}
for (Class<?> implemented : type.getInterfaces()) {
if (matches(implemented, classNames)) {
return true;
}
}
return matches(type.getSuperclass(), classNames);
}
private String[] classNames(String... sourceNames) {
String[] names = new String[sourceNames.length];
for (int index = 0; index < sourceNames.length; index++) {
names[index] = resolver.mapClass(sourceNames[index])
.getTargetName().replace('/', '.');
}
return names;
}
private float partialTicks() {
Object timer = ReflectionSupport.get(timerField, minecraft);
if (timer == null) {
return 0.0F;
}
if (partialTicksField == null) {
partialTicksField = ReflectionSupport.findField(
timer.getClass(), partialTicksName);
if (partialTicksField == null && !partialTicksWarningLogged) {
partialTicksWarningLogged = true;
System.err.println("[OrangeX] Cannot read "
+ partialTicksName + " from " + timer.getClass().getName()
+ ": world positions will not interpolate");
}
}
return partialTicksField == null
? 0.0F
: ReflectionSupport.getFloat(partialTicksField, timer);
}
private int thirdPersonView() {
Object settings = ReflectionSupport.get(gameSettingsField, minecraft);
if (settings == null) {
return 0;
}
if (thirdPersonViewField == null) {
thirdPersonViewField = ReflectionSupport.findField(
settings.getClass(), thirdPersonViewName);
}
if (thirdPersonViewField == null) {
return 0;
}
// 1.8.9 stores an int (0/1/2); some 1.8 builds use a boolean flag.
if (thirdPersonViewField.getType() == boolean.class) {
return ReflectionSupport.getBoolean(thirdPersonViewField, settings) ? 1 : 0;
}
return ReflectionSupport.getInt(thirdPersonViewField, settings);
}
private float fieldOfView(float partialTicks) {
Object renderer = ReflectionSupport.get(entityRendererField, minecraft);
if (renderer != null && fovModifierMethod == null) {
fovModifierMethod = ReflectionSupport.findMethod(
renderer.getClass(), fovModifierMethodName,
float.class, float.class, boolean.class);
}
if (fovModifierMethod != null) {
return ((Number) ReflectionSupport.invoke(
fovModifierMethod, renderer, partialTicks, Boolean.TRUE))
.floatValue();
}
Object settings = ReflectionSupport.get(gameSettingsField, minecraft);
if (settings != null) {
if (fovSettingField == null) {
fovSettingField = ReflectionSupport.findField(
settings.getClass(), fovSettingName);
}
if (fovSettingField != null) {
return ReflectionSupport.getFloat(fovSettingField, settings);
}
}
return DEFAULT_FOV;
}
private double thirdPersonDistance(float partialTicks) {
Object renderer = ReflectionSupport.get(entityRendererField, minecraft);
if (renderer == null || !resolveOptionalCameraFields(renderer.getClass())) {
return DEFAULT_THIRD_PERSON_DISTANCE;
}
float previous = thirdPersonDistanceTempField == null
? DEFAULT_THIRD_PERSON_DISTANCE
: ReflectionSupport.getFloat(thirdPersonDistanceTempField, renderer);
float current = thirdPersonDistanceField == null
? DEFAULT_THIRD_PERSON_DISTANCE
: ReflectionSupport.getFloat(thirdPersonDistanceField, renderer);
return previous + (current - previous) * partialTicks;
}
private boolean resolveOptionalCameraFields(Class<?> rendererClass) {
if (optionalCameraFieldsResolved) {
return true;
}
optionalCameraFieldsResolved = true;
if (thirdPersonDistanceName != null) {
thirdPersonDistanceField = ReflectionSupport.findField(
rendererClass, thirdPersonDistanceName);
}
if (thirdPersonDistanceTempName != null) {
thirdPersonDistanceTempField = ReflectionSupport.findField(
rendererClass, thirdPersonDistanceTempName);
}
return thirdPersonDistanceField != null
|| thirdPersonDistanceTempField != null;
}
private Field loadedEntitiesField(Class<?> worldClass) {
if (loadedEntitiesField == null) {
loadedEntitiesField = ReflectionSupport.findField(
worldClass, loadedEntitiesName);
}
return loadedEntitiesField;
}
private EntityAccess accessFor(Class<?> entityClass) {
EntityAccess access = accessCache.get(entityClass);
if (access == null) {
access = new EntityAccess(entityClass);
accessCache.put(entityClass, access);
}
return access;
}
private Field resolveField(MappingClass owner, String name, Class<?> runtimeOwner) {
MappingField mapping = owner.getField(name);
if (mapping == null) {
throw new IllegalStateException(
"No mapping for field '" + name + "' on " + owner.getSourceName());
}
return ReflectionSupport.requireField(
runtimeOwner, mapping.getTargetName(), owner.getSourceName());
}
private String fieldName(String ownerClass, String name) {
MappingClass owner = resolver.mapClass(ownerClass);
MappingField mapping = owner.getField(name);
if (mapping == null) {
throw new IllegalStateException(
"No mapping for field '" + name + "' on " + ownerClass);
}
return mapping.getTargetName();
}
private String optionalFieldName(String ownerClass, String name) {
MappingClass owner = resolver.mapClass(ownerClass);
MappingField mapping = owner.getField(name);
return mapping == null ? null : mapping.getTargetName();
}
private String methodName(String ownerClass, String name, String descriptor) {
MappingClass owner = resolver.mapClass(ownerClass);
MappingMethod mapping = owner.getMethod(name, descriptor);
if (mapping == null) {
throw new IllegalStateException(
"No mapping for method '" + name + descriptor + "' on " + ownerClass);
}
return mapping.getTargetName();
}
private String optionalMethodName(String ownerClass, String name, String descriptor) {
MappingClass owner = resolver.mapClass(ownerClass);
MappingMethod mapping = owner.getMethod(name, descriptor);
return mapping == null ? null : mapping.getTargetName();
}
private static double interpolate(Field current, Field previous,
Object entity, float partialTicks) {
double previousValue = ReflectionSupport.getDouble(previous, entity);
double currentValue = ReflectionSupport.getDouble(current, entity);
return previousValue + (currentValue - previousValue) * partialTicks;
}
private static float interpolateAngle(Field current, Field previous,
Object entity, float partialTicks) {
float previousValue = ReflectionSupport.getFloat(previous, entity);
float currentValue = ReflectionSupport.getFloat(current, entity);
return previousValue + (currentValue - previousValue) * partialTicks;
}
private static float invokeFloat(Method method, Object target) {
return ((Number) ReflectionSupport.invoke(method, target)).floatValue();
}
private static boolean invokeBoolean(Method method, Object target) {
return ((Boolean) ReflectionSupport.invoke(method, target)).booleanValue();
}
private static double distance(double x1, double y1, double z1,
double x2, double y2, double z2) {
double dx = x1 - x2;
double dy = y1 - y2;
double dz = z1 - z2;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
/**
* Per-class reflective member cache for entities. Resolving methods on
* every frame for every player would be needlessly slow.
*/
private final class EntityAccess {
private final Field posX;
private final Field posY;
private final Field posZ;
private final Field lastTickPosX;
private final Field lastTickPosY;
private final Field lastTickPosZ;
private final Field width;
private final Field height;
private final Field rotationYaw;
private final Field rotationPitch;
private final Field prevRotationYaw;
private final Field prevRotationPitch;
private final Method eyeHeight;
private final Method getName;
private final Method getHealth;
private final Method getMaxHealth;
private final Method isInvisible;
private EntityAccess(Class<?> entityClass) {
MappingClass entity = resolver.mapClass(ENTITY);
MappingClass living = resolver.mapClass(ENTITY_LIVING);
this.posX = mappedField(entity, "posX", entityClass);
this.posY = mappedField(entity, "posY", entityClass);
this.posZ = mappedField(entity, "posZ", entityClass);
this.lastTickPosX = mappedField(entity, "lastTickPosX", entityClass);
this.lastTickPosY = mappedField(entity, "lastTickPosY", entityClass);
this.lastTickPosZ = mappedField(entity, "lastTickPosZ", entityClass);
this.rotationYaw = mappedField(entity, "rotationYaw", entityClass);
this.rotationPitch = mappedField(entity, "rotationPitch", entityClass);
this.prevRotationYaw = mappedField(entity, "prevRotationYaw", entityClass);
this.prevRotationPitch = mappedField(entity, "prevRotationPitch", entityClass);
this.width = mappedField(entity, "width", entityClass);
this.height = mappedField(entity, "height", entityClass);
this.eyeHeight = mappedMethod(entity, "getEyeHeight", "()F",
float.class, entityClass);
this.getName = mappedMethod(entity, "getName", "()Ljava/lang/String;",
String.class, entityClass);
this.getHealth = optionalMappedMethod(living, "getHealth", "()F",
float.class, entityClass);
this.getMaxHealth = optionalMappedMethod(living, "getMaxHealth", "()F",
float.class, entityClass);
this.isInvisible = mappedMethod(entity, "isInvisible", "()Z",
boolean.class, entityClass);
}
private Field mappedField(MappingClass owner, String name, Class<?> type) {
MappingField mapping = owner.getField(name);
if (mapping == null) {
throw new IllegalStateException("No mapping for field '" + name
+ "' on " + owner.getSourceName());
}
return ReflectionSupport.requireField(
type, mapping.getTargetName(), owner.getSourceName());
}
private Method mappedMethod(MappingClass owner, String name,
String descriptor, Class<?> returnType,
Class<?> type) {
String target = methodName(owner.getSourceName(), name, descriptor);
return ReflectionSupport.requireMethod(type, target, returnType,
owner.getSourceName(), new Class<?>[0]);
}
private Method optionalMappedMethod(MappingClass owner, String name,
String descriptor, Class<?> returnType,
Class<?> type) {
String target = optionalMethodName(owner.getSourceName(), name, descriptor);
if (target == null) {
return null;
}
return ReflectionSupport.findMethod(type, target, returnType,
new Class<?>[0]);
}
}
}
@@ -1,6 +1,8 @@
package cn.xiaozhou233.orangex.wrapper.internal.v1_8_9;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.Player;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import cn.xiaozhou233.orangex.wrapper.internal.WrapperContext;
import cn.xiaozhou233.orangex.wrapper.internal.WrapperProvider;
@@ -15,4 +17,14 @@ public final class V1_8_9WrapperProvider implements WrapperProvider {
context.getRuntimeInfo(),
context.getMappingResolver());
}
@Override
public WorldView createWorld(WrapperContext context, Minecraft minecraft) {
return new V1_8_9WorldView(context.getMappingResolver(), minecraft);
}
@Override
public Player createPlayer(WrapperContext context, Minecraft minecraft) {
return new V1_8_9Player(context.getMappingResolver(), minecraft);
}
}
@@ -0,0 +1,82 @@
package cn.xiaozhou233.orangex.wrapper.internal.v26_2;
import cn.xiaozhou233.orangex.mapping.MappingClass;
import cn.xiaozhou233.orangex.mapping.MappingField;
import cn.xiaozhou233.orangex.mapping.MappingResolver;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.Player;
import cn.xiaozhou233.orangex.wrapper.internal.ReflectionSupport;
import java.lang.reflect.Field;
/**
* 26.2 implementation of {@link Player}.
*
* <p>Modern clients replaced the 1.8 {@code jumpTicks} counter with
* {@code LivingEntity#noJumpDelay}, which is decremented once per tick and
* blocks a new jump while positive. Zeroing it every tick removes the delay.</p>
*/
public final class V26_2Player implements Player {
private static final String MINECRAFT = "net/minecraft/client/Minecraft";
private static final String ENTITY_LIVING = "net/minecraft/world/entity/LivingEntity";
private static final String PLAYER_FIELD = "player";
private static final String JUMP_DELAY_FIELD = "noJumpDelay";
private final Object minecraft;
private final Field playerField;
private final String jumpDelayFieldName;
private Field jumpDelayField;
public V26_2Player(MappingResolver resolver, Minecraft minecraft) {
this.minecraft = minecraft.getMinecraft();
MappingClass minecraftMapping = resolver.mapClass(MINECRAFT);
this.playerField = resolveField(
minecraftMapping, PLAYER_FIELD, this.minecraft.getClass());
this.jumpDelayFieldName = fieldName(
resolver.mapClass(ENTITY_LIVING), JUMP_DELAY_FIELD);
}
@Override
public void clearJumpDelay() {
Object localPlayer = ReflectionSupport.get(playerField, minecraft);
if (localPlayer == null) {
return;
}
// The player class is stable for the process, but the player instance
// is not, so only the field lookup is cached.
if (jumpDelayField == null) {
jumpDelayField = ReflectionSupport.requireField(
localPlayer.getClass(), jumpDelayFieldName, ENTITY_LIVING);
}
ReflectionSupport.setInt(jumpDelayField, localPlayer, 0);
}
private static Field resolveField(MappingClass owner,
String name,
Class<?> runtimeOwner) {
MappingField mapping = owner.getField(name);
if (mapping == null) {
throw new IllegalStateException(
"No mapping for field '" + name + "' on "
+ owner.getSourceName());
}
return ReflectionSupport.requireField(
runtimeOwner, mapping.getTargetName(), owner.getSourceName());
}
private static String fieldName(MappingClass owner, String name) {
MappingField mapping = owner.getField(name);
if (mapping == null) {
throw new IllegalStateException(
"No mapping for field '" + name + "' on "
+ owner.getSourceName());
}
return mapping.getTargetName();
}
}
@@ -0,0 +1,405 @@
package cn.xiaozhou233.orangex.wrapper.internal.v26_2;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import cn.xiaozhou233.orangex.wrapper.common.EntityKind;
import cn.xiaozhou233.orangex.wrapper.common.EntityTarget;
import cn.xiaozhou233.orangex.wrapper.common.Vec3;
import cn.xiaozhou233.orangex.wrapper.common.WorldSnapshot;
import cn.xiaozhou233.orangex.wrapper.internal.ReflectionSupport;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 26.2 implementation of {@link WorldView}.
*
* <p>The modern client already exposes an interpolated camera
* ({@code GameRenderer#mainCamera}) and its FOV, so no third-person math is
* needed here. Member names are the Mojang names the runtime uses.</p>
*/
public final class V26_2WorldView implements WorldView {
private static final float DEFAULT_FOV = 70.0F;
private static final String ENTITY_PLAYER =
"net.minecraft.world.entity.player.Player";
private static final String ENTITY_MONSTER =
"net.minecraft.world.entity.monster.Enemy";
private static final String ENTITY_ANIMAL =
"net.minecraft.world.entity.animal.Animal";
private static final String ENTITY_WATER_ANIMAL =
"net.minecraft.world.entity.animal.fish.WaterAnimal";
private static final String ENTITY_AMBIENT =
"net.minecraft.world.entity.ambient.AmbientCreature";
private static final String ENTITY_GOLEM =
"net.minecraft.world.entity.animal.golem.AbstractGolem";
private static final String ENTITY_VILLAGER =
"net.minecraft.world.entity.npc.villager.AbstractVillager";
private static final String[] PLAYER_CLASSES = {ENTITY_PLAYER};
private static final String[] MONSTER_CLASSES = {ENTITY_MONSTER};
private static final String[] ANIMAL_CLASSES = {
ENTITY_ANIMAL, ENTITY_WATER_ANIMAL, ENTITY_AMBIENT, ENTITY_GOLEM
};
private static final String[] VILLAGER_CLASSES = {ENTITY_VILLAGER};
private final Object minecraft;
private final Field levelField;
private final Field playerField;
private final Field gameRendererField;
private Method deltaTrackerMethod;
private Method deltaPartialTickMethod;
private Method mainCameraMethod;
private Method cameraPositionMethod;
private Method cameraXRotMethod;
private Method cameraYRotMethod;
private Method cameraFovMethod;
private boolean entitySourceResolved;
private Method entitiesForRenderingMethod;
private Method getEntitiesMethod;
private Method getAllMethod;
private Method playersMethod;
private final Map<Class<?>, EntityAccess> accessCache =
new HashMap<Class<?>, EntityAccess>();
private final Map<Class<?>, Field[]> vectorFields =
new HashMap<Class<?>, Field[]>();
public V26_2WorldView(Minecraft minecraft) {
this.minecraft = minecraft.getMinecraft();
Class<?> minecraftClass = this.minecraft.getClass();
this.levelField = ReflectionSupport.requireField(
minecraftClass, "level", "net.minecraft.client.Minecraft");
this.playerField = ReflectionSupport.requireField(
minecraftClass, "player", "net.minecraft.client.Minecraft");
this.gameRendererField = ReflectionSupport.requireField(
minecraftClass, "gameRenderer", "net.minecraft.client.Minecraft");
}
@Override
public WorldSnapshot snapshot(float partialTicks) {
Object level = ReflectionSupport.get(levelField, minecraft);
Object localPlayer = ReflectionSupport.get(playerField, minecraft);
Object gameRenderer = ReflectionSupport.get(gameRendererField, minecraft);
if (level == null || gameRenderer == null) {
return null;
}
Object camera = camera(gameRenderer);
if (camera == null) {
return null;
}
// The 26.2 hook extracts the GUI from the game's delta tracker, so it
// supplies no partial tick and the tracker is the authoritative value.
if (!WorldView.isUsablePartialTick(partialTicks)) {
partialTicks = partialTicks();
}
Vec3 cameraPosition = readVec3(
ReflectionSupport.invoke(cameraPositionMethod, camera));
float yaw = invokeFloat(cameraYRotMethod, camera);
float pitch = invokeFloat(cameraXRotMethod, camera);
float fov = invokeFloat(cameraFovMethod, camera);
List<EntityTarget> targets = collectTargets(
level, localPlayer, cameraPosition, partialTicks);
return new WorldSnapshot(cameraPosition, yaw, pitch,
fov > 1.0F ? fov : DEFAULT_FOV, targets);
}
private Object camera(Object gameRenderer) {
if (mainCameraMethod == null) {
mainCameraMethod = ReflectionSupport.findMethod(
gameRenderer.getClass(), "mainCamera", null);
}
if (mainCameraMethod == null) {
return null;
}
Object camera = ReflectionSupport.invoke(mainCameraMethod, gameRenderer);
if (camera == null) {
return null;
}
Class<?> cameraClass = camera.getClass();
if (cameraPositionMethod == null) {
cameraPositionMethod = ReflectionSupport.requireMethod(
cameraClass, "position", null, "net.minecraft.client.Camera");
cameraXRotMethod = ReflectionSupport.requireMethod(
cameraClass, "xRot", float.class, "net.minecraft.client.Camera");
cameraYRotMethod = ReflectionSupport.requireMethod(
cameraClass, "yRot", float.class, "net.minecraft.client.Camera");
cameraFovMethod = ReflectionSupport.requireMethod(
cameraClass, "getFov", float.class, "net.minecraft.client.Camera");
}
return camera;
}
/**
* Captures every entity the level exposes for rendering. No gameplay
* filtering happens here: feature code (for example the ESP module)
* decides which kinds it wants to show.
*/
private List<EntityTarget> collectTargets(Object level,
Object localPlayer,
Vec3 cameraPosition,
float partialTicks) {
List<EntityTarget> targets = new ArrayList<EntityTarget>();
Iterable<?> entities = entities(level);
if (entities == null) {
return targets;
}
for (Object entity : entities) {
if (entity == null) {
continue;
}
EntityAccess access = accessFor(entity.getClass());
Vec3 position = readVec3(ReflectionSupport.invoke(
access.getPosition, entity, Float.valueOf(partialTicks)));
if (position == null) {
continue;
}
boolean local = entity == localPlayer;
targets.add(new EntityTarget(
invokeString(access.getName, entity),
position,
invokeFloat(access.getBbWidth, entity),
invokeFloat(access.getBbHeight, entity),
access.getHealth == null ? 0.0F : invokeFloat(access.getHealth, entity),
access.getMaxHealth == null ? 0.0F : invokeFloat(access.getMaxHealth, entity),
distance(cameraPosition, position),
classify(entity.getClass()),
local,
invokeBoolean(access.isInvisible, entity)));
}
return targets;
}
/**
* Resolves the all-entity source once. Modern clients expose
* {@code Level#entitiesForRendering()}; older/newer builds may instead
* expose {@code Level#getEntities()#getAll()}. {@code players()} stays as
* a last-resort fallback so the overlay keeps working if the level API
* changes again.
*/
private Iterable<?> entities(Object level) {
if (!entitySourceResolved) {
entitySourceResolved = true;
entitiesForRenderingMethod = ReflectionSupport.findMethod(
level.getClass(), "entitiesForRendering", null);
if (entitiesForRenderingMethod == null) {
getEntitiesMethod = ReflectionSupport.findMethod(
level.getClass(), "getEntities", null);
}
if (entitiesForRenderingMethod == null && getEntitiesMethod == null) {
playersMethod = ReflectionSupport.findMethod(
level.getClass(), "players", null);
}
}
if (entitiesForRenderingMethod != null) {
Object value = ReflectionSupport.invoke(entitiesForRenderingMethod, level);
return value instanceof Iterable ? (Iterable<?>) value : null;
}
if (getEntitiesMethod != null) {
Object getter = ReflectionSupport.invoke(getEntitiesMethod, level);
if (getter == null) {
return null;
}
if (getAllMethod == null) {
getAllMethod = ReflectionSupport.findMethod(
getter.getClass(), "getAll", null);
}
if (getAllMethod != null) {
Object value = ReflectionSupport.invoke(getAllMethod, getter);
return value instanceof Iterable ? (Iterable<?>) value : null;
}
return null;
}
if (playersMethod != null) {
Object value = ReflectionSupport.invoke(playersMethod, level);
return value instanceof Iterable ? (Iterable<?>) value : null;
}
return null;
}
private static EntityKind classify(Class<?> entityClass) {
if (matches(entityClass, PLAYER_CLASSES)) {
return EntityKind.PLAYER;
}
if (matches(entityClass, VILLAGER_CLASSES)) {
return EntityKind.VILLAGER;
}
if (matches(entityClass, MONSTER_CLASSES)) {
return EntityKind.MONSTER;
}
if (matches(entityClass, ANIMAL_CLASSES)) {
return EntityKind.ANIMAL;
}
return EntityKind.OTHER;
}
private static boolean matches(Class<?> type, String[] classNames) {
if (type == null) {
return false;
}
String name = type.getName();
for (String className : classNames) {
if (name.equals(className)) {
return true;
}
}
for (Class<?> implemented : type.getInterfaces()) {
if (matches(implemented, classNames)) {
return true;
}
}
return matches(type.getSuperclass(), classNames);
}
private float partialTicks() {
if (deltaTrackerMethod == null) {
deltaTrackerMethod = ReflectionSupport.findMethod(
minecraft.getClass(), "getDeltaTracker", null);
}
if (deltaTrackerMethod == null) {
return 0.0F;
}
Object tracker = ReflectionSupport.invoke(deltaTrackerMethod, minecraft);
if (tracker == null) {
return 0.0F;
}
if (deltaPartialTickMethod == null) {
deltaPartialTickMethod = ReflectionSupport.findMethod(
tracker.getClass(), "getGameTimeDeltaPartialTick", null,
boolean.class);
}
if (deltaPartialTickMethod == null) {
return 0.0F;
}
return invokeFloat(deltaPartialTickMethod, tracker, Boolean.FALSE);
}
private EntityAccess accessFor(Class<?> entityClass) {
EntityAccess access = accessCache.get(entityClass);
if (access == null) {
access = new EntityAccess(entityClass);
accessCache.put(entityClass, access);
}
return access;
}
private Vec3 readVec3(Object nativeVec) {
if (nativeVec == null) {
return null;
}
Class<?> type = nativeVec.getClass();
Field[] fields = vectorFields.get(type);
if (fields == null) {
fields = new Field[]{
ReflectionSupport.requireField(type, "x", type.getName()),
ReflectionSupport.requireField(type, "y", type.getName()),
ReflectionSupport.requireField(type, "z", type.getName())
};
vectorFields.put(type, fields);
}
return new Vec3(
ReflectionSupport.getDouble(fields[0], nativeVec),
ReflectionSupport.getDouble(fields[1], nativeVec),
ReflectionSupport.getDouble(fields[2], nativeVec));
}
private static String invokeString(Method method, Object target) {
Object value = ReflectionSupport.invoke(method, target);
if (value == null) {
return "";
}
Method getString = ReflectionSupport.findMethod(
value.getClass(), "getString", String.class);
if (getString == null) {
return String.valueOf(value);
}
Object text = ReflectionSupport.invoke(getString, value);
return text == null ? "" : String.valueOf(text);
}
private static float invokeFloat(Method method, Object target, Object... arguments) {
return ((Number) ReflectionSupport.invoke(method, target, arguments))
.floatValue();
}
private static boolean invokeBoolean(Method method, Object target) {
return ((Boolean) ReflectionSupport.invoke(method, target)).booleanValue();
}
private static double distance(Vec3 first, Vec3 second) {
return first.distanceTo(second);
}
/**
* Per-class reflective member cache for entities.
*/
private static final class EntityAccess {
private final Method getPosition;
private final Method getName;
private final Method getHealth;
private final Method getMaxHealth;
private final Method getBbWidth;
private final Method getBbHeight;
private final Method isInvisible;
private EntityAccess(Class<?> entityClass) {
this.getPosition = ReflectionSupport.requireMethod(
entityClass, "getPosition", null, entityClass.getName(),
float.class);
this.getName = ReflectionSupport.requireMethod(
entityClass, "getName", null, entityClass.getName());
// Health only exists on LivingEntity, so non-living entities
// (items, arrows, ...) leave these null.
this.getHealth = ReflectionSupport.findMethod(
entityClass, "getHealth", float.class);
this.getMaxHealth = ReflectionSupport.findMethod(
entityClass, "getMaxHealth", float.class);
this.getBbWidth = ReflectionSupport.requireMethod(
entityClass, "getBbWidth", float.class, entityClass.getName());
this.getBbHeight = ReflectionSupport.requireMethod(
entityClass, "getBbHeight", float.class, entityClass.getName());
this.isInvisible = ReflectionSupport.requireMethod(
entityClass, "isInvisible", boolean.class, entityClass.getName());
}
}
}
@@ -1,6 +1,8 @@
package cn.xiaozhou233.orangex.wrapper.internal.v26_2;
import cn.xiaozhou233.orangex.wrapper.api.Minecraft;
import cn.xiaozhou233.orangex.wrapper.api.Player;
import cn.xiaozhou233.orangex.wrapper.api.WorldView;
import cn.xiaozhou233.orangex.wrapper.internal.WrapperContext;
import cn.xiaozhou233.orangex.wrapper.internal.WrapperProvider;
@@ -12,4 +14,14 @@ public final class V26_2WrapperProvider implements WrapperProvider {
context.getRuntimeInfo(),
context.getMappingResolver());
}
@Override
public WorldView createWorld(WrapperContext context, Minecraft minecraft) {
return new V26_2WorldView(minecraft);
}
@Override
public Player createPlayer(WrapperContext context, Minecraft minecraft) {
return new V26_2Player(context.getMappingResolver(), minecraft);
}
}
@@ -30,6 +30,15 @@ public final class Hooks {
Render2DEvents.fire(context, inWorld);
}
/**
* 1.8.9 entry point: the HUD method receives the frame's partial tick, so
* injected code passes it straight through as {@code $1}.
*/
public static void render2d(Object context, boolean inWorld,
float partialTicks) {
Render2DEvents.fire(context, inWorld, partialTicks);
}
public static void render2d(Object context) {
Render2DEvents.fire(context);
}
@@ -14,6 +14,10 @@ public final class Legacy {
return V1_8_9Input.isRepeatEvent();
}
public static void forwardScroll(Object screen) {
V1_8_9Input.forwardScroll(screen);
}
private Legacy() {
}
}
+160 -7
View File
@@ -1,10 +1,163 @@
# OrangeX Client
## 项目重构中, Legacy版本请移步 [OrangeX-Client-Legacy](https://github.com/xiaozhou233/OrangeX-Client-Legacy)
## Project is being refactored, Legacy version please refer to [OrangeX-Client-Legacy](https://github.com/xiaozhou233/OrangeX-Client-Legacy)
![Banner](docs/img/banner2.png)
## 支持注入的版本
| Minecraft Version | Vanilla | Forge | Fabric | Badlion Client | MCP |
|:-----------------:|:-------:|:-----:|:------:|:--------------:|:---:|
| 1.8.9 | ✓ | ✓ | — | ✓ | ✓ |
| 26.2 | ✓ | ✗ | ✓ | — | — |
> [!WARNING]
> **项目重构中 / Under Refactoring**
>
> 当前 `main` 分支为重构版本,项目架构、API 和功能仍在持续调整中,暂不保证向后兼容。
>
> The `main` branch contains the rewritten client. Its architecture, APIs, and features are still evolving and may change without notice.
>
> 旧版本请访问:[OrangeX-Client-Legacy](https://github.com/xiaozhou233/OrangeX-Client-Legacy)
## 项目介绍 | Introduction
OrangeX Client 是一个面向 Minecraft 的注入式辅助客户端
OrangeX Client is an injection-based Minecraft utility client
## 支持的版本 | Compatibility
以下表格列出了目前已验证的 Minecraft 版本与运行环境组合。
| Minecraft Version | Vanilla | Forge | Fabric | Badlion Client | Lunar Client | MCP |
|:-----------------:|:-------:|:-----:|:------:|:--------------:|:------------:|:---:|
| 1.8.9 | ✓ | ✓ | — | ✓ | ✓ | ✓ |
| 26.2 | ✓ | ✗ | ✓ | — | — | — |
**状态说明:**
- ✓ Supported:已支持并验证
- ✗ Unsupported:已验证不支持
- — N/A / Untested:环境不存在或尚未完成测试
> 兼容性信息仅反映已经验证的组合,不代表其他未列出的环境一定不兼容。
## 下载 | Downloads
### Stable Releases
正式发布版本可从 GitHub Releases 获取:
[OrangeX Client Releases](https://github.com/xiaozhou233/OrangeX-Client/releases)
### Development Builds
开发版本由 Jenkins 自动构建并发布:
[Jenkins - OrangeX Client](https://jenkins.xiaozhou233.cn/job/OrangeX-Client/)
> [!NOTE]
> 开发版本可能包含未完成的功能、实验性接口或尚未修复的问题,不建议在生产环境中使用。
## 构建 | Building
### 环境要求 | Requirements
| 环境 | 要求 |
|---|---|
| Java | 25 |
| Network | 需要网络连接以下载构建依赖 |
| Build Tool | Gradle Wrapper(项目自带) |
### 开始构建 | Build
克隆项目后,在项目根目录执行:
```bash
./gradlew packageAll
```
Windows 环境:
```bat
gradlew.bat packageAll
```
> [!IMPORTANT]
> `build` 任务被有意禁用。请使用 `packageAll` 进行完整构建。
>
> The `build` task is intentionally disabled. Use `packageAll` instead.
### 构建产物 | Artifacts
构建完成后,产物将输出到 `out/` 目录。
| 路径 | 说明 |
|---|---|
| `out/injection.zip` | 完整注入包,包含 Loader、OrangeX、原生 DLL 和配置文件 |
| `out/injector.jar` | 图形化注入器,内置 FlatLaf |
| `out/tmp/` | 打包过程中生成的临时文件 |
首次构建时,Gradle 会自动下载所需依赖并保存到 `libraries/` 目录。
如果依赖下载失败,请检查网络连接及代理配置。
## 使用指南 | Usage
### 1. 获取程序
选择以下任意一种方式获取 OrangeX Client:
- [GitHub Releases](https://github.com/xiaozhou233/OrangeX-Client/releases)
- [Jenkins Development Builds](https://jenkins.xiaozhou233.cn/job/OrangeX-Client/)
- 自行构建,参见 [构建指南](#构建--building)
### 2. 启动注入器
```bash
java -jar injector.jar
```
### 4. 执行注入
在图形化注入器中选择目标 Minecraft 进程,并按照界面提示完成注入。
## 开发指南 | Development
完整开发文档见 [docs/README.md](docs/README.md):模块开发、跨版本 Wrapper、反射与映射、Hook 和渲染。
### 开发环境 | Requirements
| 环境 | 要求 |
|---------|-------------------------------------------|
| Java | 25 |
| IDE | IntelliJ IDEA 2026.2.3 或更高版本(推荐) |
| Git | 用于版本控制 |
| Network | 需要网络连接 |
### 初始化项目 | Setup
**1. 克隆仓库**
```bash
git clone https://github.com/xiaozhou233/OrangeX-Client.git
cd OrangeX-Client
```
**2. 使用 IntelliJ IDEA 打开项目**
等待 Gradle 同步及依赖下载完成。
**3. 准备 Minecraft 开发环境**
加入项目 QQ 群 1103504356,从群文件下载 `Minecraft1.8.8.zip`。
将压缩包解压到`Minecraft1.8.8/`目录,确保目录中有`src/`和`runtime/`
**4. 开始开发**
根据需要修改对应模块的代码。
**5. 运行客户端**
使用 IntelliJ IDEA 中配置好的运行配置启动 Minecraft 客户端。
![Start Client](docs/img/start-client.png)
## 其他 | Others
- 项目仍处于积极重构阶段,部分功能和接口可能发生变化。
- 欢迎提交 Issue 和 Pull Request。
- 使用过程中遇到问题,可以通过项目 Issue 或 QQ 群反馈。
+77
View File
@@ -0,0 +1,77 @@
# OrangeX 开发文档
本文档目录面向继续开发 OrangeX 的开发者,说明各层职责、代码放在哪里,以及新增功能时的完整流程。
## 文档索引
### 版本与运行时
| 文档 | 内容 |
| --- | --- |
| [adding-minecraft-versions.md](adding-minecraft-versions.md) | 如何让 OrangeX 识别新的 Minecraft 版本:版本 ID、结构签名、加载器探测 |
| [adding-wrapper-versions.md](adding-wrapper-versions.md) | 如何为一个已识别的版本实现跨版本 Wrapper |
| [adding-wrapper-capabilities.md](adding-wrapper-capabilities.md) | 如何新增一种跨版本能力(以 `Player` + `NoJumpDelay` 为例) |
| [reflection-and-mappings.md](reflection-and-mappings.md) | 反射、MCP/SRG/混淆名与 `MappingResolver` 的使用规范 |
### 功能开发
| 文档 | 内容 |
| --- | --- |
| [adding-modules.md](adding-modules.md) | 新增模块:注册、事件、Value 设置项、配置持久化 |
| [hooks.md](hooks.md) | 字节码 Hook 架构与新增 Hook 的规则 |
| [hook-on-tick-example.md](hook-on-tick-example.md) | 从零理解 tick 注入与 EventBus 的示例 |
### 渲染
| 文档 | 内容 |
| --- | --- |
| [render/README.md](render/README.md) | 渲染模块总览 |
| [render/gui-rendering.md](render/gui-rendering.md) | GUI 绘制 API |
| [render/font-port.md](render/font-port.md) | 字体后端 |
| [render/world-gating-and-input.md](render/world-gating-and-input.md) | 世界渲染开关与输入处理 |
| [render/vape-font-gui-rendering.md](render/vape-font-gui-rendering.md) | 字体/GUI 渲染实现细节 |
## 推荐阅读顺序
1. [adding-modules.md](adding-modules.md) —— 先能写一个能开关、能保存配置的模块。
2. [reflection-and-mappings.md](reflection-and-mappings.md) —— 理解为什么不能直接写 Minecraft 类名。
3. [adding-wrapper-capabilities.md](adding-wrapper-capabilities.md) —— 当模块需要新的游戏数据时,如何把它做成跨版本能力。
4. [adding-wrapper-versions.md](adding-wrapper-versions.md) —— 需要支持新版本时再读。
5. [hooks.md](hooks.md) —— 只有需要新的游戏内触发点时再读。
## 分层结构
```text
modules/ 功能模块(只依赖 wrapper/api)
└── impl/<category>/ 按分类放置模块
wrapper/api/ 跨版本契约(只依赖 JDK)
wrapper/common/ 与版本无关的值对象
wrapper/internal/ 版本选择逻辑
└── vX_Y_Z/ 唯一允许出现 Minecraft 类名/字段名的地方
event/ EventBus 事件
hook/ 字节码注入
mapping/ 混淆名 -> 运行时名解析
config/ 模块配置持久化
```
## 改动应该放在哪一层
| 需求 | 应该改哪里 |
| --- | --- |
| 新增一个功能(飞行、ESP、自动跳跃……) | `modules/impl/...` + `ModuleManager` 注册 |
| 模块需要读一个新的游戏字段/方法 | 先在 `wrapper/api` 加能力,再在 `wrapper/internal/vX_Y_Z` 实现 |
| 支持新的 Minecraft 版本 | `runtime/version` + `wrapper/internal/vX_Y_Z` |
| 需要新的游戏内触发时机(例如攻击、受伤) | `hook/` 新增 `ClassHook` |
| 新增配置项 | 模块里的 `Value`,会自动进入配置和 ClickGUI |
核心约束:**模块和 `wrapper/api` 中不允许出现 `net.minecraft.*`、SRG 名或混淆名**,版本差异全部收敛在 `wrapper/internal/vX_Y_Z`。
## 构建
```bash
./gradlew :OrangeX:shadowJar
# 或完整打包
./gradlew packageAll
```
`build` 任务被有意禁用,请使用 `shadowJar` / `packageAll`。
+295
View File
@@ -0,0 +1,295 @@
# 添加模块(Module)
本文说明如何新增一个功能模块,包括注册、生命周期、事件订阅、设置项和配置持久化。示例直接使用仓库里的 `NoJumpDelay` 模块。
## 1. 模块在架构中的位置
```text
Module(功能逻辑)
├── Value 设置项,自动进入 ClickGUI 和配置文件
├── EventBus 订阅 模块启用时自动注册,禁用时自动反注册
└── wrapper/api 读取游戏数据(Player / WorldView / Minecraft)
└── wrapper/internal/vX_Y_Z 真正的反射实现
```
模块中**不允许**出现 `net.minecraft.*`、MCP 名、SRG 名或混淆名。需要新的游戏数据时,先按 [adding-wrapper-capabilities.md](adding-wrapper-capabilities.md) 增加 wrapper 能力。
## 2. 最小模块
模块统一放在:
```text
modules/impl/<category>/<ModuleName>.java
```
`NoJumpDelay` 的完整实现:
```java
package cn.xiaozhou233.orangex.modules.impl.movement;
import cn.xiaozhou233.orangex.OrangeX;
import cn.xiaozhou233.orangex.event.impl.EventTickPre;
import cn.xiaozhou233.orangex.modules.Module;
import cn.xiaozhou233.orangex.modules.ModuleCategory;
import cn.xiaozhou233.orangex.wrapper.api.Player;
import org.greenrobot.eventbus.Subscribe;
public class NoJumpDelay extends Module {
public NoJumpDelay() {
super("NoJumpDelay", ModuleCategory.MOVEMENT);
}
@Subscribe
public void onTickPre(EventTickPre event) {
Player player = OrangeX.getInstance().getPlayer();
if (player == null) {
return;
}
player.clearJumpDelay();
}
}
```
要点:
- 构造函数只调用 `super(name, category[, defaultKey])`。此时游戏可能还没初始化,**不要**在构造函数里读世界、玩家或做反射。
- `@Subscribe` 方法必须是 `public`。
- 模块启用时 `Module#setEnabled` 会自动把模块注册到 EventBus,禁用时自动反注册,所以不需要手动注册/注销。
## 3. 注册模块
在 `ModuleManager#registerAll()` 中加一行:
```java
public void registerAll() {
register(new HUD());
register(new ClickGUI());
register(new ESP());
register(new NoJumpDelay());
}
```
`register` 只负责把模块放进列表。模块默认关闭,除非构造函数里显式 `setEnabled(true)`(例如 `HUD`)。
## 4. 生命周期
| 阶段 | 发生什么 |
| --- | --- |
| 构造 | `ModuleManager` 创建实例,只初始化名称、分类、keybind 和 Value |
| 启用 | 注册到 EventBus → 调用 `onEnable()` |
| 禁用 | 从 EventBus 反注册 → 调用 `onDisable()` |
| 按键切换 | `ModuleManager#onKey` 比较 `EventKey#getKey()` 和模块 keybind,然后 `toggle()` |
| 加载配置 | 先恢复 Value,再按 `enabled` 字段调用 `setEnabled(...)` |
| 关闭客户端 | 关闭钩子里 `saveIfDirty()` |
重写 `onEnable()` / `onDisable()` 时必须调用 `super`:
```java
@Override
protected void onEnable() {
super.onEnable();
// 打开界面、发请求、重置状态……
}
@Override
protected void onDisable() {
// 关闭界面、恢复游戏状态……
super.onDisable();
}
```
`onEnable()` 里要假设“玩家可能还没进入世界”。例如 `ClickGUI` 会检查 `mc.isInWorld()` 和 `mc.isScreenOpen()`,条件不满足时立即 `setEnabled(false)`。
## 5. 设置项(Value)
在模块字段上声明即可,`Module` 会自动收集:
```java
public class Example extends Module {
private final BooleanValue showBox = addBoolean("Box", true);
private final BooleanValue fill = addBoolean("Fill", false);
private final ModeValue style = addMode("Style", "Box", "Box", "Corners");
private final ModeValue color = addMode("Color", "Orange", "Orange", "Health", "Rainbow");
public Example() {
super("Example", ModuleCategory.RENDER);
}
}
```
可用类型:
| 类型 | 创建方法 | 常用 API |
| --- | --- | --- |
| `BooleanValue` | `addBoolean(name, default)` | `isEnabled()`、`setEnabled()`、`toggle()` |
| `ModeValue` | `addMode(name, default, modes...)` | `is("Box")`、`getMode()`、`next()`、`previous()`、`getModes()` |
| `KeybindValue` | `addKeybind(name, key)` | `getKey()`、`matches(key)`、`isBound()` |
规则:
- 名称在同一个模块内必须唯一,重复会抛 `IllegalArgumentException`。
- `ModeValue` 的默认值必须出现在模式列表中。
- `KeybindValue` 使用 1.8.9 / LWJGL 2 键码(见 `input/KeyCodes`),26.2 的 GLFW 键码会先转换。
- 模块自身的 keybind 由 `Module` 自动创建,名字固定为 `keybind`。
### 5.1 条件显示
```java
private final ModeValue style = addMode("Style", "Box", "Box", "Corners");
private final BooleanValue corners = addBoolean("Corners", true)
.visibleWhen(() -> style.is("Corners"));
```
`visibleWhen` 只影响 ClickGUI 是否显示,不影响配置读写。
### 5.2 值变化回调
```java
private final BooleanValue enabled = addBoolean("Enabled", true)
.onChange(value -> rebuildCache());
```
`onChange` 只在值真正变化时触发。任何 Value 变化都会自动把配置标记为 dirty,不需要手动保存。
### 5.3 自定义 Value 类型
ClickGUI 目前直接识别 `BooleanValue` 和 `ModeValue`:
- `BooleanValue` 显示开关。
- `ModeValue` 显示 `< 当前值 >`,左键下一个、右键上一个。
- 其他类型在设置页里只读显示 `String.valueOf(value)`。
新增自定义 `Value` 子类时,除了实现 `toJson()` / `fromJson(JsonElement)`,还要修改 `ui/clickgui/SettingsSection.java` 才能交互。绝大多数需求用现有三种类型就够了。
## 6. 配置持久化
配置文件位于:
```text
~/.orangex/configs/<name>.json
```
结构大致如下:
```json
{
"version": 1,
"modules": {
"cn.xiaozhou233.orangex.modules.impl.movement.NoJumpDelay": {
"enabled": true,
"values": {
"keybind": 0
}
}
}
}
```
关键规则:
- 模块以 `getConfigKey()` 为键,默认返回**类全名**。修改显示名不会丢配置;读取时还会兼容旧版用显示名作键的配置。
- 保存内容 = `enabled` + 模块全部 Value(包括 keybind)。
- 启用/禁用模块、修改任意 Value 都会 `markDirty()`。
- 真正落盘发生在:关闭 ClickGUI、切换配置、JVM 关闭钩子。也可以手动调用 `ConfigManager#saveIfDirty()`。
- 反序列化时未知字段会被忽略,非法值(例如不存在的 mode)不会写入,避免坏配置让模块不可用。
- 新增模块后不需要改 `ConfigManager` 或序列化器,`ModuleManager` 里的模块会被自动序列化。
## 7. 事件
模块通过 `@Subscribe` 接收事件。项目统一使用一个 EventBus:`OrangeX.getInstance().getEventBus()`。
| 事件 | 触发时机 | 适合做什么 |
| --- | --- | --- |
| `EventTickPre` | 每个游戏 tick,`Minecraft.runTick` 之前 | 移动、战斗、状态修改 |
| `EventTickPost` | 每个 tick,`runTick` 之后 | 需要读取本 tick 结果的逻辑、延迟操作 |
| `EventRender2D` | GUI 绘制帧 | HUD、ESP、ClickGUI |
| `EventKey` | 键盘按下 | 快捷键、模块切换 |
约定:
- 使用默认的 `ThreadMode.POSTING`,不要用 `ASYNC` / `MAIN`。所有回调都在游戏主线程。
- 事件方法里不要做耗时操作;反射 `Field` / `Method` 要缓存。
- 模块被禁用后不会再收到事件;如果逻辑依赖“禁用时恢复”,写在 `onDisable()` 里。
- `EventRender2D#isInWorld()` 表示当前帧是否在世界中;现代版本在标题界面也会触发渲染事件,不能假设有玩家。
- 投影世界坐标必须使用 `EventRender2D#getPartialTicks()`,不要自己读计时器。
## 8. 读取游戏数据
入口都在 `OrangeX`:
```java
OrangeX client = OrangeX.getInstance();
client.getMinecraft(); // 原生 Minecraft 实例(不透明对象)
client.getPlayer(); // 跨版本本地玩家能力
client.getWorldView(); // 世界/相机快照
```
所有 wrapper 都可能在以下情况返回 `null` 或不可用:
- 还在标题界面、没有进入世界;
- 该版本没有实现对应能力;
- 启动时反射失败(日志会打印 `World wrapper unavailable` / `Player wrapper unavailable`)。
因此每次使用前都要判空。ESP 的写法可以作为参考:
```java
WorldView world = OrangeX.getInstance().getWorldView();
if (world == null) {
return;
}
WorldSnapshot snapshot = world.snapshot(event.getPartialTicks());
```
## 9. NoJumpDelay 的完整调用链
```text
ModuleManager 注册 NoJumpDelay
│
▼
用户开启模块 ── EventBus.register(module)
│
▼
Minecraft.runTick() 前(TickHook 注入)
│ EventTickPre
▼
NoJumpDelay.onTickPre()
│ OrangeX.getInstance().getPlayer()
▼
Player wrapper(V1_8_9Player / V26_2Player)
│ 反射 jumpTicks / noJumpDelay
▼
把冷却计时器清零 → 落地即可再次起跳
```
涉及文件:
```text
modules/impl/movement/NoJumpDelay.java
wrapper/api/Player.java
wrapper/internal/v1_8_9/V1_8_9Player.java
wrapper/internal/v26_2/V26_2Player.java
```
## 10. Checklist
- [ ] 模块放在 `modules/impl/<category>/`,构造函数不访问游戏状态。
- [ ] 在 `ModuleManager#registerAll()` 注册。
- [ ] 需要配置的字段使用 `addBoolean` / `addMode` / `addKeybind`,名称唯一。
- [ ] 依赖玩家/世界时先判空。
- [ ] 不使用 Minecraft 类名、字段名或混淆名;需要新数据先加 wrapper。
- [ ] `onEnable` / `onDisable` 重写时调用了 `super`。
- [ ] `./gradlew :OrangeX:shadowJar` 通过,并在游戏里验证开关、配置保存和重连后的行为。
## 11. 常见问题
| 现象 | 原因 |
| --- | --- |
| 模块不显示在 ClickGUI | 没在 `ModuleManager#registerAll()` 注册,或分类写错 |
| 开关无效 / 事件不触发 | `@Subscribe` 方法不是 `public`,或模块没有真正启用 |
| 启动时 `NullPointerException` | 在构造函数或字段初始化时访问了玩家/世界 |
| 配置重启后丢失 | Value 名称重复导致构造失败,或配置从未触发落盘(关闭 ClickGUI / 正常退出) |
| 设置页看不到某个值 | `visibleWhen` 条件为 false,或该类型不被 ClickGUI 识别 |
| 每帧卡顿 | 在 tick/render 回调里重复做反射查找,改为在 wrapper 构造时缓存 |
+329
View File
@@ -0,0 +1,329 @@
# 添加跨版本 Wrapper 能力
本文说明当模块需要一份新的游戏数据时,如何把它做成跨版本能力。完整示例直接使用本次新增的 `Player` + `NoJumpDelay`。
## 1. 什么时候需要新能力
出现以下情况时,应该新增 wrapper 能力,而不是在模块里直接反射:
- 模块需要读/写一个 Minecraft 字段或方法;
- 这个字段在不同版本/加载器下名字不同;
- 多个模块可能复用同一份数据(玩家、世界、背包、聊天……)。
判断标准:**只要代码里出现 `net.minecraft.*` 或混淆名,就说明位置不对。**
模块只能依赖 `wrapper/api`,版本差异收敛到 `wrapper/internal/vX_Y_Z`。
## 2. 分层与文件位置
以 `Player` 为例:
```text
wrapper/api/Player.java 跨版本契约(只依赖 JDK)
wrapper/internal/WrapperProvider.java 每个版本的能力工厂
wrapper/internal/WrapperRegistry.java 版本 -> Provider 分发
wrapper/MinecraftFactory.java 对外创建入口
wrapper/internal/v1_8_9/V1_8_9Player.java 1.8.9 实现
wrapper/internal/v26_2/V26_2Player.java 26.2 实现
OrangeX.java 启动时创建并持有 wrapper
```
规则:
- `api` / `common` 不允许 import `net.minecraft.*`。
- Provider 必须无状态,运行时数据全部来自 `WrapperContext`。
- 实现类不要调用 `OrangeX.getInstance()` 或 `MappingManager.getResolver()`,依赖由构造器注入。
- 新的能力接口按“能力”拆分,不要把 Player、Chat、Inventory 全塞进 `Minecraft` 接口。
## 3. 第一步:定义 API
`wrapper/api/Player.java`:
```java
package cn.xiaozhou233.orangex.wrapper.api;
/**
* Cross-version view of the local player.
*/
public interface Player {
/**
* Clears the client-side jump cooldown.
* Does nothing while no world/player is loaded.
*/
void clearJumpDelay();
}
```
接口只描述**能力**,不暴露 Minecraft 类型。宁可多一个 `Object getHandle()` 之类的逃生口,也不要把 `net.minecraft.entity.Entity` 写进 API。
## 4. 第二步:实现各版本
### 4.1 1.8.9
```java
package cn.xiaozhou233.orangex.wrapper.internal.v1_8_9;
public final class V1_8_9Player implements Player {
private static final String MINECRAFT = "net/minecraft/client/Minecraft";
private static final String ENTITY_LIVING = "net/minecraft/entity/EntityLivingBase";
private static final String PLAYER_FIELD = "thePlayer";
private static final String JUMP_DELAY_FIELD = "jumpTicks";
private final Object minecraft;
private final Field playerField;
private final String jumpDelayFieldName;
private Field jumpDelayField;
public V1_8_9Player(MappingResolver resolver, Minecraft minecraft) {
this.minecraft = minecraft.getMinecraft();
MappingClass minecraftMapping = resolver.mapClass(MINECRAFT);
this.playerField = resolveField(
minecraftMapping, PLAYER_FIELD, this.minecraft.getClass());
this.jumpDelayFieldName = fieldName(
resolver.mapClass(ENTITY_LIVING), JUMP_DELAY_FIELD);
}
@Override
public void clearJumpDelay() {
Object localPlayer = ReflectionSupport.get(playerField, minecraft);
if (localPlayer == null) {
return;
}
if (jumpDelayField == null) {
jumpDelayField = ReflectionSupport.requireField(
localPlayer.getClass(), jumpDelayFieldName, ENTITY_LIVING);
}
ReflectionSupport.setInt(jumpDelayField, localPlayer, 0);
}
}
```
### 4.2 26.2
```java
package cn.xiaozhou233.orangex.wrapper.internal.v26_2;
public final class V26_2Player implements Player {
private static final String MINECRAFT = "net/minecraft/client/Minecraft";
private static final String ENTITY_LIVING = "net/minecraft/world/entity/LivingEntity";
private static final String PLAYER_FIELD = "player";
private static final String JUMP_DELAY_FIELD = "noJumpDelay";
// 构造、解析和 clearJumpDelay 与 1.8.9 版本相同
}
```
差异只体现在常量上:
| 含义 | 1.8.9 | 26.2 |
| --- | --- | --- |
| Minecraft 里的玩家字段 | `thePlayer` | `player` |
| 玩家基类 | `net/minecraft/entity/EntityLivingBase` | `net/minecraft/world/entity/LivingEntity` |
| 跳跃冷却字段 | `jumpTicks` | `noJumpDelay` |
名称解析的细节见 [reflection-and-mappings.md](reflection-and-mappings.md)。
## 5. 第三步:扩展 Provider
`wrapper/internal/WrapperProvider.java` 增加一个工厂方法:
```java
public interface WrapperProvider {
Minecraft createMinecraft(WrapperContext context);
WorldView createWorld(WrapperContext context, Minecraft minecraft);
Player createPlayer(WrapperContext context, Minecraft minecraft);
}
```
两个版本的 Provider 分别实现:
```java
// v1_8_9/V1_8_9WrapperProvider
@Override
public Player createPlayer(WrapperContext context, Minecraft minecraft) {
return new V1_8_9Player(context.getMappingResolver(), minecraft);
}
// v26_2/V26_2WrapperProvider
@Override
public Player createPlayer(WrapperContext context, Minecraft minecraft) {
return new V26_2Player(context.getMappingResolver(), minecraft);
}
```
为什么参数里要传 `Minecraft`:实现需要从 `Minecraft` 实例上读 `thePlayer` / `player` 字段;`WrapperContext` 只包含运行时信息和映射解析器。
## 6. 第四步:Registry 分发
`wrapper/internal/WrapperRegistry.java`:
```java
public static Player createPlayer(WrapperContext context, Minecraft minecraft) {
return provider(context).createPlayer(context, minecraft);
}
```
`provider(context)` 按 `RuntimeInfo#getMinecraftVersion()` 找到对应 Provider,未注册的版本会抛出 `Unsupported Minecraft version`。
## 7. 第五步:Factory 暴露
`wrapper/MinecraftFactory.java`:
```java
public static Player createPlayer(RuntimeInfo runtimeInfo,
MappingResolver mappingResolver,
Minecraft minecraft) {
return WrapperRegistry.createPlayer(
new WrapperContext(runtimeInfo, mappingResolver), minecraft);
}
```
业务代码只应依赖 `MinecraftFactory` 和 `api`,不要直接 import `WrapperRegistry` 或版本实现。
## 8. 第六步:启动时创建
`OrangeX.start()` 中,在 `MinecraftFactory.create(...)` 之后创建:
```java
try {
this.player = MinecraftFactory.createPlayer(
runtimeInfo, MappingManager.getResolver(), minecraft);
} catch (Throwable throwable) {
// 能力不可用时客户端仍要能启动,依赖它的模块自然失效即可。
System.err.println("[OrangeX] Player wrapper unavailable: "
+ throwable.getMessage());
throwable.printStackTrace();
}
```
同时加 getter:
```java
@Getter
private Player player;
```
注意:
- 创建顺序必须是 `Minecraft` → `WorldView` / `Player`,因为后两者构造时需要读取 `Minecraft` 实例上的字段。
- 能力构造失败不能中断启动;模块里对 `null` 做处理。
- 模块开启时才订阅事件,所以 wrapper 为 null 时模块只是“没有效果”,不会崩。
## 9. 第七步:模块使用
```java
public class NoJumpDelay extends Module {
public NoJumpDelay() {
super("NoJumpDelay", ModuleCategory.MOVEMENT);
}
@Subscribe
public void onTickPre(EventTickPre event) {
Player player = OrangeX.getInstance().getPlayer();
if (player == null) {
return;
}
player.clearJumpDelay();
}
}
```
模块不需要知道版本,也不需要知道字段名。完整调用链:
```text
TickHook 注入 Minecraft.runTick
│
▼
EventBus.post(EventTickPre)
│
▼
NoJumpDelay.onTickPre()
│
▼
OrangeX.getPlayer() // api.Player
│
▼
V1_8_9Player / V26_2Player // 版本实现
│
▼
ReflectionSupport.setInt(jumpTicks / noJumpDelay, 0)
```
## 10. 设计约定
### 10.1 对象会变,字段不会
- `Minecraft` 单例:整个进程稳定。
- 本地玩家:换世界、重连、切服务器都会变。
- 玩家类:进程内稳定,可以缓存 `Field` / `Method`。
因此典型模式是:
```text
构造器:解析 Minecraft 字段
首次调用:解析玩家类字段并缓存
每次调用:重新读取玩家对象,判空,再读写字段
```
### 10.2 能力要能安全地“不可用”
- 无世界/无玩家时返回 null 或空操作,不要抛异常。
- 构造失败时只打日志,让依赖模块自然失效。
- 读操作失败不要让整个渲染帧挂掉(参考 ESP 对 `WorldView` 的 try/catch)。
### 10.3 保持 API 纯净
- 不把 `Object` 强转逻辑泄漏到模块。
- 不把版本枚举带进模块(不要写 `if (version == V1_8_9)`)。
- 同一个能力如果有多个数据,放在同一个接口里,例如 `Player#getHealth()`、`Player#clearJumpDelay()`。
### 10.4 命名
- `api` 接口用能力名:`Player`、`WorldView`、`Minecraft`。
- 版本实现用 `V<主>_<次>_<修订><能力>`:`V1_8_9Player`、`V26_2Player`。
- Provider 用 `V<版本>WrapperProvider`。
- 包名 `v1_8_9` / `v26_2`,与现有结构保持一致。
## 11. 支持新版本时要做什么
当 `WrapperRegistry` 新增一个版本时,该版本的 Provider 必须实现**所有**能力方法:
```java
@Override public Minecraft createMinecraft(WrapperContext context) { ... }
@Override public WorldView createWorld(WrapperContext context, Minecraft minecraft) { ... }
@Override public Player createPlayer(WrapperContext context, Minecraft minecraft) { ... }
```
某个版本暂时不支持的能力可以抛 `UnsupportedOperationException`,`OrangeX.start()` 会捕获并记录,其他能力不受影响。
## 12. Checklist
- [ ] `wrapper/api` 新接口只依赖 JDK,没有 Minecraft 类型。
- [ ] 每个已支持版本都实现了新的 Provider 方法。
- [ ] `WrapperRegistry` 和 `MinecraftFactory` 已增加分发方法。
- [ ] `OrangeX` 启动时创建 wrapper,并捕获异常。
- [ ] 模块只依赖 `api`,使用前判空。
- [ ] 没有缓存玩家/世界实例,只缓存 `Field` / `Method`。
- [ ] 所有名字通过 `MappingResolver`。
- [ ] `./gradlew :OrangeX:shadowJar` 通过。
- [ ] 在 1.8.9(Vanilla / Forge / MCP)和 26.2 至少各验证一次。
## 13. 相关文档
- [adding-modules.md](adding-modules.md):模块注册、Value、配置持久化。
- [reflection-and-mappings.md](reflection-and-mappings.md):反射工具和映射细节。
- [adding-wrapper-versions.md](adding-wrapper-versions.md):新增 Minecraft 版本。
+55 -16
View File
@@ -19,7 +19,9 @@ wrapper/
├── MinecraftFactory.java # 唯一公开入口
├── package-info.java
├── api/
│ └── Minecraft.java # 跨版本契约,只依赖 JDK
│ ├── Minecraft.java # 跨版本契约,只依赖 JDK
│ ├── Player.java
│ └── WorldView.java
├── common/
│ └── Vec3.java # 与版本无关的值对象
└── internal/
@@ -28,7 +30,9 @@ wrapper/
├── WrapperRegistry.java # 版本 -> Provider 注册表
└── v1_8_9/
├── V1_8_9WrapperProvider.java
└── V1_8_9Minecraft.java
├── V1_8_9Minecraft.java
├── V1_8_9WorldView.java
└── V1_8_9Player.java
```
各层职责:
@@ -234,42 +238,71 @@ static {
MCP 开发环境使用 `MappingClass.identity(...)`:没有显式注册的成员会按
同名返回,因此 `theMinecraft` 这类 named 字段可以直接使用。
## 4. 添加新的 Wrapper 类型
## 4. 添加新的 Wrapper 能力
当需要暴露 Player、World、Chat 等能力时,不要往 `Minecraft` 接口里堆方法,
按能力单独建接口。
按能力单独建接口。完整实战(`Player` + `NoJumpDelay`)见
[adding-wrapper-capabilities.md](adding-wrapper-capabilities.md)。
以 `Player` 为例:
```java
// api/Player.java
public interface Player {
double getHealth();
void setHealth(double health);
void clearJumpDelay();
}
```
然后扩展 Provider:
`WrapperProvider` 为每种能力增加一个工厂方法。依赖 `Minecraft` 实例的能力
要把实例一起传进来:
```java
public interface WrapperProvider {
Minecraft createMinecraft(WrapperContext context);
Player createPlayer(WrapperContext context);
WorldView createWorld(WrapperContext context, Minecraft minecraft);
Player createPlayer(WrapperContext context, Minecraft minecraft);
}
```
每个版本的 Provider 实现自己的 `createPlayer`;不支持的版本抛
`UnsupportedOperationException`。
最后在 `WrapperRegistry` 增加对应分发方法,并在 `MinecraftFactory` 暴露:
`UnsupportedOperationException`:
```java
@Override
public Player createPlayer(WrapperContext context, Minecraft minecraft) {
return new V1_8_9Player(context.getMappingResolver(), minecraft);
}
```
然后在 `WrapperRegistry` 增加分发方法,并在 `MinecraftFactory` 暴露:
```java
// WrapperRegistry
public static Player createPlayer(WrapperContext context, Minecraft minecraft) {
return provider(context).createPlayer(context, minecraft);
}
// MinecraftFactory
public static Player createPlayer(RuntimeInfo runtimeInfo,
MappingResolver mappingResolver) {
MappingResolver mappingResolver,
Minecraft minecraft) {
return WrapperRegistry.createPlayer(
new WrapperContext(runtimeInfo, mappingResolver));
new WrapperContext(runtimeInfo, mappingResolver), minecraft);
}
```
最后在 `OrangeX.start()` 里创建并保存(失败只记录日志):
```java
try {
this.player = MinecraftFactory.createPlayer(
runtimeInfo, MappingManager.getResolver(), minecraft);
} catch (Throwable throwable) {
System.err.println("[OrangeX] Player wrapper unavailable: "
+ throwable.getMessage());
}
```
@@ -277,7 +310,8 @@ public static Player createPlayer(RuntimeInfo runtimeInfo,
- 业务代码只依赖 `api`。
- 新版本只需要实现同一个 Provider 接口。
- 新能力只需要加一个 API + 一个分发方法。
- 新能力只需要加一个 API、一个 Provider 方法和一个分发方法。
- 具体字段反射写在 `internal.vX_Y_Z` 中,模块看不到 Minecraft 类名。
## 5. 构建与验证
@@ -319,10 +353,15 @@ ave@71e820ad
## 7. Checklist
- [ ] `MinecraftVersion` 已有该版本,且版本检测能正确输出。
- [ ] `wrapper/internal/vX_Y_Z` 下有 `VX_Y_ZWrappedProvider` 和 `VX_Y_ZMinecraft`。
- [ ] `WrapperRegistry` 已注册该 Provider。
- [ ] `wrapper/internal/vX_Y_Z` 下有 `VX_Y_ZWrapperProvider`、`VX_Y_ZMinecraft`,
以及该版本支持的其它能力实现(`WorldView`、`Player`……)。
- [ ] Provider 实现了 `createMinecraft`、`createWorld`、`createPlayer`;
暂不支持的能力显式抛 `UnsupportedOperationException`。
- [ ] `WrapperRegistry` 已注册该 Provider,并为每种能力增加分发方法。
- [ ] `MappingManager` 已支持该版本 + 加载器组合。
- [ ] SRG 资源已放到 `src/main/resources/mappings/...`。
- [ ] 实现类中没有静态单例查询,依赖全部来自 `WrapperContext`。
- [ ] `api` / `common` 中没有任何 Minecraft 或映射名称。
- [ ] `./gradlew :OrangeX:shadowJar` 通过,并在真实客户端中打印出实例。
新增能力而不是新增版本时,见 [adding-wrapper-capabilities.md](adding-wrapper-capabilities.md)。
Binary file not shown.

After

Width:  |  Height:  |  Size: 277 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

+254
View File
@@ -0,0 +1,254 @@
# 反射与混淆映射
本文说明 OrangeX 如何安全地访问 Minecraft 的类、字段和方法,以及多版本/多加载器下必须遵守的规则。
## 1. 为什么不能直接写死
同一个字段在不同运行环境里的名字完全不同:
| 环境 | 本地玩家字段 | 跳跃冷却字段 |
| --- | --- | --- |
| 1.8.9 MCP(开发环境) | `thePlayer` | `jumpTicks` |
| 1.8.9 Vanilla / Forge(混淆) | `h` | `bn` |
| 26.2(Mojang 名) | `player` | `noJumpDelay` |
而且混淆名会随客户端版本变化。直接写 `getDeclaredField("jumpTicks")` 在 MCP 开发环境能跑,到了线上混淆客户端会立刻 `NoSuchFieldException`。
因此项目统一遵守:
```text
业务代码写“命名名”(MCP / Mojang)
│
▼
MappingResolver 翻译成运行时名(混淆名或原样)
│
▼
ReflectionSupport 按运行时名查找并缓存 Field / Method
```
**只有 `wrapper/internal/vX_Y_Z` 允许出现 Minecraft 类名、字段名和方法名。**
模块、`wrapper/api`、`wrapper/common` 中都不要出现 `net.minecraft.*`。
## 2. 命名来源
项目里会出现三种名字,注意区分:
| 名字 | 示例 | 用在哪里 |
| --- | --- | --- |
| 命名名(MCP / Mojang) | `net/minecraft/entity/EntityLivingBase#jumpTicks` | 源码常量、`MappingResolver` 的输入 |
| 运行时名(混淆 / 原样) | `pr#bn` / `noJumpDelay` | `Class#getDeclaredField`、`Class#getDeclaredMethod` |
| 内部名(internal) | `pr/bn` | 映射文件、`Class.forName` 前需要 `.replace('/', '.')` |
写映射时统一使用**内部名 + 命名成员名**,例如:
```java
resolver.mapClass("net/minecraft/entity/EntityLivingBase");
resolver.mapField("net/minecraft/entity/EntityLivingBase", "jumpTicks");
resolver.mapMethod("net/minecraft/client/Minecraft", "runTick", "()V");
```
## 3. MappingResolver
入口:
```java
MappingResolver resolver = MappingManager.getResolver();
```
`MappingManager.init(runtimeInfo)` 按版本和加载器选择实现:
| 版本 | 加载器 | Resolver | 行为 |
| --- | --- | --- | --- |
| 1.8.9 | MCP | `MCPMappingResolver` | 全部按原名返回 |
| 1.8.9 | Vanilla | `SrgMappingResolver("mappings/vanilla189/joined.srg")` | 命名名 → 混淆名 |
| 1.8.9 | Forge | `SrgMappingResolver("mappings/forge189/joined.srg")` | 命名名 → 混淆名 |
| 26.2 | 任意(Mojang 名) | `IdentityFallbackMappingResolver` | 全部按原名返回 |
映射文件位于:
```text
OrangeX/src/main/resources/mappings/vanilla189/joined.srg
OrangeX/src/main/resources/mappings/forge189/joined.srg
```
SRG 行格式(节选):
```text
CL: pr net/minecraft/entity/EntityLivingBase
FD: pr/bn net/minecraft/entity/EntityLivingBase/jumpTicks
```
`SrgMappingResolver` 会在内部把 `FD` 的右侧(命名)作为 key,左侧(混淆)作为目标名,所以:
```java
resolver.mapField("net/minecraft/entity/EntityLivingBase", "jumpTicks")
.getTargetName(); // "bn"
```
### 3.1 API
```java
MappingClass mapClass(String className);
MappingField mapField(String owner, String fieldName);
MappingMethod mapMethod(String owner, String methodName, String descriptor);
```
`MappingClass` 还提供:
```java
mappingClass.getTargetName(); // 运行时类名(内部名)
mappingClass.getField("jumpTicks"); // 可能为 null
mappingClass.getMethod("runTick", "()V"); // 可能为 null
```
两种取值方式要注意:
- `resolver.mapField(...)` / `resolver.mapMethod(...)`:找不到映射时返回**同名映射**,不会为 null,适合“名字一定存在,只是可能被混淆”的场景。
- `MappingClass#getField` / `#getMethod`:非 identity 映射找不到时返回 `null`,适合需要显式判断“这个成员在当前版本不存在”的场景。
当前 `MappingClass` 有 identity 模式(MCP / 26.2),该模式下未登记的成员也返回同名映射。
### 3.2 类名与 `Class.forName`
映射出来的类名是内部名(`pr`、`net/minecraft/client/Minecraft`),加载时要转成二进制名,并始终使用游戏的 ClassLoader:
```java
String binaryName = resolver.mapClass("net/minecraft/client/Minecraft")
.getTargetName()
.replace('/', '.');
Class<?> minecraftClass = Class.forName(
binaryName, false, runtimeInfo.getMinecraftClassLoader());
```
不要用 `Class.forName(name)` 的单参版本:Fabric / Forge / 启动器的类可能只在游戏 ClassLoader 中可见。
## 4. ReflectionSupport
`wrapper/internal/ReflectionSupport` 是版本实现共用的反射工具,所有查找都会沿父类链向上找:
| 方法 | 说明 |
| --- | --- |
| `findField(Class, name)` | 查找实例字段(跳过 static),找不到返回 `null`,并已 `setAccessible(true)` |
| `requireField(Class, name, ownerName)` | 同上,找不到抛 `IllegalStateException` |
| `findMethod(Class, name, returnType, params...)` | 按名称、参数类型(可选返回类型)查找实例方法 |
| `requireMethod(...)` | 同上,找不到抛异常 |
| `get` / `getInt` / `getFloat` / `getDouble` / `getBoolean` | 读取字段 |
| `setInt(Field, target, value)` | 写入 int 字段 |
| `invoke(Method, target, args...)` | 调用方法,包装反射异常 |
为什么必须沿父类链查找:字段经常声明在基类,而实际对象是子类。例如 `jumpTicks` 声明在 `EntityLivingBase`,拿到的对象却是 `EntityPlayerSP`;玩家字段声明在 `Minecraft`,实现类可能被启动器替换。
## 5. 编写一个版本实现
以 `V1_8_9Player` 为例:
```java
public final class V1_8_9Player implements Player {
private static final String MINECRAFT = "net/minecraft/client/Minecraft";
private static final String ENTITY_LIVING = "net/minecraft/entity/EntityLivingBase";
private static final String PLAYER_FIELD = "thePlayer";
private static final String JUMP_DELAY_FIELD = "jumpTicks";
private final Object minecraft;
private final Field playerField;
private final String jumpDelayFieldName;
private Field jumpDelayField;
public V1_8_9Player(MappingResolver resolver, Minecraft minecraft) {
this.minecraft = minecraft.getMinecraft();
MappingClass minecraftMapping = resolver.mapClass(MINECRAFT);
this.playerField = resolveField(
minecraftMapping, PLAYER_FIELD, this.minecraft.getClass());
this.jumpDelayFieldName = fieldName(
resolver.mapClass(ENTITY_LIVING), JUMP_DELAY_FIELD);
}
@Override
public void clearJumpDelay() {
Object localPlayer = ReflectionSupport.get(playerField, minecraft);
if (localPlayer == null) {
return;
}
if (jumpDelayField == null) {
jumpDelayField = ReflectionSupport.requireField(
localPlayer.getClass(), jumpDelayFieldName, ENTITY_LIVING);
}
ReflectionSupport.setInt(jumpDelayField, localPlayer, 0);
}
}
```
规律:
1. **在构造器里解析 `Minecraft` 上的字段**。`Minecraft` 实例在整个进程里是稳定的。
2. **玩家实例不要缓存**。换世界、重连、切服务器后对象会变,每次使用时重新读字段。
3. **字段本身可以缓存**。玩家类在进程内稳定,第一次拿到玩家后再解析 `jumpTicks` / `noJumpDelay` 并缓存。
4. **玩家为 null 时直接返回**。标题界面、加载界面没有本地玩家。
5. **所有名字通过 `MappingResolver` / `MappingClass` 获取**,不要出现 `"bn"`、`"h"` 这类硬编码。
### 5.1 1.8.9 与 26.2 的对照
| 含义 | 1.8.9 | 26.2 |
| --- | --- | --- |
| 本地玩家字段 | `Minecraft#thePlayer` | `Minecraft#player` |
| 玩家基类 | `net/minecraft/entity/EntityLivingBase` | `net/minecraft/world/entity/LivingEntity` |
| 跳跃冷却字段 | `jumpTicks`(int) | `noJumpDelay`(int) |
| 冷却语义 | 跳跃后设为 10,减到 0 才允许再跳 | 每 tick 递减,大于 0 时禁止起跳 |
注意 1.8.9 的 `jumpTicks` 是从基类继承的,因此 `ReflectionSupport.requireField(localPlayer.getClass(), ...)` 会向上找到 `EntityLivingBase`。
## 6. 常见坑
| 坑 | 说明 / 解决 |
| --- | --- |
| 用 `getField` 读私有字段 | `getField` 只能找到 public 字段,改用 `getDeclaredField` + `setAccessible(true)`(`ReflectionSupport` 已封装) |
| 把内部名直接传给 `Class.forName` | 先 `.replace('/', '.')` |
| 用默认 ClassLoader | 使用 `runtimeInfo.getMinecraftClassLoader()` |
| 缓存玩家对象 | 玩家对象会换;缓存字段或方法,不缓存实例 |
| 字段在父类上 | `ReflectionSupport` 会沿父类链查找,不要只查 `getClass().getDeclaredField(...)` |
| 基本类型用 `Field#get` | int 用 `getInt` / `setInt`,float 用 `getFloat`,否则拿到的是包装类型或类型不匹配 |
| 静态字段 | `findField` 会跳过 static;单例字段需要单独按静态字段处理(参考 `V1_8_9Minecraft#findStaticField`) |
| 方法重载 | 提供参数类型;如果方法名相同但签名不同,`MappingResolver` 需要同时给出 descriptor |
| 映射文件过期 | 客户端小版本变化后混淆名可能变,更新对应的 `joined.srg` |
| 每个 tick 重复查找 | 构造器或首次使用时解析并缓存 `Field` / `Method` |
| 反射异常吞掉不报 | wrapper 构造失败会打印日志;模块里也要避免静默失败导致“功能看起来没生效” |
## 7. 排查顺序
1. 打开日志,确认版本和加载器检测正确:
```text
Loader Type: VANILLA
Minecraft Version: V1_8_9 (version id 15)
```
2. 打印解析结果,确认命名名映射到了预期的运行时名:
```java
System.out.println(resolver.mapField(OWNER, "jumpTicks").getTargetName());
```
3. 确认反射查找的类来自正确的 ClassLoader。
4. 确认对象非 null:标题界面没有玩家,属于正常情况。
5. 确认字段类型:int 字段不能用 `get()` 后强转 `Integer` 以外的处理方式。
6. 如果只有某个加载器失败,检查 `MappingManager` 是否选中了对应版本的 SRG 文件。
## 8. Checklist
- [ ] 模块 / `wrapper/api` / `wrapper/common` 没有 Minecraft 类名或混淆名。
- [ ] 所有类、字段、方法名都通过 `MappingResolver`。
- [ ] 私有成员使用 `getDeclaredField` + `setAccessible(true)`。
- [ ] `Class.forName` 使用游戏 ClassLoader,并转换内部名。
- [ ] 玩家/世界对象不缓存,字段/方法缓存。
- [ ] 对象可能为 null 的路径已处理。
- [ ] 首次解析失败会打日志,不会每 tick 重试刷屏。
- [ ] 在 Vanilla、Forge、MCP / 26.2 至少各验证一次。