diff --git a/.gitignore b/.gitignore
index 6708bd52..02eb04a3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,3 +17,6 @@ target/
# Ignore any json files in the server root (should only be config files, the sample file should still be updated)
2006Scape Server/*.json
+rsapriv
+rsapub
+
diff --git a/2006Scape Client/pom.xml b/2006Scape Client/pom.xml
index 820c3892..0537035f 100644
--- a/2006Scape Client/pom.xml
+++ b/2006Scape Client/pom.xml
@@ -13,6 +13,20 @@
1.0
jar
+
+
+ net.java.dev.jna
+ jna
+ 4.4.0
+
+
+ junit
+ junit
+ 4.7
+ test
+
+
+
diff --git a/2006Scape Client/src/main/java/AndroidHooks.java b/2006Scape Client/src/main/java/AndroidHooks.java
index 3876310c..78703493 100644
--- a/2006Scape Client/src/main/java/AndroidHooks.java
+++ b/2006Scape Client/src/main/java/AndroidHooks.java
@@ -47,4 +47,24 @@ public final class AndroidHooks {
public static void showKeyboard() {}
public static void hideKeyboard() {}
+
+ public static void drawModernMinimap(Object graphics, int[] minimapPixels, int windowWidth) {}
+
+ public static Object getRenderGraphics(Object screenGraphics) {
+ return screenGraphics;
+ }
+
+ public static void flip(Object screenGraphics) {}
+
+ public static void loadExternalDexPlugins(java.io.File file, java.util.List plugins, java.util.List scripts) {}
+
+ public static void showPluginManagerDialog(Game game) {}
+
+ public static void openScriptsFolder() {
+ try {
+ java.io.File dir = new java.io.File(Signlink.findcachedir(), "scripts");
+ if (!dir.exists()) dir.mkdirs();
+ java.awt.Desktop.getDesktop().open(dir);
+ } catch (Throwable ignored) {}
+ }
}
diff --git a/2006Scape Client/src/main/java/Class40.java b/2006Scape Client/src/main/java/Class40.java
index 89b5fce5..0dbfd7a2 100644
--- a/2006Scape Client/src/main/java/Class40.java
+++ b/2006Scape Client/src/main/java/Class40.java
@@ -2,7 +2,7 @@
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
-final class Class40 {
+public final class Class40 {
public Class40(int i, int j, int k, int l, int i1, int j1, int k1, int l1, int i2, int j2, int k2, int l2, int i3, int j3, int k3, int l3, int i4, int k4, int l4) {
aBoolean683 = !(i3 != l2 || i3 != l || i3 != k2);
@@ -151,12 +151,14 @@ final class Class40 {
anIntArray676 = new int[j7];
anIntArray677 = new int[j7];
anIntArray678 = new int[j7];
+ isOverlayFace = new boolean[j7];
if (i1 != -1) {
anIntArray682 = new int[j7];
}
int l7 = 0;
for (int j8 = 0; j8 < j7; j8++) {
int l8 = ai3[l7];
+ isOverlayFace[j8] = (l8 != 0);
int k9 = ai3[l7 + 1];
int i10 = ai3[l7 + 2];
int k10 = ai3[l7 + 3];
@@ -214,21 +216,23 @@ final class Class40 {
l9 /= 14;
}
- final int[] anIntArray673;
- final int[] anIntArray674;
- final int[] anIntArray675;
- final int[] anIntArray676;
- final int[] anIntArray677;
- final int[] anIntArray678;
- final int[] anIntArray679;
- final int[] anIntArray680;
- final int[] anIntArray681;
- int anIntArray682[];
- final boolean aBoolean683;
- final int anInt684;
- final int anInt685;
- final int anInt686;
- final int anInt687;
+ public final int[] anIntArray673;
+ public final int[] anIntArray674;
+ public final int[] anIntArray675;
+ public final int[] anIntArray676;
+ public final int[] anIntArray677;
+ public final int[] anIntArray678;
+ public final int[] anIntArray679;
+ public final int[] anIntArray680;
+ public final int[] anIntArray681;
+ public final boolean[] isOverlayFace;
+ public int anIntArray682[];
+ public final boolean aBoolean683;
+ public final int anInt684;
+ public final int anInt685;
+ public final int anInt686;
+ public final int anInt687;
+ public int plane;
static final int[] anIntArray688 = new int[6];
static final int[] anIntArray689 = new int[6];
static final int[] anIntArray690 = new int[6];
diff --git a/2006Scape Client/src/main/java/Class43.java b/2006Scape Client/src/main/java/Class43.java
index 74d03050..d1a3b3da 100644
--- a/2006Scape Client/src/main/java/Class43.java
+++ b/2006Scape Client/src/main/java/Class43.java
@@ -2,7 +2,7 @@
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
-final class Class43 {
+public final class Class43 {
public Class43(int i, int j, int k, int l, int i1, int j1, boolean flag) {
aBoolean721 = true;
@@ -15,11 +15,12 @@ final class Class43 {
aBoolean721 = flag;
}
- final int anInt716;
- final int anInt717;
- final int anInt718;
- final int anInt719;
- final int anInt720;
- boolean aBoolean721;
- final int anInt722;
+ public final int anInt716;
+ public final int anInt717;
+ public final int anInt718;
+ public final int anInt719;
+ public final int anInt720;
+ public boolean aBoolean721;
+ public final int anInt722;
+ public boolean isOverlay = false;
}
diff --git a/2006Scape Client/src/main/java/ClientArgs.java b/2006Scape Client/src/main/java/ClientArgs.java
index 211fb7ed..aacc9d87 100644
--- a/2006Scape Client/src/main/java/ClientArgs.java
+++ b/2006Scape Client/src/main/java/ClientArgs.java
@@ -36,9 +36,22 @@ public final class ClientArgs {
case "-check-crc":
ClientSettings.CHECK_CRC = true;
break;
+ case "-resizable":
+ case "-resize":
+ if (!ClientSettings.ANDROID) {
+ ClientSettings.RESIZABLE = true;
+ ClientSettings.SHOW_NAVBAR = false;
+ }
+ break;
+ case "-hd":
+ case "-317hd":
+ ClientSettings.HD_317 = true;
+ break;
case "-qol":
case "-fixes":
+ case "-enable-qol":
ClientSettings.CUSTOM_SETTINGS_TAB = true;
+ ClientSettings.ENABLE_QOL = true;
ClientSettings.BILINEAR_MINIMAP_FILTERING = true;
ClientSettings.FIX_TRANSPARENCY_OVERFLOW = true;
ClientSettings.FULL_512PX_VIEWPORT = true;
@@ -46,6 +59,10 @@ public final class ClientArgs {
ClientSettings.CONTROL_KEY_ZOOMING = true;
}
break;
+ case "-no-qol":
+ case "-disable-qol":
+ ClientSettings.ENABLE_QOL = false;
+ break;
case "-no-nav":
case "-disable-nav":
ClientSettings.SHOW_NAVBAR = false;
@@ -111,6 +128,8 @@ public final class ClientArgs {
}
}
}
+ // Game copies SERVER_IP into Game.server in its constructor, which runs before these args are applied
+ Game.server = ClientSettings.SERVER_IP;
}
public static String[] splitArgs(String input) {
diff --git a/2006Scape Client/src/main/java/ClientPlugin.java b/2006Scape Client/src/main/java/ClientPlugin.java
new file mode 100644
index 00000000..2ac002e6
--- /dev/null
+++ b/2006Scape Client/src/main/java/ClientPlugin.java
@@ -0,0 +1,114 @@
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Base class for RuneLite-style event-driven plugins.
+ */
+public abstract class ClientPlugin {
+
+ protected PluginContext ctx;
+ private boolean enabled;
+
+ public abstract String getName();
+
+ public String getDescription() {
+ return "";
+ }
+
+ public String getAuthor() {
+ return "2006Scape";
+ }
+
+ public String getVersion() {
+ return "1.0.0";
+ }
+
+ public String getMinApiVersion() {
+ return "1.0.0";
+ }
+
+ public final SemVer getSemVer() {
+ return SemVer.parse(getVersion());
+ }
+
+ public boolean isEnabledByDefault() {
+ return false;
+ }
+
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ public void setEnabled(boolean enabled) {
+ this.enabled = enabled;
+ }
+
+ public List getConfigItems() {
+ return Collections.emptyList();
+ }
+
+ public void onConfigChanged(String key, Object value) {
+ }
+
+ public void onStart(PluginContext ctx) {
+ this.ctx = ctx;
+ }
+
+ public void onStop() {
+ }
+
+ public void onGameTick() {
+ }
+
+ /**
+ * Called before rendering or executing the right-click menu.
+ * The last entry in the list is the default left-click action.
+ */
+ public void onPreMenuRender(List entries) {
+ }
+
+ /**
+ * Called when a menu action is chosen. Return false to consume/block the action.
+ */
+ public boolean onMenuAction(MenuEntry entry) {
+ return true;
+ }
+
+ public void onChatMessage(int type, String sender, String message) {
+ }
+
+ public void onGroundItemSpawn(int itemId, int amount, int worldX, int worldY, int plane) {
+ }
+
+ public void onGroundItemSpawned(PluginContext.GroundItemWrapper item) {
+ }
+
+ public void onXpGained(int skillId, int deltaXp) {
+ }
+
+ public void onAnimationChanged(int animId) {
+ }
+
+ public void onLogin() {
+ }
+
+ public void onDisconnect() {
+ }
+
+ public void onPlayerDeath() {
+ }
+
+ public void onLogout() {
+ }
+
+ public void onRenderOverlay(PluginGraphics g) {
+ }
+
+ public boolean handlesCommandsWhenDisabled() {
+ return false;
+ }
+
+ public boolean onCommand(String command, String[] args) {
+ return false;
+ }
+}
diff --git a/2006Scape Client/src/main/java/ClientScript.java b/2006Scape Client/src/main/java/ClientScript.java
new file mode 100644
index 00000000..f788ed06
--- /dev/null
+++ b/2006Scape Client/src/main/java/ClientScript.java
@@ -0,0 +1,293 @@
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.BooleanSupplier;
+
+/**
+ * Base class for tick-safe automation scripts.
+ * Runs deterministically in the client game loop.
+ */
+public abstract class ClientScript {
+
+ protected PluginContext ctx;
+ private volatile boolean running;
+ private volatile boolean paused;
+ private long nextExecutionTimeMs;
+ private long startTimeMs;
+ private long lastProgressTimeMs;
+ private int lastProgressX = Integer.MIN_VALUE;
+ private int lastProgressY = Integer.MIN_VALUE;
+ private BooleanSupplier pendingWaitCondition;
+ private long pendingWaitDeadlineMs;
+ private int pendingWaitPollMs = 100;
+ private boolean lastWaitTimedOut;
+ private final Map timers = new HashMap<>();
+ protected String status = "Idle";
+
+ public abstract String getName();
+
+ public String getDescription() {
+ return "";
+ }
+
+ public String getAuthor() {
+ return "2006Scape";
+ }
+
+ public String getCategory() {
+ return "Automation";
+ }
+
+ public String getVersion() {
+ return "1.0.0";
+ }
+
+ public String getMinApiVersion() {
+ return "1.0.0";
+ }
+
+ public final SemVer getSemVer() {
+ return SemVer.parse(getVersion());
+ }
+
+ public List getCommandNames() {
+ return Collections.emptyList();
+ }
+
+ public List getConfigItems() {
+ return Collections.emptyList();
+ }
+
+ public void onConfigChanged(String key, Object value) {
+ }
+
+ public final void start(PluginContext ctx) {
+ this.ctx = ctx;
+ this.running = true;
+ this.paused = false;
+ this.startTimeMs = System.currentTimeMillis();
+ this.nextExecutionTimeMs = 0;
+ this.lastProgressTimeMs = this.startTimeMs;
+ this.lastProgressX = Integer.MIN_VALUE;
+ this.lastProgressY = Integer.MIN_VALUE;
+ this.pendingWaitCondition = null;
+ this.lastWaitTimedOut = false;
+ this.timers.clear();
+ this.status = "Starting";
+ ScriptLogger.log(getName(), "Started");
+ onStart(ctx);
+ }
+
+ public final void stop() {
+ if (!running) return;
+ this.running = false;
+ this.paused = false;
+ this.pendingWaitCondition = null;
+ this.timers.clear();
+ this.status = "Stopped";
+ ScriptLogger.log(getName(), "Stopped");
+ onStop();
+ }
+
+ public final void pause() {
+ this.paused = true;
+ this.status = "Paused";
+ ScriptLogger.log(getName(), "Paused");
+ }
+
+ public final void resume() {
+ this.paused = false;
+ this.status = "Running";
+ ScriptLogger.log(getName(), "Resumed");
+ }
+
+ public boolean isRunning() {
+ return running;
+ }
+
+ public boolean isPaused() {
+ return paused;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ String next = status != null ? status : "Idle";
+ if (!next.equals(this.status)) {
+ ScriptLogger.log(getName(), "Status -> " + next);
+ }
+ this.status = next;
+ }
+
+ public long getRuntimeMs() {
+ if (!running) return 0;
+ return System.currentTimeMillis() - startTimeMs;
+ }
+
+ public String getFormattedRuntime() {
+ long sec = getRuntimeMs() / 1000;
+ long h = sec / 3600;
+ long m = (sec % 3600) / 60;
+ long s = sec % 60;
+ return String.format("%02d:%02d:%02d", h, m, s);
+ }
+
+ /** Formats counts/XP >= 1,000 in compact K/M notation (e.g. 10000 -> 10K, 1500 -> 1.5K). */
+ public static String formatCompactNumber(long value) {
+ if (value < 1000) {
+ return String.valueOf(value);
+ }
+ if (value < 1_000_000) {
+ long whole = value / 1000;
+ long tenths = (value % 1000) / 100;
+ return (tenths > 0 && value < 100_000) ? (whole + "." + tenths + "K") : (whole + "K");
+ }
+ long whole = value / 1_000_000;
+ long tenths = (value % 1_000_000) / 100_000;
+ return tenths > 0 ? (whole + "." + tenths + "M") : (whole + "M");
+ }
+
+ public final void processTick() {
+ if (!running || paused) return;
+ long now = System.currentTimeMillis();
+ updateWatchdog(now);
+ if (now < nextExecutionTimeMs) return;
+
+ try {
+ if (pendingWaitCondition != null) {
+ boolean satisfied = pendingWaitCondition.getAsBoolean();
+ if (!satisfied && now < pendingWaitDeadlineMs) {
+ nextExecutionTimeMs = now + pendingWaitPollMs;
+ return;
+ }
+ lastWaitTimedOut = !satisfied;
+ pendingWaitCondition = null;
+ }
+ int delayMs = loop();
+ if (delayMs < 0) {
+ stop();
+ } else {
+ nextExecutionTimeMs = now + Math.max(50, delayMs);
+ }
+ } catch (Throwable t) {
+ System.err.println("Exception in script " + getName() + ": " + t.getMessage());
+ t.printStackTrace();
+ ScriptLogger.log(getName(), "ERROR: " + t.getClass().getSimpleName() + ": " + t.getMessage());
+ status = "Error: " + t.getMessage();
+ stop();
+ }
+ }
+
+ private void updateWatchdog(long now) {
+ if (ctx == null || !ctx.isLoggedIn()) return;
+ int px = ctx.getPlayerX();
+ int py = ctx.getPlayerY();
+ if (px != lastProgressX || py != lastProgressY || ctx.getPlayerAnim() > 0) {
+ lastProgressX = px;
+ lastProgressY = py;
+ lastProgressTimeMs = now;
+ }
+ }
+
+ /** Resets the idle/stuck watchdog timer to the current time. */
+ public final void resetWatchdog() {
+ lastProgressTimeMs = System.currentTimeMillis();
+ if (ctx != null && ctx.isLoggedIn()) {
+ lastProgressX = ctx.getPlayerX();
+ lastProgressY = ctx.getPlayerY();
+ }
+ }
+
+ /** Returns milliseconds elapsed since the player last moved, animated, or reset the watchdog. */
+ public final long getTimeSinceProgressMs() {
+ return Math.max(0L, System.currentTimeMillis() - lastProgressTimeMs);
+ }
+
+ /** Returns true if no progress has been observed for at least thresholdMs. */
+ public final boolean isStuck(long thresholdMs) {
+ return getTimeSinceProgressMs() >= thresholdMs;
+ }
+
+ /** Starts a non-blocking condition wait; returns the poll delay for loop(). */
+ protected final int waitUntil(BooleanSupplier condition, int timeoutMs) {
+ return waitUntil(condition, timeoutMs, 100);
+ }
+
+ /** Starts a non-blocking condition wait with custom poll interval; returns pollMs for loop(). */
+ protected final int waitUntil(BooleanSupplier condition, int timeoutMs, int pollMs) {
+ this.pendingWaitCondition = condition;
+ this.pendingWaitDeadlineMs = System.currentTimeMillis() + Math.max(50, timeoutMs);
+ this.pendingWaitPollMs = Math.max(50, pollMs);
+ this.lastWaitTimedOut = false;
+ return this.pendingWaitPollMs;
+ }
+
+ /** Returns true if the most recent waitUntil() exited due to timeout rather than condition success. */
+ protected final boolean didWaitTimeout() {
+ return lastWaitTimedOut;
+ }
+
+ public final void clearWait() {
+ this.pendingWaitCondition = null;
+ }
+
+ /** Records the current timestamp under a named timer key. */
+ public final void markTimer(String key) {
+ timers.put(key, System.currentTimeMillis());
+ }
+
+ /** Returns true if at least ms milliseconds have elapsed since markTimer(key) (or if never marked). */
+ public final boolean hasElapsed(String key, long ms) {
+ Long t = timers.get(key);
+ return t == null || (System.currentTimeMillis() - t) >= ms;
+ }
+
+ public final void clearTimer(String key) {
+ timers.remove(key);
+ }
+
+ /**
+ * Called when the script starts.
+ */
+ public void onStart(PluginContext ctx) {
+ }
+
+ /**
+ * Executed periodically on the game thread.
+ * @return Delay in milliseconds before next execution, or -1 to stop the script.
+ */
+ public abstract int loop();
+
+ /**
+ * Called when the script stops.
+ */
+ public void onStop() {
+ }
+
+ public void onChatMessage(int type, String sender, String message) {
+ }
+
+ public void onXpGained(int skillId, int deltaXp) {
+ }
+
+ public void onAnimationChanged(int animId) {
+ }
+
+ public void onGroundItemSpawned(PluginContext.GroundItemWrapper item) {
+ }
+
+ public void onLogin() {
+ }
+
+ public void onDisconnect() {
+ }
+
+ public void onPlayerDeath() {
+ }
+
+ public void onRenderOverlay(PluginGraphics g) {
+ }
+}
diff --git a/2006Scape Client/src/main/java/ClientSettings.java b/2006Scape Client/src/main/java/ClientSettings.java
index 7437da0e..8b46afb2 100644
--- a/2006Scape Client/src/main/java/ClientSettings.java
+++ b/2006Scape Client/src/main/java/ClientSettings.java
@@ -13,6 +13,48 @@ public class ClientSettings {
*/
public static boolean ANDROID = false;
+ /**
+ * Flag indicating whether Modern/Resizable display mode is active.
+ */
+ public static boolean RESIZABLE = false;
+
+ /**
+ * Modern layout active: Android modern mode OR desktop -resizable when expanded beyond original 765x503 size.
+ */
+ public static boolean isModernLayout() {
+ if (ANDROID) {
+ return RESIZABLE || VIEWPORT_WIDTH > 512;
+ }
+ return isDesktopModern();
+ }
+
+ /**
+ * Click routing uses touchTargetArea (Android, or desktop modern layout).
+ */
+ public static boolean usesTouchTargets() {
+ return ANDROID || isDesktopModern();
+ }
+
+ /**
+ * Classic hard-coded tab icon hit boxes apply (fixed layout, or desktop modern after coordinate translation).
+ */
+ public static boolean usesClassicTabHitboxes() {
+ return !isModernLayout() || !ANDROID;
+ }
+
+ /**
+ * Desktop modern mode active (enabled via -resizable and window expanded past original 765x503 fixed size).
+ */
+ public static boolean isDesktopModern() {
+ return !ANDROID && RESIZABLE && (ModernLayout.windowWidth > 765 || ModernLayout.windowHeight > 503);
+ }
+
+ /**
+ * Flag indicating whether 317HD / RLHD graphics enhancements are active.
+ * Strictly gated for Android Mobile clients only.
+ */
+ public static boolean HD_317 = false;
+
/**
* Viewport dimensions for 3D rendering.
* Default 512x334 in fixed mode; scaled to native widescreen in resizable mode.
@@ -103,9 +145,14 @@ public class ClientSettings {
/**
* @QoL
- * Enables A Custom Tab With Various QoL Changes
+ * Enables A Custom Tab With Various QoL Changes & Plugin System
*/
- public static boolean CUSTOM_SETTINGS_TAB = false;
+ public static boolean CUSTOM_SETTINGS_TAB = true;
+ /**
+ * @QoL
+ * Enables QoL Settings (Player Names, Item Drops, Draw Distance, Exp Tracker, etc.)
+ */
+ public static boolean ENABLE_QOL = false;
/**
* @QoL
* Enables Bilinear Minimap Filtering Which Smooths Out Lines And Sprites On The Minimap
@@ -152,7 +199,7 @@ public class ClientSettings {
*/
public final static int UID = 314268572;
- public static final BigInteger RSA_MODULUS = new BigInteger("91553247461173033466542043374346300088148707506479543786501537350363031301992107112953015516557748875487935404852620239974482067336878286174236183516364787082711186740254168914127361643305190640280157664988536979163450791820893999053469529344247707567448479470137716627440246788713008490213212272520901741443");
- public static final BigInteger RSA_EXPONENT = new BigInteger("65537");
+ public static BigInteger RSA_MODULUS = new BigInteger("91553247461173033466542043374346300088148707506479543786501537350363031301992107112953015516557748875487935404852620239974482067336878286174236183516364787082711186740254168914127361643305190640280157664988536979163450791820893999053469529344247707567448479470137716627440246788713008490213212272520901741443");
+ public static BigInteger RSA_EXPONENT = new BigInteger("65537");
}
diff --git a/2006Scape Client/src/main/java/DesktopHd317Renderer.java b/2006Scape Client/src/main/java/DesktopHd317Renderer.java
new file mode 100644
index 00000000..d753b339
--- /dev/null
+++ b/2006Scape Client/src/main/java/DesktopHd317Renderer.java
@@ -0,0 +1,1336 @@
+import com.sun.jna.Function;
+import com.sun.jna.Library;
+import com.sun.jna.Memory;
+import com.sun.jna.Native;
+import com.sun.jna.NativeLibrary;
+import com.sun.jna.Platform;
+import com.sun.jna.Pointer;
+import com.sun.jna.Structure;
+import com.sun.jna.ptr.IntByReference;
+import java.nio.Buffer;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.FloatBuffer;
+import java.nio.IntBuffer;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Hardware-Accelerated 317HD / RLHD OpenGL Renderer for 2006Scape Desktop Client.
+ * Supports:
+ * - Linux / macOS / ANGLE via JNA EGL 1.5 + OpenGL ES 3.0+ (with surfaceless fallback)
+ * - Windows via JNA WGL (opengl32.dll / gdi32.dll / user32.dll) OpenGL 3.3 Core/Compatibility
+ * - Pass 1: 2048x2048 Directional Sun Shadow Map Depth FBO
+ * - Pass 2: Main 317HD Scene FBO (3-vertex height-splatted terrain, Sobel normal mapping,
+ * 9-tap PCF soft shadows, 317HD water shader, dynamic point lights, distance fog)
+ * - Pass 3: Post-Process Bloom + Tonemapping + Zero-Copy BGRA readout to DrawingArea.pixels
+ */
+public final class DesktopHd317Renderer implements HD317Pipeline.HdRendererBackend {
+
+ // OpenGL Constants
+ private static final int GL_DEPTH_BUFFER_BIT = 0x00000100;
+ private static final int GL_COLOR_BUFFER_BIT = 0x00004000;
+ private static final int GL_TRIANGLES = 0x0004;
+ private static final int GL_TRIANGLE_STRIP = 0x0005;
+ private static final int GL_SRC_ALPHA = 0x0302;
+ private static final int GL_ONE_MINUS_SRC_ALPHA = 0x0303;
+ private static final int GL_NONE = 0;
+ private static final int GL_LEQUAL = 0x0203;
+ private static final int GL_DEPTH_TEST = 0x0B71;
+ private static final int GL_BLEND = 0x0BE2;
+ private static final int GL_TEXTURE_2D = 0x0DE1;
+ private static final int GL_UNSIGNED_BYTE = 0x1401;
+ private static final int GL_UNSIGNED_INT = 0x1405;
+ private static final int GL_FLOAT = 0x1406;
+ private static final int GL_DEPTH_COMPONENT = 0x1902;
+ private static final int GL_RGBA = 0x1908;
+ private static final int GL_NEAREST = 0x2600;
+ private static final int GL_LINEAR = 0x2601;
+ private static final int GL_LINEAR_MIPMAP_LINEAR = 0x2703;
+ private static final int GL_TEXTURE_MAG_FILTER = 0x2800;
+ private static final int GL_TEXTURE_MIN_FILTER = 0x2801;
+ private static final int GL_TEXTURE_WRAP_S = 0x2802;
+ private static final int GL_TEXTURE_WRAP_T = 0x2803;
+ private static final int GL_REPEAT = 0x2901;
+ private static final int GL_POLYGON_OFFSET_FILL = 0x8037;
+ private static final int GL_RGBA8 = 0x8058;
+ private static final int GL_CLAMP_TO_EDGE = 0x812F;
+ private static final int GL_DEPTH_COMPONENT24 = 0x81A6;
+ private static final int GL_TEXTURE0 = 0x84C0;
+ private static final int GL_TEXTURE1 = 0x84C1;
+ private static final int GL_TEXTURE2 = 0x84C2;
+ private static final int GL_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE;
+ private static final int GL_TEXTURE_COMPARE_MODE = 0x884C;
+ private static final int GL_TEXTURE_COMPARE_FUNC = 0x884D;
+ private static final int GL_COMPARE_REF_TO_TEXTURE = 0x884E;
+ private static final int GL_ARRAY_BUFFER = 0x8892;
+ private static final int GL_STREAM_DRAW = 0x88E0;
+ private static final int GL_STATIC_DRAW = 0x88E4;
+ private static final int GL_FRAGMENT_SHADER = 0x8B30;
+ private static final int GL_VERTEX_SHADER = 0x8B31;
+ private static final int GL_COMPILE_STATUS = 0x8B81;
+ private static final int GL_LINK_STATUS = 0x8B82;
+ private static final int GL_TEXTURE_2D_ARRAY = 0x8C1A;
+ private static final int GL_FRAMEBUFFER = 0x8D40;
+ private static final int GL_RENDERBUFFER = 0x8D41;
+ private static final int GL_COLOR_ATTACHMENT0 = 0x8CE0;
+ private static final int GL_DEPTH_ATTACHMENT = 0x8D00;
+
+ private int shadowMapSize = 2048;
+
+ // JNA Interfaces for EGL + GLES3 (Linux / macOS / ANGLE)
+ public interface EGLLibrary extends Library {
+ Pointer eglGetDisplay(Pointer display_id);
+ Pointer eglGetPlatformDisplay(int platform, Pointer native_display, Pointer attrib_list);
+ boolean eglInitialize(Pointer dpy, int[] major, int[] minor);
+ boolean eglChooseConfig(Pointer dpy, int[] attrib_list, Pointer[] configs, int config_size, int[] num_config);
+ Pointer eglCreateContext(Pointer dpy, Pointer config, Pointer share_context, int[] attrib_list);
+ Pointer eglCreatePbufferSurface(Pointer dpy, Pointer config, int[] attrib_list);
+ boolean eglMakeCurrent(Pointer dpy, Pointer draw, Pointer read, Pointer ctx);
+ }
+
+ public interface GLES3Library extends Library {
+ void glActiveTexture(int texture);
+ void glAttachShader(int program, int shader);
+ void glBindBuffer(int target, int buffer);
+ void glBindFramebuffer(int target, int framebuffer);
+ void glBindRenderbuffer(int target, int renderbuffer);
+ void glBindTexture(int target, int texture);
+ void glBindVertexArray(int array);
+ void glBlendFunc(int sfactor, int dfactor);
+ void glBufferData(int target, long size, Buffer data, int usage);
+ void glBufferSubData(int target, long offset, long size, Buffer data);
+ void glClear(int mask);
+ void glClearColor(float red, float green, float blue, float alpha);
+ void glCompileShader(int shader);
+ int glCreateProgram();
+ int glCreateShader(int type);
+ void glDeleteFramebuffers(int n, int[] framebuffers);
+ void glDeleteProgram(int program);
+ void glDeleteRenderbuffers(int n, int[] renderbuffers);
+ void glDeleteShader(int shader);
+ void glDeleteTextures(int n, int[] textures);
+ void glDepthFunc(int func);
+ void glDepthMask(boolean flag);
+ void glDisable(int cap);
+ void glDisableVertexAttribArray(int index);
+ void glDrawArrays(int mode, int first, int count);
+ void glDrawBuffers(int n, int[] bufs);
+ void glEnable(int cap);
+ void glEnableVertexAttribArray(int index);
+ void glFramebufferRenderbuffer(int target, int attachment, int renderbuffertarget, int renderbuffer);
+ void glFramebufferTexture2D(int target, int attachment, int textarget, int texture, int level);
+ void glGenBuffers(int n, int[] buffers);
+ void glGenFramebuffers(int n, int[] framebuffers);
+ void glGenRenderbuffers(int n, int[] renderbuffers);
+ void glGenTextures(int n, int[] textures);
+ void glGenVertexArrays(int n, int[] arrays);
+ void glGenerateMipmap(int target);
+ void glGetProgramInfoLog(int program, int bufSize, int[] length, byte[] infoLog);
+ void glGetProgramiv(int program, int pname, int[] params);
+ void glGetShaderInfoLog(int shader, int bufSize, int[] length, byte[] infoLog);
+ void glGetShaderiv(int shader, int pname, int[] params);
+ int glGetUniformLocation(int program, String name);
+ void glLinkProgram(int program);
+ void glPolygonOffset(float factor, float units);
+ void glReadBuffer(int src);
+ void glReadPixels(int x, int y, int width, int height, int format, int type, Buffer pixels);
+ void glRenderbufferStorage(int target, int internalformat, int width, int height);
+ void glShaderSource(int shader, int count, String[] string, int[] length);
+ void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, Buffer pixels);
+ void glTexImage3D(int target, int level, int internalformat, int width, int height, int depth, int border, int format, int type, Buffer pixels);
+ void glTexParameterf(int target, int pname, float param);
+ void glTexParameteri(int target, int pname, int param);
+ void glUniform1f(int location, float v0);
+ void glUniform1i(int location, int v0);
+ void glUniform2f(int location, float v0, float v1);
+ void glUniform3f(int location, float v0, float v1, float v2);
+ void glUniform4fv(int location, int count, float[] value);
+ void glUniformMatrix4fv(int location, int count, boolean transpose, float[] value);
+ void glUseProgram(int program);
+ void glVertexAttribPointer(int index, int size, int type, boolean normalized, int stride, Pointer pointer);
+ void glViewport(int x, int y, int width, int height);
+ }
+
+ // JNA Interfaces for Windows WGL (opengl32.dll / gdi32.dll / user32.dll)
+ public static class PIXELFORMATDESCRIPTOR extends Structure {
+ public short nSize;
+ public short nVersion;
+ public int dwFlags;
+ public byte iPixelType;
+ public byte cColorBits;
+ public byte cRedBits, cRedShift, cGreenBits, cGreenShift, cBlueBits, cBlueShift, cAlphaBits, cAlphaShift;
+ public byte cAccumBits, cAccumRedBits, cAccumGreenBits, cAccumBlueBits, cAccumAlphaBits;
+ public byte cDepthBits;
+ public byte cStencilBits;
+ public byte cAuxBuffers;
+ public byte iLayerType;
+ public byte bReserved;
+ public int dwLayerMask, dwVisibleMask, dwDamageMask;
+
+ @Override
+ protected List getFieldOrder() {
+ return Arrays.asList(
+ "nSize", "nVersion", "dwFlags", "iPixelType", "cColorBits",
+ "cRedBits", "cRedShift", "cGreenBits", "cGreenShift", "cBlueBits", "cBlueShift", "cAlphaBits", "cAlphaShift",
+ "cAccumBits", "cAccumRedBits", "cAccumGreenBits", "cAccumBlueBits", "cAccumAlphaBits",
+ "cDepthBits", "cStencilBits", "cAuxBuffers", "iLayerType", "bReserved",
+ "dwLayerMask", "dwVisibleMask", "dwDamageMask"
+ );
+ }
+ }
+
+ public interface User32Library extends Library {
+ Pointer CreateWindowExA(int dwExStyle, String lpClassName, String lpWindowName, int dwStyle,
+ int x, int y, int nWidth, int nHeight,
+ Pointer hWndParent, Pointer hMenu, Pointer hInstance, Pointer lpParam);
+ Pointer GetDC(Pointer hWnd);
+ }
+
+ public interface Gdi32Library extends Library {
+ int ChoosePixelFormat(Pointer hdc, PIXELFORMATDESCRIPTOR ppfd);
+ boolean SetPixelFormat(Pointer hdc, int format, PIXELFORMATDESCRIPTOR ppfd);
+ }
+
+ public interface WglLibrary extends Library {
+ Pointer wglCreateContext(Pointer hdc);
+ boolean wglMakeCurrent(Pointer hdc, Pointer hglrc);
+ Pointer wglGetProcAddress(String lpszProc);
+ }
+
+ private final HdProceduralGenerator procGen = new HdProceduralGenerator();
+ private final HdSceneUploader sceneUploader = new HdSceneUploader();
+
+ // Context & backend state
+ private EGLLibrary eglLib = null;
+ private GLES3Library gles = null;
+ private WglLibrary wglLib = null;
+ private NativeLibrary opengl32Lib = null;
+ private final Map wglFunctions = new HashMap<>();
+ private boolean useDesktopGlsl330 = false;
+
+ private Pointer eglDisplay = Pointer.NULL;
+ private Pointer eglContext = Pointer.NULL;
+ private Pointer eglSurface = Pointer.NULL;
+ private Pointer wglHdc = Pointer.NULL;
+ private Pointer wglContext = Pointer.NULL;
+
+ private Thread boundThread = null;
+ private boolean glInitialized = false;
+ private boolean glFailed = false;
+ private boolean materialsInitialized = false;
+
+ // Textures & Shader Programs
+ private int diffuseArrayTex = 0;
+ private int normalArrayTex = 0;
+ private int shadowProgram = 0;
+ private int sceneProgram = 0;
+ private int postProgram = 0;
+ private int vaoId = 0;
+
+ // Uniform Locations - Shadow Program
+ private int uShadowLightViewProj = -1;
+ private int uShadowDiffuseArray = -1;
+
+ // Uniform Locations - Scene Program
+ private int uSceneViewProj = -1;
+ private int uSceneLightViewProj = -1;
+ private int uSceneDiffuseArray = -1;
+ private int uSceneNormalArray = -1;
+ private int uSceneShadowMap = -1;
+ private int uSceneCameraPos = -1;
+ private int uSceneSunDir = -1;
+ private int uSceneSunColor = -1;
+ private int uSceneAmbientColor = -1;
+ private int uSceneSkyColor = -1;
+ private int uSceneFogColor = -1;
+ private int uSceneFogMin = -1;
+ private int uSceneFogMax = -1;
+ private int uSceneTime = -1;
+ private int uSceneShadowTexelSize = -1;
+ private int uSceneShadowsEnabled = -1;
+ private int uSceneShadowSoftPcf = -1;
+ private int uSceneGroundTextures = -1;
+ private int uSceneNormalMapping = -1;
+ private int uSceneWaterShader = -1;
+ private int uSceneSaturation = -1;
+ private int uSceneBrightness = -1;
+ private int uSceneLightCount = -1;
+ private int uSceneLightPosRad = -1;
+ private int uSceneLightColorInt = -1;
+
+ // Uniform Locations - Post Program
+ private int uPostSceneTex = -1;
+ private int uPostTexelSize = -1;
+
+ // GPU Buffers & Framebuffers
+ private final int[] terrainVbos = new int[4];
+ private final int[] terrainBucketCounts = new int[4];
+ private final int[][] staticOpaqueVbos = new int[4][HdSceneUploader.CHUNKS_PER_PLANE];
+ private final int[][] staticOpaqueCounts = new int[4][HdSceneUploader.CHUNKS_PER_PLANE];
+ private final int[][] staticTransVbos = new int[4][HdSceneUploader.CHUNKS_PER_PLANE];
+ private final int[][] staticTransCounts = new int[4][HdSceneUploader.CHUNKS_PER_PLANE];
+ private final int[][] uploadedChunkGen = new int[4][HdSceneUploader.CHUNKS_PER_PLANE];
+ private final boolean[] chunkVisible = new boolean[HdSceneUploader.CHUNKS_PER_PLANE];
+ private int uploadedTerrainGenId = -1;
+ private int sceneVbo = 0;
+ private int transVbo = 0;
+ private int quadVbo = 0;
+ private long sceneVboCapacity = 0;
+ private long transVboCapacity = 0;
+ private int shadowFbo = 0;
+ private int shadowDepthTex = 0;
+ private int sceneFbo = 0;
+ private int sceneColorTex = 0;
+ private int sceneDepthRbo = 0;
+ private int postFbo = 0;
+ private int postColorTex = 0;
+
+ private int fboWidth = 0;
+ private int fboHeight = 0;
+ private ByteBuffer readbackByteBuffer = null;
+ private IntBuffer readbackIntBuffer = null;
+
+ // Camera & Environment State
+ private int camX, camY, camZ, camPitch, camYaw;
+ private final float[] viewProjMatrix = new float[16];
+ private final float[] lightViewMatrix = new float[16];
+ private final float[] lightProjMatrix = new float[16];
+ private final float[] lightViewProjMatrix = new float[16];
+
+ private final float[] sunDir = {-0.52f, -0.74f, -0.42f};
+ private final float[] sunColor = {0.88f, 0.84f, 0.76f};
+ private final float[] ambientColor = {0.46f, 0.52f, 0.62f};
+ private final float[] skyColor = {0.62f, 0.78f, 0.94f};
+ private final float[] fogColor = {0.68f, 0.81f, 0.94f};
+ private float fogMin = 2100.0f;
+ private float fogMax = 3500.0f;
+
+ private static final int MAX_ACTIVE_LIGHTS = 16;
+ private final float[] activeLightPosRad = new float[MAX_ACTIVE_LIGHTS * 4];
+ private final float[] activeLightColorInt = new float[MAX_ACTIVE_LIGHTS * 4];
+ private int activeLightCount = 0;
+
+ private final long startTimeMs = System.currentTimeMillis();
+ private boolean sceneLoaded = false;
+ private Game lastGame = null;
+ private ObjectManager lastObjectManager = null;
+ private WorldController lastWorldController = null;
+
+ public DesktopHd317Renderer() {
+ float len = (float) Math.sqrt(sunDir[0] * sunDir[0] + sunDir[1] * sunDir[1] + sunDir[2] * sunDir[2]);
+ sunDir[0] /= len;
+ sunDir[1] /= len;
+ sunDir[2] /= len;
+ }
+
+ @Override
+ public boolean isGpuReady() {
+ return !glFailed;
+ }
+
+ @Override
+ public synchronized void onSceneLoad(Game game, ObjectManager objectManager, WorldController worldController) {
+ this.lastGame = game;
+ this.lastObjectManager = objectManager;
+ this.lastWorldController = worldController;
+ try {
+ procGen.generateSceneData(game, objectManager, worldController);
+ sceneUploader.setSceneContext(procGen, worldController);
+ sceneLoaded = true;
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ }
+
+ @Override
+ public void beginFrame(Game game, int xCam, int yCam, int zCam, int pitch, int yaw) {
+ if (glFailed) return;
+
+ if (!sceneLoaded && game != null && game.worldController != null) {
+ procGen.generateSceneData(game, lastObjectManager, game.worldController);
+ sceneUploader.setSceneContext(procGen, game.worldController);
+ sceneLoaded = true;
+ }
+
+ this.camX = xCam;
+ this.camY = yCam;
+ this.camZ = zCam;
+ this.camPitch = pitch;
+ this.camYaw = yaw;
+
+ updateEnvironmentProfile(game);
+ sceneUploader.resetFrame();
+ }
+
+ @Override
+ public void drawSimpleTile(Class43 tile, int plane, int tileX, int tileZ) {
+ if (glFailed) return;
+ sceneUploader.appendSimpleTile(tile, plane, tileX, tileZ);
+ }
+
+ @Override
+ public void drawShapedTile(Class40 tile, int plane, int tileX, int tileZ) {
+ if (glFailed) return;
+ sceneUploader.appendShapedTile(tile, plane, tileX, tileZ);
+ }
+
+ @Override
+ public void drawModel(Model model, int orientation, int sinPitch, int cosPitch, int sinYaw, int cosYaw,
+ int relX, int relY, int relZ, int uid) {
+ if (glFailed) return;
+ sceneUploader.appendModel(model, orientation, relX, relY, relZ, uid);
+ }
+
+ @Override
+ public void endFrame(int[] dstPixels, int width, int height) {
+ if (glFailed || dstPixels == null || width <= 0 || height <= 0) return;
+ if (dstPixels.length < width * height) return;
+
+ if (!ensureGlContext()) {
+ return;
+ }
+
+ if (!materialsInitialized) {
+ initMaterials();
+ }
+
+ ensureFramebuffers(width, height);
+
+ this.camX = WorldController.anInt455;
+ this.camY = WorldController.anInt456;
+ this.camZ = WorldController.anInt457;
+
+ if (vaoId != 0) {
+ gles.glBindVertexArray(vaoId);
+ }
+
+ sceneUploader.rebuildDirtyChunks();
+
+ int curTerrainGen = sceneUploader.getTerrainGenerationId();
+ if (curTerrainGen != uploadedTerrainGenId) {
+ for (int b = 0; b < 4; b++) {
+ int cnt = sceneUploader.getStaticTerrainVertexCount(b);
+ terrainBucketCounts[b] = cnt;
+ if (cnt > 0) {
+ FloatBuffer tb = sceneUploader.prepareStaticTerrainBucket(b);
+ if (tb != null) {
+ gles.glBindBuffer(GL_ARRAY_BUFFER, terrainVbos[b]);
+ gles.glBufferData(GL_ARRAY_BUFFER, (long) cnt * HdSceneUploader.BYTES_PER_VERTEX, tb, GL_STATIC_DRAW);
+ }
+ }
+ }
+ uploadedTerrainGenId = curTerrainGen;
+ }
+
+ for (int b = 0; b < 4; b++) {
+ for (int c = 0; c < HdSceneUploader.CHUNKS_PER_PLANE; c++) {
+ int gen = sceneUploader.getStaticSceneryChunkGen(b, c);
+ if (gen != uploadedChunkGen[b][c]) {
+ uploadedChunkGen[b][c] = gen;
+ int soCnt = sceneUploader.getStaticSceneryOpaqueCount(b, c);
+ staticOpaqueCounts[b][c] = soCnt;
+ if (soCnt > 0) {
+ FloatBuffer sb = sceneUploader.prepareStaticBuffer(sceneUploader.getStaticSceneryOpaqueBucket(b, c), soCnt);
+ if (sb != null) {
+ gles.glBindBuffer(GL_ARRAY_BUFFER, staticOpaqueVbos[b][c]);
+ gles.glBufferData(GL_ARRAY_BUFFER, (long) soCnt * HdSceneUploader.BYTES_PER_VERTEX, sb, GL_STATIC_DRAW);
+ }
+ }
+ int stCnt = sceneUploader.getStaticSceneryTransCount(b, c);
+ staticTransCounts[b][c] = stCnt;
+ if (stCnt > 0) {
+ FloatBuffer stb = sceneUploader.prepareStaticBuffer(sceneUploader.getStaticSceneryTransBucket(b, c), stCnt);
+ if (stb != null) {
+ gles.glBindBuffer(GL_ARRAY_BUFFER, staticTransVbos[b][c]);
+ gles.glBufferData(GL_ARRAY_BUFFER, (long) stCnt * HdSceneUploader.BYTES_PER_VERTEX, stb, GL_STATIC_DRAW);
+ }
+ }
+ }
+ }
+ }
+
+ int opaqueCount = sceneUploader.getOpaqueVertexCount();
+ int transCount = sceneUploader.getTransVertexCount();
+ if (opaqueCount > 0) {
+ FloatBuffer vb = sceneUploader.prepareOpaqueBuffer();
+ sceneVboCapacity = uploadStreamVbo(sceneVbo, sceneVboCapacity, (long) opaqueCount * HdSceneUploader.BYTES_PER_VERTEX, vb);
+ }
+ if (transCount > 0) {
+ FloatBuffer tvb = sceneUploader.prepareTransBuffer();
+ transVboCapacity = uploadStreamVbo(transVbo, transVboCapacity, (long) transCount * HdSceneUploader.BYTES_PER_VERTEX, tvb);
+ }
+
+ computeCameraAndLightMatrices(width, height);
+ selectActiveLights();
+
+ boolean shadowsOn = HD317Pipeline.cfgShadowsEnabled;
+ int desiredShadowSize = HD317Pipeline.cfgShadowResolution;
+ if (shadowsOn && desiredShadowSize != shadowMapSize && (desiredShadowSize == 512 || desiredShadowSize == 1024 || desiredShadowSize == 2048)) {
+ shadowMapSize = desiredShadowSize;
+ gles.glBindTexture(GL_TEXTURE_2D, shadowDepthTex);
+ gles.glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24,
+ shadowMapSize, shadowMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, null);
+ }
+
+ int maxPlane = WorldController.hdMaxPlane;
+ float maxChunkDist = fogMax + HdSceneUploader.CHUNK_RADIUS;
+ float maxChunkDistSq = maxChunkDist * maxChunkDist;
+ boolean hasStaticOpaque = false;
+ boolean hasStaticTrans = false;
+ for (int c = 0; c < HdSceneUploader.CHUNKS_PER_PLANE; c++) {
+ int cx = c / HdSceneUploader.CHUNKS_PER_AXIS;
+ int cz = c % HdSceneUploader.CHUNKS_PER_AXIS;
+ float centerX = (cx * HdSceneUploader.CHUNK_TILE_SIZE + HdSceneUploader.CHUNK_TILE_SIZE * 0.5f) * 128.0f;
+ float centerZ = (cz * HdSceneUploader.CHUNK_TILE_SIZE + HdSceneUploader.CHUNK_TILE_SIZE * 0.5f) * 128.0f;
+ float dx = centerX - camX;
+ float dz = centerZ - camZ;
+ boolean vis = (dx * dx + dz * dz) <= maxChunkDistSq;
+ chunkVisible[c] = vis;
+ if (vis) {
+ for (int b = 0; b <= maxPlane; b++) {
+ if (staticOpaqueCounts[b][c] > 0) hasStaticOpaque = true;
+ if (staticTransCounts[b][c] > 0) hasStaticTrans = true;
+ }
+ }
+ }
+
+ // =====================================================================
+ // PASS 1: Directional Sun Shadow Map Depth Pass (Models Only)
+ // =====================================================================
+ if (shadowsOn && (opaqueCount > 0 || hasStaticOpaque)) {
+ gles.glBindFramebuffer(GL_FRAMEBUFFER, shadowFbo);
+ gles.glViewport(0, 0, shadowMapSize, shadowMapSize);
+ gles.glEnable(GL_DEPTH_TEST);
+ gles.glDepthFunc(GL_LEQUAL);
+ gles.glDepthMask(true);
+ gles.glDisable(GL_BLEND);
+ gles.glEnable(GL_POLYGON_OFFSET_FILL);
+ gles.glPolygonOffset(1.5f, 3.0f);
+ gles.glClear(GL_DEPTH_BUFFER_BIT);
+
+ gles.glUseProgram(shadowProgram);
+ gles.glUniformMatrix4fv(uShadowLightViewProj, 1, false, lightViewProjMatrix);
+
+ gles.glActiveTexture(GL_TEXTURE0);
+ gles.glBindTexture(GL_TEXTURE_2D_ARRAY, diffuseArrayTex);
+ gles.glUniform1i(uShadowDiffuseArray, 0);
+
+ for (int b = 0; b <= maxPlane; b++) {
+ for (int c = 0; c < HdSceneUploader.CHUNKS_PER_PLANE; c++) {
+ if (!chunkVisible[c]) continue;
+ int soCnt = staticOpaqueCounts[b][c];
+ if (soCnt > 0) {
+ gles.glBindBuffer(GL_ARRAY_BUFFER, staticOpaqueVbos[b][c]);
+ gles.glEnableVertexAttribArray(0);
+ gles.glVertexAttribPointer(0, 3, GL_FLOAT, false, HdSceneUploader.BYTES_PER_VERTEX, Pointer.createConstant(0));
+ gles.glEnableVertexAttribArray(2);
+ gles.glVertexAttribPointer(2, 2, GL_FLOAT, false, HdSceneUploader.BYTES_PER_VERTEX, Pointer.createConstant(6 * 4));
+ gles.glEnableVertexAttribArray(4);
+ gles.glVertexAttribPointer(4, 4, GL_FLOAT, false, HdSceneUploader.BYTES_PER_VERTEX, Pointer.createConstant(12 * 4));
+ gles.glDrawArrays(GL_TRIANGLES, 0, soCnt);
+ }
+ }
+ }
+ if (opaqueCount > 0) {
+ gles.glBindBuffer(GL_ARRAY_BUFFER, sceneVbo);
+ gles.glEnableVertexAttribArray(0);
+ gles.glVertexAttribPointer(0, 3, GL_FLOAT, false, HdSceneUploader.BYTES_PER_VERTEX, Pointer.createConstant(0));
+ gles.glEnableVertexAttribArray(2);
+ gles.glVertexAttribPointer(2, 2, GL_FLOAT, false, HdSceneUploader.BYTES_PER_VERTEX, Pointer.createConstant(6 * 4));
+ gles.glEnableVertexAttribArray(4);
+ gles.glVertexAttribPointer(4, 4, GL_FLOAT, false, HdSceneUploader.BYTES_PER_VERTEX, Pointer.createConstant(12 * 4));
+ gles.glDrawArrays(GL_TRIANGLES, 0, opaqueCount);
+ }
+
+ gles.glDisableVertexAttribArray(0);
+ gles.glDisableVertexAttribArray(2);
+ gles.glDisableVertexAttribArray(4);
+ gles.glDisable(GL_POLYGON_OFFSET_FILL);
+ }
+
+ // =====================================================================
+ // PASS 2: Main 317HD Scene Render Pass (Terrain + Models + Translucent)
+ // =====================================================================
+ gles.glBindFramebuffer(GL_FRAMEBUFFER, sceneFbo);
+ gles.glViewport(0, 0, width, height);
+ gles.glClearColor(fogColor[0], fogColor[1], fogColor[2], 0.0f);
+ gles.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ gles.glEnable(GL_DEPTH_TEST);
+ gles.glDepthFunc(GL_LEQUAL);
+ gles.glDepthMask(true);
+
+ boolean hasTerrain = false;
+ for (int b = 0; b <= maxPlane; b++) {
+ if (terrainBucketCounts[b] > 0) { hasTerrain = true; break; }
+ }
+
+ if (hasTerrain || hasStaticOpaque || hasStaticTrans || opaqueCount > 0 || transCount > 0) {
+ gles.glEnable(GL_BLEND);
+ gles.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+
+ gles.glUseProgram(sceneProgram);
+ gles.glUniformMatrix4fv(uSceneViewProj, 1, false, viewProjMatrix);
+ gles.glUniformMatrix4fv(uSceneLightViewProj, 1, false, lightViewProjMatrix);
+ gles.glUniform3f(uSceneCameraPos, (float) camX, (float) camY, (float) camZ);
+ gles.glUniform3f(uSceneSunDir, sunDir[0], sunDir[1], sunDir[2]);
+ gles.glUniform3f(uSceneSunColor, sunColor[0], sunColor[1], sunColor[2]);
+ gles.glUniform3f(uSceneAmbientColor, ambientColor[0], ambientColor[1], ambientColor[2]);
+ gles.glUniform3f(uSceneSkyColor, skyColor[0], skyColor[1], skyColor[2]);
+ gles.glUniform3f(uSceneFogColor, fogColor[0], fogColor[1], fogColor[2]);
+ gles.glUniform1f(uSceneFogMin, HD317Pipeline.cfgAtmosphericFog ? fogMin : 999999.0f);
+ gles.glUniform1f(uSceneFogMax, HD317Pipeline.cfgAtmosphericFog ? fogMax : 1000000.0f);
+ float timeSec = (System.currentTimeMillis() - startTimeMs) * 0.001f;
+ gles.glUniform1f(uSceneTime, timeSec);
+ gles.glUniform1f(uSceneShadowTexelSize, 1.0f / shadowMapSize);
+ gles.glUniform1i(uSceneShadowsEnabled, shadowsOn ? 1 : 0);
+ gles.glUniform1i(uSceneShadowSoftPcf, HD317Pipeline.cfgShadowSoftPcf ? 1 : 0);
+ gles.glUniform1i(uSceneGroundTextures, HD317Pipeline.cfgGroundTextures ? 1 : 0);
+ gles.glUniform1i(uSceneNormalMapping, HD317Pipeline.cfgNormalMapping ? 1 : 0);
+ gles.glUniform1i(uSceneWaterShader, HD317Pipeline.cfgWaterShader ? 1 : 0);
+ gles.glUniform1f(uSceneSaturation, HD317Pipeline.cfgSaturation);
+ gles.glUniform1f(uSceneBrightness, HD317Pipeline.cfgBrightness);
+
+ gles.glUniform1i(uSceneLightCount, activeLightCount);
+ if (activeLightCount > 0) {
+ gles.glUniform4fv(uSceneLightPosRad, activeLightCount, activeLightPosRad);
+ gles.glUniform4fv(uSceneLightColorInt, activeLightCount, activeLightColorInt);
+ }
+
+ gles.glActiveTexture(GL_TEXTURE0);
+ gles.glBindTexture(GL_TEXTURE_2D_ARRAY, diffuseArrayTex);
+ gles.glUniform1i(uSceneDiffuseArray, 0);
+
+ gles.glActiveTexture(GL_TEXTURE1);
+ gles.glBindTexture(GL_TEXTURE_2D_ARRAY, normalArrayTex);
+ gles.glUniform1i(uSceneNormalArray, 1);
+
+ gles.glActiveTexture(GL_TEXTURE2);
+ gles.glBindTexture(GL_TEXTURE_2D, shadowDepthTex);
+ gles.glUniform1i(uSceneShadowMap, 2);
+
+ gles.glDepthMask(true);
+ for (int b = 0; b <= maxPlane; b++) {
+ int cnt = terrainBucketCounts[b];
+ if (cnt > 0) {
+ gles.glBindBuffer(GL_ARRAY_BUFFER, terrainVbos[b]);
+ bindSceneVertexAttribs();
+ gles.glDrawArrays(GL_TRIANGLES, 0, cnt);
+ }
+ }
+
+ for (int b = 0; b <= maxPlane; b++) {
+ for (int c = 0; c < HdSceneUploader.CHUNKS_PER_PLANE; c++) {
+ if (!chunkVisible[c]) continue;
+ int soCnt = staticOpaqueCounts[b][c];
+ if (soCnt > 0) {
+ gles.glBindBuffer(GL_ARRAY_BUFFER, staticOpaqueVbos[b][c]);
+ bindSceneVertexAttribs();
+ gles.glDrawArrays(GL_TRIANGLES, 0, soCnt);
+ }
+ }
+ }
+
+ if (opaqueCount > 0) {
+ gles.glBindBuffer(GL_ARRAY_BUFFER, sceneVbo);
+ bindSceneVertexAttribs();
+ gles.glDepthMask(true);
+ gles.glDrawArrays(GL_TRIANGLES, 0, opaqueCount);
+ }
+
+ for (int b = 0; b <= maxPlane; b++) {
+ for (int c = 0; c < HdSceneUploader.CHUNKS_PER_PLANE; c++) {
+ if (!chunkVisible[c]) continue;
+ int stCnt = staticTransCounts[b][c];
+ if (stCnt > 0) {
+ gles.glBindBuffer(GL_ARRAY_BUFFER, staticTransVbos[b][c]);
+ bindSceneVertexAttribs();
+ gles.glDepthMask(false);
+ gles.glDrawArrays(GL_TRIANGLES, 0, stCnt);
+ gles.glDepthMask(true);
+ }
+ }
+ }
+
+ if (transCount > 0) {
+ gles.glBindBuffer(GL_ARRAY_BUFFER, transVbo);
+ bindSceneVertexAttribs();
+ gles.glDepthMask(false);
+ gles.glDrawArrays(GL_TRIANGLES, 0, transCount);
+ gles.glDepthMask(true);
+ }
+
+ unbindSceneVertexAttribs();
+ }
+
+ // =====================================================================
+ // PASS 3: Post-Process Bloom + Tonemap + Zero-Copy BGRA Readout
+ // =====================================================================
+ gles.glBindFramebuffer(GL_FRAMEBUFFER, postFbo);
+ gles.glViewport(0, 0, width, height);
+ gles.glDisable(GL_DEPTH_TEST);
+ gles.glDisable(GL_BLEND);
+
+ gles.glUseProgram(postProgram);
+ gles.glActiveTexture(GL_TEXTURE0);
+ gles.glBindTexture(GL_TEXTURE_2D, sceneColorTex);
+ gles.glUniform1i(uPostSceneTex, 0);
+ gles.glUniform2f(uPostTexelSize, 1.0f / width, 1.0f / height);
+
+ gles.glBindBuffer(GL_ARRAY_BUFFER, quadVbo);
+ gles.glEnableVertexAttribArray(0);
+ gles.glVertexAttribPointer(0, 2, GL_FLOAT, false, 8, Pointer.createConstant(0));
+ gles.glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
+ gles.glDisableVertexAttribArray(0);
+
+ ((Buffer) readbackByteBuffer).position(0);
+ gles.glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, readbackByteBuffer);
+ ((Buffer) readbackIntBuffer).position(0);
+ readbackIntBuffer.get(dstPixels, 0, width * height);
+ }
+
+ @Override
+ public void onStaticChunkInvalidated(int tileX, int tileZ) {
+ sceneUploader.invalidateChunk(tileX, tileZ);
+ }
+
+ @Override
+ public void onToggle(boolean enabled) {
+ if (enabled && !sceneLoaded && lastWorldController != null) {
+ onSceneLoad(lastGame, lastObjectManager, lastWorldController);
+ }
+ }
+
+ private long uploadStreamVbo(int vbo, long currentCapacity, long requiredBytes, FloatBuffer buf) {
+ gles.glBindBuffer(GL_ARRAY_BUFFER, vbo);
+ if (requiredBytes > currentCapacity) {
+ long newCap = Math.max(requiredBytes, currentCapacity + (currentCapacity >> 1));
+ gles.glBufferData(GL_ARRAY_BUFFER, newCap, null, GL_STREAM_DRAW);
+ currentCapacity = newCap;
+ }
+ gles.glBufferSubData(GL_ARRAY_BUFFER, 0, requiredBytes, buf);
+ return currentCapacity;
+ }
+
+ private void bindSceneVertexAttribs() {
+ final int stride = HdSceneUploader.BYTES_PER_VERTEX;
+ gles.glEnableVertexAttribArray(0);
+ gles.glVertexAttribPointer(0, 3, GL_FLOAT, false, stride, Pointer.createConstant(0));
+ gles.glEnableVertexAttribArray(1);
+ gles.glVertexAttribPointer(1, 3, GL_FLOAT, false, stride, Pointer.createConstant(3 * 4));
+ gles.glEnableVertexAttribArray(2);
+ gles.glVertexAttribPointer(2, 2, GL_FLOAT, false, stride, Pointer.createConstant(6 * 4));
+ gles.glEnableVertexAttribArray(3);
+ gles.glVertexAttribPointer(3, 4, GL_FLOAT, false, stride, Pointer.createConstant(8 * 4));
+ gles.glEnableVertexAttribArray(4);
+ gles.glVertexAttribPointer(4, 4, GL_FLOAT, false, stride, Pointer.createConstant(12 * 4));
+ }
+
+ private void unbindSceneVertexAttribs() {
+ gles.glDisableVertexAttribArray(0);
+ gles.glDisableVertexAttribArray(1);
+ gles.glDisableVertexAttribArray(2);
+ gles.glDisableVertexAttribArray(3);
+ gles.glDisableVertexAttribArray(4);
+ }
+
+ private void computeCameraAndLightMatrices(int width, int height) {
+ double yawRad = (camYaw & 2047) * (2.0 * Math.PI / 2048.0);
+ double pitchRad = (camPitch & 2047) * (2.0 * Math.PI / 2048.0);
+
+ float sinY = (float) Math.sin(yawRad);
+ float cosY = (float) Math.cos(yawRad);
+ float sinP = (float) Math.sin(pitchRad);
+ float cosP = (float) Math.cos(pitchRad);
+
+ float r0x = cosY, r0y = 0.0f, r0z = sinY;
+ float r1x = sinP * sinY, r1y = cosP, r1z = -sinP * cosY;
+ float r2x = -cosP * sinY, r2y = sinP, r2z = cosP * cosY;
+
+ float tx = -(r0x * camX + r0y * camY + r0z * camZ);
+ float ty = -(r1x * camX + r1y * camY + r1z * camZ);
+ float tz = -(r2x * camX + r2y * camY + r2z * camZ);
+
+ float cx = Texture.textureInt1;
+ float cy = Texture.textureInt2;
+ float fov = 512.0f;
+
+ float sx = (2.0f * fov) / width;
+ float ox = (2.0f * cx / width) - 1.0f;
+ float sy = (-2.0f * fov) / height;
+ float oy = 1.0f - (2.0f * cy / height);
+
+ float near = 50.0f;
+ float far = Math.max(5400.0f, fogMax + 600.0f);
+ float sz = (far + near) / (far - near);
+ float oz = -(2.0f * far * near) / (far - near);
+
+ viewProjMatrix[0] = sx * r0x + ox * r2x;
+ viewProjMatrix[4] = sx * r0y + ox * r2y;
+ viewProjMatrix[8] = sx * r0z + ox * r2z;
+ viewProjMatrix[12] = sx * tx + ox * tz;
+
+ viewProjMatrix[1] = sy * r1x + oy * r2x;
+ viewProjMatrix[5] = sy * r1y + oy * r2y;
+ viewProjMatrix[9] = sy * r1z + oy * r2z;
+ viewProjMatrix[13] = sy * ty + oy * tz;
+
+ viewProjMatrix[2] = sz * r2x;
+ viewProjMatrix[6] = sz * r2y;
+ viewProjMatrix[10] = sz * r2z;
+ viewProjMatrix[14] = sz * tz + oz;
+
+ viewProjMatrix[3] = r2x;
+ viewProjMatrix[7] = r2y;
+ viewProjMatrix[11] = r2z;
+ viewProjMatrix[15] = tz;
+
+ float focusDist = 800.0f + Math.max(0, Game.zoom) * 140.0f;
+ float centerX = (float) Math.floor((camX + r2x * focusDist) / 16.0f) * 16.0f;
+ float centerY = (float) Math.floor((camY + r2y * focusDist) / 16.0f) * 16.0f;
+ float centerZ = (float) Math.floor((camZ + r2z * focusDist) / 16.0f) * 16.0f;
+
+ float eyeX = centerX + sunDir[0] * 3600.0f;
+ float eyeY = centerY + sunDir[1] * 3600.0f;
+ float eyeZ = centerZ + sunDir[2] * 3600.0f;
+
+ HD317Pipeline.setLookAtM(lightViewMatrix, 0, eyeX, eyeY, eyeZ, centerX, centerY, centerZ, 0.0f, -1.0f, 0.0f);
+ float orthoHalf = 2600.0f + Math.max(0, Game.zoom) * 180.0f;
+ HD317Pipeline.orthoM(lightProjMatrix, 0, -orthoHalf, orthoHalf, -orthoHalf, orthoHalf, 100.0f, 7200.0f);
+ HD317Pipeline.multiplyMM(lightViewProjMatrix, 0, lightProjMatrix, 0, lightViewMatrix, 0);
+ }
+
+ private void selectActiveLights() {
+ activeLightCount = 0;
+ if (!HD317Pipeline.cfgDynamicLights) return;
+ int total = procGen.sceneLightCount;
+ if (total <= 0) return;
+
+ float timeSec = (System.currentTimeMillis() - startTimeMs) * 0.001f;
+ float flicker = 0.94f + 0.06f * (float) Math.sin(timeSec * 9.0);
+
+ for (int i = 0; i < total && activeLightCount < MAX_ACTIVE_LIGHTS; i++) {
+ int src = i * 4;
+ float lx = procGen.sceneLightPosRad[src];
+ float ly = procGen.sceneLightPosRad[src + 1];
+ float lz = procGen.sceneLightPosRad[src + 2];
+ float dx = lx - camX;
+ float dz = lz - camZ;
+ if (dx * dx + dz * dz < 3200.0f * 3200.0f) {
+ int dst = activeLightCount * 4;
+ activeLightPosRad[dst] = lx;
+ activeLightPosRad[dst + 1] = ly;
+ activeLightPosRad[dst + 2] = lz;
+ activeLightPosRad[dst + 3] = procGen.sceneLightPosRad[src + 3];
+
+ activeLightColorInt[dst] = procGen.sceneLightColorInt[src];
+ activeLightColorInt[dst + 1] = procGen.sceneLightColorInt[src + 1];
+ activeLightColorInt[dst + 2] = procGen.sceneLightColorInt[src + 2];
+ activeLightColorInt[dst + 3] = procGen.sceneLightColorInt[src + 3] * flicker;
+ activeLightCount++;
+ }
+ }
+ }
+
+ private void updateEnvironmentProfile(Game game) {
+ float pX = 52.0f * 128.0f;
+ float pZ = 52.0f * 128.0f;
+ if (game != null && game.myPlayer != null) {
+ pX = game.myPlayer.x;
+ pZ = game.myPlayer.y;
+ }
+ float camDistToPlayer = (float) Math.hypot(camX - pX, camZ - pZ);
+
+ float baseDist = WorldController.drawDistance * 144.0f;
+ fogMax = Math.max(4800.0f, baseDist + camDistToPlayer + Math.max(0, Game.zoom) * 200.0f);
+ fogMin = fogMax * 0.75f;
+
+ int worldX = 3222;
+ int worldY = 3218;
+ if (game != null && game.myPlayer != null) {
+ worldX = game.baseX + game.myPlayer.smallX[0];
+ worldY = game.baseY + game.myPlayer.smallY[0];
+ }
+
+ if (worldY >= 6000) {
+ if ((worldX >= 2360 && worldX <= 2500 && worldY >= 5000 && worldY <= 5200)
+ || (worldX >= 2800 && worldX <= 2900 && worldY >= 9500)) {
+ setColors(1.10f, 0.55f, 0.28f, 0.52f, 0.24f, 0.16f, 0.34f, 0.12f, 0.06f);
+ fogMin = fogMax * 0.55f;
+ } else {
+ setColors(0.75f, 0.74f, 0.72f, 0.38f, 0.42f, 0.50f, 0.10f, 0.12f, 0.16f);
+ fogMin = fogMax * 0.60f;
+ }
+ } else if (worldY >= 3520 && worldY <= 4000) {
+ setColors(0.82f, 0.74f, 0.68f, 0.44f, 0.40f, 0.42f, 0.25f, 0.20f, 0.20f);
+ } else if (worldX >= 3400 && worldX <= 3600 && worldY >= 3150 && worldY <= 3550) {
+ setColors(0.78f, 0.84f, 0.72f, 0.38f, 0.48f, 0.42f, 0.22f, 0.28f, 0.23f);
+ } else {
+ setColors(1.12f, 1.01f, 0.86f, 0.48f, 0.57f, 0.70f, 0.66f, 0.79f, 0.92f);
+ }
+ }
+
+ private void setColors(float sr, float sg, float sb, float ar, float ag, float ab, float fr, float fg, float fb) {
+ sunColor[0] = sr; sunColor[1] = sg; sunColor[2] = sb;
+ ambientColor[0] = ar; ambientColor[1] = ag; ambientColor[2] = ab;
+ fogColor[0] = fr; fogColor[1] = fg; fogColor[2] = fb;
+ skyColor[0] = fr; skyColor[1] = fg; skyColor[2] = fb;
+ }
+
+ private boolean ensureGlContext() {
+ Thread current = Thread.currentThread();
+ if (glInitialized && boundThread == current) {
+ return true;
+ }
+ try {
+ if (Platform.isWindows()) {
+ if (!ensureWglContext()) {
+ glFailed = true;
+ return false;
+ }
+ } else {
+ if (!ensureEglContext()) {
+ glFailed = true;
+ return false;
+ }
+ }
+
+ boundThread = current;
+ if (!glInitialized) {
+ initGlResources();
+ glInitialized = !glFailed;
+ }
+ return glInitialized;
+ } catch (Throwable t) {
+ t.printStackTrace();
+ glFailed = true;
+ return false;
+ }
+ }
+
+ private boolean ensureEglContext() {
+ if (eglLib == null) {
+ eglLib = (EGLLibrary) Native.loadLibrary("EGL", EGLLibrary.class);
+ gles = (GLES3Library) Native.loadLibrary("GLESv2", GLES3Library.class);
+ useDesktopGlsl330 = false;
+ }
+
+ if (eglDisplay == Pointer.NULL) {
+ int[] major = new int[1];
+ int[] minor = new int[1];
+
+ Pointer dpy = eglLib.eglGetDisplay(Pointer.NULL);
+ boolean ok = (dpy != Pointer.NULL) && eglLib.eglInitialize(dpy, major, minor);
+ if (!ok) {
+ // Fallback to EGL_PLATFORM_SURFACELESS_MESA (0x31DD)
+ dpy = eglLib.eglGetPlatformDisplay(0x31DD, Pointer.NULL, Pointer.NULL);
+ ok = (dpy != Pointer.NULL) && eglLib.eglInitialize(dpy, major, minor);
+ }
+ if (!ok) {
+ return false;
+ }
+ eglDisplay = dpy;
+
+ int[] configAttribs = {
+ 0x3040 /* EGL_RENDERABLE_TYPE */, 0x0040 /* EGL_OPENGL_ES3_BIT_KHR */,
+ 0x3033 /* EGL_SURFACE_TYPE */, 0x0001 /* EGL_PBUFFER_BIT */,
+ 0x3024 /* EGL_RED_SIZE */, 8,
+ 0x3023 /* EGL_GREEN_SIZE */, 8,
+ 0x3022 /* EGL_BLUE_SIZE */, 8,
+ 0x3021 /* EGL_ALPHA_SIZE */, 8,
+ 0x3025 /* EGL_DEPTH_SIZE */, 24,
+ 0x3038 /* EGL_NONE */
+ };
+ Pointer[] configs = new Pointer[1];
+ int[] numConfigs = new int[1];
+ if (!eglLib.eglChooseConfig(eglDisplay, configAttribs, configs, 1, numConfigs) || numConfigs[0] == 0) {
+ int[] fallbackAttribs = {
+ 0x3040 /* EGL_RENDERABLE_TYPE */, 0x0040 /* EGL_OPENGL_ES3_BIT_KHR */,
+ 0x3024 /* EGL_RED_SIZE */, 8,
+ 0x3023 /* EGL_GREEN_SIZE */, 8,
+ 0x3022 /* EGL_BLUE_SIZE */, 8,
+ 0x3025 /* EGL_DEPTH_SIZE */, 24,
+ 0x3038 /* EGL_NONE */
+ };
+ if (!eglLib.eglChooseConfig(eglDisplay, fallbackAttribs, configs, 1, numConfigs) || numConfigs[0] == 0) {
+ return false;
+ }
+ }
+
+ int[] ctxAttribs = {
+ 0x3098 /* EGL_CONTEXT_CLIENT_VERSION */, 3,
+ 0x3038 /* EGL_NONE */
+ };
+ eglContext = eglLib.eglCreateContext(eglDisplay, configs[0], Pointer.NULL, ctxAttribs);
+ if (eglContext == Pointer.NULL) {
+ return false;
+ }
+
+ int[] pbufAttribs = {
+ 0x3057 /* EGL_WIDTH */, 16,
+ 0x3056 /* EGL_HEIGHT */, 16,
+ 0x3038 /* EGL_NONE */
+ };
+ eglSurface = eglLib.eglCreatePbufferSurface(eglDisplay, configs[0], pbufAttribs);
+ }
+
+ Pointer surf = (eglSurface != null) ? eglSurface : Pointer.NULL;
+ if (!eglLib.eglMakeCurrent(eglDisplay, surf, surf, eglContext)) {
+ if (!eglLib.eglMakeCurrent(eglDisplay, Pointer.NULL, Pointer.NULL, eglContext)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean ensureWglContext() {
+ if (wglLib == null) {
+ User32Library user32 = (User32Library) Native.loadLibrary("user32", User32Library.class);
+ Gdi32Library gdi32 = (Gdi32Library) Native.loadLibrary("gdi32", Gdi32Library.class);
+ wglLib = (WglLibrary) Native.loadLibrary("opengl32", WglLibrary.class);
+ opengl32Lib = NativeLibrary.getInstance("opengl32");
+ useDesktopGlsl330 = true;
+
+ Pointer hwnd = user32.CreateWindowExA(0, "STATIC", "2006Scape317HD", 0, 0, 0, 16, 16,
+ Pointer.NULL, Pointer.NULL, Pointer.NULL, Pointer.NULL);
+ if (hwnd == Pointer.NULL) return false;
+ wglHdc = user32.GetDC(hwnd);
+ if (wglHdc == Pointer.NULL) return false;
+
+ PIXELFORMATDESCRIPTOR pfd = new PIXELFORMATDESCRIPTOR();
+ pfd.nSize = (short) pfd.size();
+ pfd.nVersion = 1;
+ pfd.dwFlags = 0x00000004 /* PFD_DRAW_TO_WINDOW */ | 0x00000020 /* PFD_SUPPORT_OPENGL */ | 0x00000001 /* PFD_DOUBLEBUFFER */;
+ pfd.iPixelType = 0 /* PFD_TYPE_RGBA */;
+ pfd.cColorBits = 32;
+ pfd.cDepthBits = 24;
+ pfd.write();
+
+ int pf = gdi32.ChoosePixelFormat(wglHdc, pfd);
+ if (pf == 0 || !gdi32.SetPixelFormat(wglHdc, pf, pfd)) {
+ return false;
+ }
+
+ Pointer baseCtx = wglLib.wglCreateContext(wglHdc);
+ if (baseCtx == Pointer.NULL || !wglLib.wglMakeCurrent(wglHdc, baseCtx)) {
+ return false;
+ }
+ wglContext = baseCtx;
+
+ Pointer createAttribsPtr = wglLib.wglGetProcAddress("wglCreateContextAttribsARB");
+ if (createAttribsPtr != null && Pointer.nativeValue(createAttribsPtr) != 0) {
+ Function createAttribs = Function.getFunction(createAttribsPtr, Function.ALT_CONVENTION);
+ int[] attribs = {
+ 0x2091 /* WGL_CONTEXT_MAJOR_VERSION_ARB */, 3,
+ 0x2092 /* WGL_CONTEXT_MINOR_VERSION_ARB */, 3,
+ 0
+ };
+ Pointer coreCtx = (Pointer) createAttribs.invoke(Pointer.class, new Object[]{wglHdc, Pointer.NULL, attribs});
+ if (coreCtx != null && Pointer.nativeValue(coreCtx) != 0) {
+ wglLib.wglMakeCurrent(wglHdc, coreCtx);
+ wglContext = coreCtx;
+ }
+ }
+
+ gles = createWglGlesProxy();
+ }
+ return wglLib.wglMakeCurrent(wglHdc, wglContext);
+ }
+
+ private Function getWglFunc(String name) {
+ Function f = wglFunctions.get(name);
+ if (f != null) return f;
+ Pointer p = wglLib.wglGetProcAddress(name);
+ if (p != null && Pointer.nativeValue(p) != 0) {
+ f = Function.getFunction(p, Function.ALT_CONVENTION);
+ } else {
+ f = opengl32Lib.getFunction(name, Function.ALT_CONVENTION);
+ }
+ wglFunctions.put(name, f);
+ return f;
+ }
+
+ private GLES3Library createWglGlesProxy() {
+ return (GLES3Library) java.lang.reflect.Proxy.newProxyInstance(
+ GLES3Library.class.getClassLoader(),
+ new Class>[]{GLES3Library.class},
+ (proxy, method, args) -> {
+ String name = method.getName();
+ if ("glShaderSource".equals(name)) {
+ int shader = (Integer) args[0];
+ String[] strs = (String[]) args[2];
+ byte[] bytes = (strs[0] + "\0").getBytes("UTF-8");
+ Memory mem = new Memory(bytes.length);
+ mem.write(0, bytes, 0, bytes.length);
+ Memory ptrArray = new Memory(Native.POINTER_SIZE);
+ ptrArray.setPointer(0, mem);
+ getWglFunc(name).invokeVoid(new Object[]{shader, 1, ptrArray, Pointer.NULL});
+ return null;
+ }
+ Function fn = getWglFunc(name);
+ Class> ret = method.getReturnType();
+ if (ret == void.class || ret == Void.class) {
+ fn.invokeVoid(args);
+ return null;
+ } else if (ret == int.class || ret == Integer.class) {
+ return fn.invokeInt(args);
+ }
+ return fn.invoke(ret, args);
+ }
+ );
+ }
+
+ private void initMaterials() {
+ if (materialsInitialized) return;
+
+ final int size = HdMaterial.TEX_SIZE;
+ final int layers = HdMaterial.LAYER_COUNT;
+ final int layerBytes = size * size * 4;
+
+ ByteBuffer diffuseBuf = ByteBuffer.allocateDirect(layers * layerBytes).order(ByteOrder.nativeOrder());
+ ByteBuffer normalBuf = ByteBuffer.allocateDirect(layers * layerBytes).order(ByteOrder.nativeOrder());
+
+ HdMaterial.populateTextureBuffers(diffuseBuf, normalBuf);
+
+ int[] texIds = new int[2];
+ gles.glGenTextures(2, texIds);
+ diffuseArrayTex = texIds[0];
+ normalArrayTex = texIds[1];
+
+ gles.glBindTexture(GL_TEXTURE_2D_ARRAY, diffuseArrayTex);
+ gles.glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA8, size, size, layers, 0, GL_RGBA, GL_UNSIGNED_BYTE, diffuseBuf);
+ gles.glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
+ gles.glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
+ gles.glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ gles.glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_REPEAT);
+ gles.glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_REPEAT);
+ gles.glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_ANISOTROPY_EXT, 8.0f);
+
+ gles.glBindTexture(GL_TEXTURE_2D_ARRAY, normalArrayTex);
+ gles.glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA8, size, size, layers, 0, GL_RGBA, GL_UNSIGNED_BYTE, normalBuf);
+ gles.glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
+ gles.glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
+ gles.glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ gles.glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_REPEAT);
+ gles.glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_REPEAT);
+ gles.glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_ANISOTROPY_EXT, 8.0f);
+
+ gles.glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
+ materialsInitialized = true;
+ }
+
+ private int createProgram(String vertSrc, String fragSrc) {
+ if (useDesktopGlsl330) {
+ vertSrc = HD317Pipeline.adaptGlslForDesktop330(vertSrc);
+ fragSrc = HD317Pipeline.adaptGlslForDesktop330(fragSrc);
+ }
+ int vs = compileShader(GL_VERTEX_SHADER, vertSrc);
+ if (vs == 0) return 0;
+ int fs = compileShader(GL_FRAGMENT_SHADER, fragSrc);
+ if (fs == 0) {
+ gles.glDeleteShader(vs);
+ return 0;
+ }
+ int prog = gles.glCreateProgram();
+ gles.glAttachShader(prog, vs);
+ gles.glAttachShader(prog, fs);
+ gles.glLinkProgram(prog);
+
+ int[] linkStatus = new int[1];
+ gles.glGetProgramiv(prog, GL_LINK_STATUS, linkStatus);
+ gles.glDeleteShader(vs);
+ gles.glDeleteShader(fs);
+
+ if (linkStatus[0] == 0) {
+ byte[] logBytes = new byte[2048];
+ int[] len = new int[1];
+ gles.glGetProgramInfoLog(prog, logBytes.length, len, logBytes);
+ System.err.println("317HD Program link failed: " + new String(logBytes, 0, Math.max(0, len[0])));
+ gles.glDeleteProgram(prog);
+ return 0;
+ }
+ return prog;
+ }
+
+ private int compileShader(int type, String src) {
+ int shader = gles.glCreateShader(type);
+ gles.glShaderSource(shader, 1, new String[]{src}, null);
+ gles.glCompileShader(shader);
+ int[] compiled = new int[1];
+ gles.glGetShaderiv(shader, GL_COMPILE_STATUS, compiled);
+ if (compiled[0] == 0) {
+ byte[] logBytes = new byte[2048];
+ int[] len = new int[1];
+ gles.glGetShaderInfoLog(shader, logBytes.length, len, logBytes);
+ System.err.println("317HD Shader compile error: " + new String(logBytes, 0, Math.max(0, len[0])));
+ gles.glDeleteShader(shader);
+ return 0;
+ }
+ return shader;
+ }
+
+ private void initGlResources() {
+ try {
+ int[] vaos = new int[1];
+ gles.glGenVertexArrays(1, vaos);
+ vaoId = vaos[0];
+ if (vaoId != 0) {
+ gles.glBindVertexArray(vaoId);
+ }
+ } catch (Throwable ignored) {
+ }
+
+ shadowProgram = createProgram(HD317Pipeline.SHADOW_VERT, HD317Pipeline.SHADOW_FRAG);
+ sceneProgram = createProgram(HD317Pipeline.SCENE_VERT, HD317Pipeline.SCENE_FRAG);
+ postProgram = createProgram(HD317Pipeline.POST_VERT, HD317Pipeline.POST_FRAG);
+
+ if (shadowProgram == 0 || sceneProgram == 0 || postProgram == 0) {
+ glFailed = true;
+ return;
+ }
+
+ uShadowLightViewProj = gles.glGetUniformLocation(shadowProgram, "uLightViewProj");
+ uShadowDiffuseArray = gles.glGetUniformLocation(shadowProgram, "uDiffuseArray");
+
+ uSceneViewProj = gles.glGetUniformLocation(sceneProgram, "uViewProj");
+ uSceneLightViewProj = gles.glGetUniformLocation(sceneProgram, "uLightViewProj");
+ uSceneDiffuseArray = gles.glGetUniformLocation(sceneProgram, "uDiffuseArray");
+ uSceneNormalArray = gles.glGetUniformLocation(sceneProgram, "uNormalArray");
+ uSceneShadowMap = gles.glGetUniformLocation(sceneProgram, "uShadowMap");
+ uSceneCameraPos = gles.glGetUniformLocation(sceneProgram, "uCameraPos");
+ uSceneSunDir = gles.glGetUniformLocation(sceneProgram, "uSunDir");
+ uSceneSunColor = gles.glGetUniformLocation(sceneProgram, "uSunColor");
+ uSceneAmbientColor = gles.glGetUniformLocation(sceneProgram, "uAmbientColor");
+ uSceneSkyColor = gles.glGetUniformLocation(sceneProgram, "uSkyColor");
+ uSceneFogColor = gles.glGetUniformLocation(sceneProgram, "uFogColor");
+ uSceneFogMin = gles.glGetUniformLocation(sceneProgram, "uFogMin");
+ uSceneFogMax = gles.glGetUniformLocation(sceneProgram, "uFogMax");
+ uSceneTime = gles.glGetUniformLocation(sceneProgram, "uTime");
+ uSceneShadowTexelSize = gles.glGetUniformLocation(sceneProgram, "uShadowTexelSize");
+ uSceneShadowsEnabled = gles.glGetUniformLocation(sceneProgram, "uShadowsEnabled");
+ uSceneShadowSoftPcf = gles.glGetUniformLocation(sceneProgram, "uShadowSoftPcf");
+ uSceneGroundTextures = gles.glGetUniformLocation(sceneProgram, "uGroundTextures");
+ uSceneNormalMapping = gles.glGetUniformLocation(sceneProgram, "uNormalMapping");
+ uSceneWaterShader = gles.glGetUniformLocation(sceneProgram, "uWaterShader");
+ uSceneSaturation = gles.glGetUniformLocation(sceneProgram, "uSaturation");
+ uSceneBrightness = gles.glGetUniformLocation(sceneProgram, "uBrightness");
+ uSceneLightCount = gles.glGetUniformLocation(sceneProgram, "uLightCount");
+ uSceneLightPosRad = gles.glGetUniformLocation(sceneProgram, "uLightPosRad");
+ uSceneLightColorInt = gles.glGetUniformLocation(sceneProgram, "uLightColorInt");
+
+ uPostSceneTex = gles.glGetUniformLocation(postProgram, "uSceneTex");
+ uPostTexelSize = gles.glGetUniformLocation(postProgram, "uTexelSize");
+
+ int staticCount = 4 * HdSceneUploader.CHUNKS_PER_PLANE;
+ int totalVbos = 7 + staticCount * 2;
+ int[] vbos = new int[totalVbos];
+ gles.glGenBuffers(totalVbos, vbos);
+ terrainVbos[0] = vbos[0];
+ terrainVbos[1] = vbos[1];
+ terrainVbos[2] = vbos[2];
+ terrainVbos[3] = vbos[3];
+ sceneVbo = vbos[4];
+ transVbo = vbos[5];
+ quadVbo = vbos[6];
+ int idx = 7;
+ for (int b = 0; b < 4; b++) {
+ for (int c = 0; c < HdSceneUploader.CHUNKS_PER_PLANE; c++) {
+ staticOpaqueVbos[b][c] = vbos[idx++];
+ staticTransVbos[b][c] = vbos[idx++];
+ }
+ }
+
+ float[] quadVerts = {
+ -1.0f, -1.0f,
+ 1.0f, -1.0f,
+ -1.0f, 1.0f,
+ 1.0f, 1.0f
+ };
+ FloatBuffer qBuf = ByteBuffer.allocateDirect(quadVerts.length * 4)
+ .order(ByteOrder.nativeOrder()).asFloatBuffer();
+ qBuf.put(quadVerts);
+ ((Buffer) qBuf).position(0);
+ gles.glBindBuffer(GL_ARRAY_BUFFER, quadVbo);
+ gles.glBufferData(GL_ARRAY_BUFFER, quadVerts.length * 4L, qBuf, GL_STATIC_DRAW);
+
+ int[] fbos = new int[1];
+ int[] texs = new int[1];
+ gles.glGenFramebuffers(1, fbos);
+ gles.glGenTextures(1, texs);
+ shadowFbo = fbos[0];
+ shadowDepthTex = texs[0];
+
+ gles.glBindTexture(GL_TEXTURE_2D, shadowDepthTex);
+ gles.glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24,
+ shadowMapSize, shadowMapSize, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, null);
+ gles.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ gles.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ gles.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ gles.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ gles.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
+ gles.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
+
+ gles.glBindFramebuffer(GL_FRAMEBUFFER, shadowFbo);
+ gles.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadowDepthTex, 0);
+ gles.glDrawBuffers(1, new int[]{GL_NONE});
+ gles.glReadBuffer(GL_NONE);
+ gles.glBindFramebuffer(GL_FRAMEBUFFER, 0);
+ }
+
+ private void ensureFramebuffers(int w, int h) {
+ if (fboWidth == w && fboHeight == h && sceneFbo != 0 && postFbo != 0 && readbackByteBuffer != null) {
+ return;
+ }
+
+ if (sceneFbo != 0) {
+ gles.glDeleteFramebuffers(2, new int[]{sceneFbo, postFbo});
+ gles.glDeleteTextures(2, new int[]{sceneColorTex, postColorTex});
+ gles.glDeleteRenderbuffers(1, new int[]{sceneDepthRbo});
+ }
+
+ fboWidth = w;
+ fboHeight = h;
+
+ int[] fbos = new int[2];
+ int[] texs = new int[2];
+ int[] rbos = new int[1];
+ gles.glGenFramebuffers(2, fbos);
+ gles.glGenTextures(2, texs);
+ gles.glGenRenderbuffers(1, rbos);
+
+ sceneFbo = fbos[0];
+ postFbo = fbos[1];
+ sceneColorTex = texs[0];
+ postColorTex = texs[1];
+ sceneDepthRbo = rbos[0];
+
+ gles.glBindTexture(GL_TEXTURE_2D, sceneColorTex);
+ gles.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, null);
+ gles.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ gles.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ gles.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ gles.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+
+ gles.glBindRenderbuffer(GL_RENDERBUFFER, sceneDepthRbo);
+ gles.glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, w, h);
+
+ gles.glBindFramebuffer(GL_FRAMEBUFFER, sceneFbo);
+ gles.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, sceneColorTex, 0);
+ gles.glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, sceneDepthRbo);
+
+ gles.glBindTexture(GL_TEXTURE_2D, postColorTex);
+ gles.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, null);
+ gles.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ gles.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+
+ gles.glBindFramebuffer(GL_FRAMEBUFFER, postFbo);
+ gles.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, postColorTex, 0);
+
+ gles.glBindFramebuffer(GL_FRAMEBUFFER, 0);
+
+ readbackByteBuffer = ByteBuffer.allocateDirect(w * h * 4).order(ByteOrder.LITTLE_ENDIAN);
+ readbackIntBuffer = readbackByteBuffer.asIntBuffer();
+ }
+}
diff --git a/2006Scape Client/src/main/java/DesktopHooks.java b/2006Scape Client/src/main/java/DesktopHooks.java
index cbc7b010..1d7d4021 100644
--- a/2006Scape Client/src/main/java/DesktopHooks.java
+++ b/2006Scape Client/src/main/java/DesktopHooks.java
@@ -16,11 +16,18 @@ import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Synthesizer;
import javax.swing.JOptionPane;
+import javax.swing.SwingUtilities;
public final class DesktopHooks {
private DesktopHooks() {}
+ public static void initHdBackend() {
+ if (!ClientSettings.ANDROID && HD317Pipeline.backend == null) {
+ HD317Pipeline.backend = new DesktopHd317Renderer();
+ }
+ }
+
public static void decodeImage(Sprite sprite, byte[] abyte0, Object component) {
try {
Component comp = (component instanceof Component) ? (Component) component : null;
@@ -70,7 +77,11 @@ public final class DesktopHooks {
public static void takeScreenshot(Game game, boolean sendMessage, String... subfolders) {
try {
- Window window = (Window) game.getGameComponent();
+ // getGameComponent() is the applet itself, so capture the frame that contains it
+ Window window = SwingUtilities.getWindowAncestor(game.getGameComponent());
+ if (window == null) {
+ return;
+ }
Point point = window.getLocationOnScreen();
int x = (int) point.getX();
int y = (int) point.getY();
@@ -285,4 +296,274 @@ public final class DesktopHooks {
public static void showKeyboard() {}
public static void hideKeyboard() {}
+
+ private static BufferedImage modernMinimapBezel = null;
+ private static BufferedImage modernMinimapHole = null;
+ private static BufferedImage modernMinimapComposite = null;
+ private static BufferedImage modernMinimapContent = null;
+ private static BufferedImage modernChatFrame = null;
+ private static BufferedImage modernChatComposite = null;
+ private static BufferedImage modernChatContent = null;
+ private static BufferedImage modernChatButtons = null;
+ private static BufferedImage modernTabComposite = null;
+ private static int[] modernTabPixels = null;
+ private static boolean[] modernTabMask = null;
+ private static final Object loginLock = new Object();
+ private static BufferedImage loginScreenBuffer = null;
+ private static BufferedImage offscreenBuffer = null;
+ private static Graphics2D offscreenGraphics = null;
+
+ public static void updateLoginTile(int[] tilePixels, int fixedX, int fixedY, int width, int height) {
+ if (tilePixels == null || tilePixels.length < width * height) {
+ return;
+ }
+ synchronized (loginLock) {
+ if (loginScreenBuffer == null) {
+ loginScreenBuffer = new BufferedImage(765, 503, BufferedImage.TYPE_INT_RGB);
+ }
+ loginScreenBuffer.setRGB(fixedX, fixedY, width, height, tilePixels, 0, width);
+ }
+ }
+
+ public static void drawScaledLoginTile(Graphics screenGraphics, int[] tilePixels, int fixedX, int fixedY, int width, int height) {
+ updateLoginTile(tilePixels, fixedX, fixedY, width, height);
+ // Only flip once after tile 1111 (right torch). Tile 1110 (left torch) updates buffer only.
+ if (fixedX == 0 && fixedY == 0 && width == 128 && height == 265) {
+ return;
+ }
+ redrawScaledLoginScreen(screenGraphics);
+ }
+
+ public static void redrawScaledLoginScreen(Graphics screenGraphics) {
+ if (screenGraphics == null) {
+ return;
+ }
+ synchronized (loginLock) {
+ if (loginScreenBuffer == null) {
+ return;
+ }
+ int w = ModernLayout.windowWidth;
+ int h = ModernLayout.windowHeight;
+ if (w <= 0 || h <= 0) {
+ return;
+ }
+ if (offscreenBuffer == null || offscreenBuffer.getWidth() != w || offscreenBuffer.getHeight() != h) {
+ if (offscreenGraphics != null) {
+ offscreenGraphics.dispose();
+ }
+ offscreenBuffer = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
+ offscreenGraphics = offscreenBuffer.createGraphics();
+ }
+ Graphics2D g2d = offscreenGraphics;
+ int[] bounds = ModernLayout.getScaledScreenBounds(w, h);
+ g2d.setColor(Color.BLACK);
+ g2d.fillRect(0, 0, w, h);
+ g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
+ g2d.drawImage(loginScreenBuffer, bounds[0], bounds[1], bounds[2], bounds[3], null);
+ screenGraphics.drawImage(offscreenBuffer, 0, 0, null);
+ }
+ }
+
+ public static void checkResize(Component comp) {
+ if (ClientSettings.ANDROID || !ClientSettings.RESIZABLE || comp == null) {
+ return;
+ }
+ int w = comp.getWidth();
+ int h = comp.getHeight();
+ if (w > 0 && h > 0 && (w != ModernLayout.windowWidth || h != ModernLayout.windowHeight)) {
+ ModernLayout.updateWindowSize(w, h);
+ ClientSettings.VIEWPORT_WIDTH = ClientSettings.isDesktopModern() ? w : 512;
+ ClientSettings.VIEWPORT_HEIGHT = ClientSettings.isDesktopModern() ? h : 334;
+ }
+ }
+
+ public static Graphics getRenderGraphics(Graphics screenGraphics) {
+ if (!ClientSettings.isDesktopModern()) {
+ return screenGraphics;
+ }
+ int w = ModernLayout.windowWidth;
+ int h = ModernLayout.windowHeight;
+ if (offscreenBuffer == null || offscreenBuffer.getWidth() != w || offscreenBuffer.getHeight() != h) {
+ if (offscreenGraphics != null) {
+ offscreenGraphics.dispose();
+ }
+ offscreenBuffer = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
+ offscreenGraphics = offscreenBuffer.createGraphics();
+ }
+ return offscreenGraphics;
+ }
+
+ public static void flip(Graphics screenGraphics) {
+ if (!ClientSettings.isDesktopModern() || screenGraphics == null || offscreenBuffer == null) {
+ return;
+ }
+ screenGraphics.drawImage(offscreenBuffer, 0, 0, null);
+ }
+
+ public static void drawModernMinimap(Object graphics, int[] minimapPixels, int windowWidth) {
+ if (!(graphics instanceof Graphics) || minimapPixels == null) {
+ return;
+ }
+ Graphics g = (Graphics) graphics;
+ if (modernMinimapBezel == null) {
+ try {
+ modernMinimapBezel = ImageIO.read(DesktopHooks.class.getResource("/hud_minimap_bezel.png"));
+ modernMinimapHole = ImageIO.read(DesktopHooks.class.getResource("/hud_minimap_hole.png"));
+ modernMinimapComposite = new BufferedImage(249, 168, BufferedImage.TYPE_INT_ARGB);
+ modernMinimapContent = new BufferedImage(172, 156, BufferedImage.TYPE_INT_RGB);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ if (modernMinimapBezel == null || modernMinimapHole == null) {
+ return;
+ }
+
+ modernMinimapContent.setRGB(0, 0, 172, 156, minimapPixels, 0, 172);
+
+ Graphics2D g2d = modernMinimapComposite.createGraphics();
+ g2d.setComposite(AlphaComposite.Clear);
+ g2d.fillRect(0, 0, 249, 168);
+ g2d.setComposite(AlphaComposite.SrcOver);
+ g2d.drawImage(modernMinimapContent, 34, 4, null);
+ g2d.setComposite(AlphaComposite.DstIn);
+ g2d.drawImage(modernMinimapHole, 0, 0, null);
+ g2d.setComposite(AlphaComposite.SrcOver);
+ g2d.drawImage(modernMinimapBezel, 0, 0, null);
+ g2d.dispose();
+
+ g.drawImage(modernMinimapComposite, windowWidth - 249, 0, null);
+ }
+
+ public static void drawModernChat(Object graphics, int[] chatContentPixels, int[] chatButtonsPixels, int windowHeight) {
+ if (!(graphics instanceof Graphics)) {
+ return;
+ }
+ Graphics g = (Graphics) graphics;
+ if (modernChatFrame == null) {
+ try {
+ modernChatFrame = ImageIO.read(DesktopHooks.class.getResource("/hud_chat_frame.png"));
+ modernChatComposite = new BufferedImage(519, 165, BufferedImage.TYPE_INT_ARGB);
+ modernChatContent = new BufferedImage(479, 96, BufferedImage.TYPE_INT_RGB);
+ modernChatButtons = new BufferedImage(496, 50, BufferedImage.TYPE_INT_RGB);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ if (modernChatFrame == null) {
+ return;
+ }
+
+ if (chatContentPixels != null && chatContentPixels.length >= 479 * 96) {
+ modernChatContent.setRGB(0, 0, 479, 96, chatContentPixels, 0, 479);
+ }
+ if (chatButtonsPixels != null && chatButtonsPixels.length >= 496 * 50) {
+ modernChatButtons.setRGB(0, 0, 496, 50, chatButtonsPixels, 0, 496);
+ }
+
+ Graphics2D g2d = modernChatComposite.createGraphics();
+ g2d.setComposite(AlphaComposite.Clear);
+ g2d.fillRect(0, 0, 519, 165);
+ g2d.setComposite(AlphaComposite.SrcOver);
+ g2d.drawImage(modernChatFrame, 0, 0, null);
+ if (chatContentPixels != null) {
+ g2d.drawImage(modernChatContent, 17, 19, null);
+ }
+ if (chatButtonsPixels != null) {
+ g2d.drawImage(modernChatButtons, 0, 115, null);
+ }
+ g2d.dispose();
+
+ g.drawImage(modernChatComposite, 0, windowHeight - 165, null);
+ }
+
+ public static void drawModernTab(Object graphics,
+ int[] topTabPixels,
+ int[] leftPillarTopPixels,
+ int[] leftPillarMidPixels,
+ int[] leftPillarBotPixels,
+ int[] tabBodyPixels,
+ int[] rightPillarPixels,
+ int[] bottomTabPixels,
+ int windowWidth,
+ int windowHeight) {
+ if (!(graphics instanceof Graphics)) {
+ return;
+ }
+ Graphics g = (Graphics) graphics;
+ if (modernTabComposite == null) {
+ modernTabComposite = new BufferedImage(249, 343, BufferedImage.TYPE_INT_ARGB);
+ modernTabPixels = new int[249 * 343];
+ modernTabMask = new boolean[249 * 343];
+ for (int y = 0; y < 343; y++) {
+ for (int x = 0; x < 249; x++) {
+ modernTabMask[y * 249 + x] = ModernLayout.isInsideTabArea(x, y);
+ }
+ }
+ }
+
+ // 1. Top tabs: 249x45 at y = 0..44
+ if (topTabPixels != null && topTabPixels.length >= 249 * 45) {
+ System.arraycopy(topTabPixels, 0, modernTabPixels, 0, 249 * 45);
+ }
+
+ // 2. Middle area: y from 45 to 306 (height 261, total width 249)
+ // Left vertical stone pillar is assembled from 3 fixed-mode producers:
+ // - backVmidIP2 (37x133 at y = 45..177)
+ // - backVmidIP2_2 (553x19 at y = 178..196, rightmost 37px starting at x = 516)
+ // - backVmidIP3 (57x109 at y = 197..305, rightmost 37px starting at x = 20)
+ if (leftPillarTopPixels != null && leftPillarTopPixels.length >= 37 * 133) {
+ for (int y = 0; y < 133; y++) {
+ System.arraycopy(leftPillarTopPixels, y * 37, modernTabPixels, (45 + y) * 249, 37);
+ }
+ }
+ if (leftPillarMidPixels != null && leftPillarMidPixels.length >= 553 * 19) {
+ for (int y = 0; y < 19; y++) {
+ System.arraycopy(leftPillarMidPixels, y * 553 + 516, modernTabPixels, (178 + y) * 249, 37);
+ }
+ }
+ if (leftPillarBotPixels != null && leftPillarBotPixels.length >= 57 * 109) {
+ for (int y = 0; y < 109; y++) {
+ System.arraycopy(leftPillarBotPixels, y * 57 + 20, modernTabPixels, (197 + y) * 249, 37);
+ }
+ }
+
+ // Tab body (inventory/interface): 190x261 at x = 37..226
+ if (tabBodyPixels != null && tabBodyPixels.length >= 190 * 261) {
+ for (int y = 0; y < 261; y++) {
+ System.arraycopy(tabBodyPixels, y * 190, modernTabPixels, (45 + y) * 249 + 37, 190);
+ }
+ }
+
+ // Right pillar: 22x261 at x = 227..248
+ if (rightPillarPixels != null && rightPillarPixels.length >= 22 * 261) {
+ for (int y = 0; y < 261; y++) {
+ System.arraycopy(rightPillarPixels, y * 22, modernTabPixels, (45 + y) * 249 + 227, 22);
+ }
+ }
+
+ // 3. Bottom tabs: 249x37 at y = 306..342 (cropped by 20px on left from 269x37 producer)
+ if (bottomTabPixels != null && bottomTabPixels.length >= 269 * 37) {
+ for (int y = 0; y < 37; y++) {
+ System.arraycopy(bottomTabPixels, y * 269 + 20, modernTabPixels, (306 + y) * 249, 249);
+ }
+ }
+
+ // 4. Mask out fixed-mode outer margins and 4 corner triangles to 100% transparent
+ int total = 249 * 343;
+ for (int i = 0; i < total; i++) {
+ modernTabPixels[i] = modernTabMask[i] ? (0xFF000000 | (modernTabPixels[i] & 0xFFFFFF)) : 0x00000000;
+ }
+
+ modernTabComposite.setRGB(0, 0, 249, 343, modernTabPixels, 0, 249);
+ g.drawImage(modernTabComposite, windowWidth - 249, windowHeight - 343, null);
+ }
+
+ public static String httpGet(String url) throws java.io.IOException { return null; }
+ public static boolean saveExternalScript(String fileName, String content) { return false; }
+ public static boolean deleteExternalScript(String fileName) { return false; }
+ public static void yieldUi() {}
+ public static Object boxReflectValue(Object v, Class> declaredType) { return v; }
+ public static String loadPluginConfig() { return null; }
+ public static boolean savePluginConfig(String content) { return false; }
}
diff --git a/2006Scape Client/src/main/java/ExternalPluginLoader.java b/2006Scape Client/src/main/java/ExternalPluginLoader.java
new file mode 100644
index 00000000..b4bfe87c
--- /dev/null
+++ b/2006Scape Client/src/main/java/ExternalPluginLoader.java
@@ -0,0 +1,147 @@
+import java.io.*;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+/**
+ * Loads external plugins and scripts from disk across Desktop and Android.
+ */
+public class ExternalPluginLoader {
+
+ public static class LoadedContainer {
+ public final List plugins = new ArrayList<>();
+ public final List scripts = new ArrayList<>();
+ public final List errors = new ArrayList<>();
+ }
+
+ /**
+ * Loads external plugins and scripts from the specified directory.
+ */
+ public static LoadedContainer loadExternal(File baseDir) {
+ LoadedContainer container = new LoadedContainer();
+ if (baseDir == null) return container;
+
+ File pluginsDir = new File(baseDir, "plugins");
+ File scriptsDir = new File(baseDir, "scripts");
+
+ if (!pluginsDir.exists()) pluginsDir.mkdirs();
+ if (!scriptsDir.exists()) scriptsDir.mkdirs();
+
+ // Load plugins directory
+ loadDirectory(pluginsDir, "plugin", container);
+
+ // Load scripts directory
+ loadDirectory(scriptsDir, "script", container);
+
+ return container;
+ }
+
+ private static void loadDirectory(File dir, String defaultType, LoadedContainer container) {
+ File[] files = dir.listFiles();
+ if (files == null) return;
+
+ for (File f : files) {
+ if (f.isDirectory()) continue;
+ String name = f.getName().toLowerCase();
+
+ try {
+ if (name.endsWith(".script") || name.endsWith(".bsh") || name.endsWith(".java")) {
+ loadSourceScript(f, defaultType, container);
+ } else if (name.endsWith(".jar") || name.endsWith(".dex")) {
+ loadJarOrDex(f, container);
+ }
+ } catch (Throwable t) {
+ String msg = f.getName() + ": " + (t.getMessage() != null ? t.getMessage() : t.getClass().getSimpleName());
+ container.errors.add(msg);
+ System.err.println("Failed to load external file: " + msg);
+ t.printStackTrace();
+ }
+ }
+ }
+
+ private static void loadSourceScript(File file, String defaultType, LoadedContainer container) {
+ StringBuilder sb = new StringBuilder();
+ try (BufferedReader br = new BufferedReader(new FileReader(file))) {
+ String line;
+ while ((line = br.readLine()) != null) {
+ sb.append(line).append("\n");
+ }
+ } catch (IOException e) {
+ String msg = file.getName() + ": " + e.getMessage();
+ container.errors.add(msg);
+ System.err.println("Could not read script file: " + file.getPath());
+ return;
+ }
+
+ String source = sb.toString();
+ ScriptInterpreter.ScriptMetadata meta = ScriptInterpreter.parseMetadata(source);
+ if ("Example Feather Farmer".equalsIgnoreCase(meta.name)) {
+ try {
+ file.delete();
+ } catch (Throwable ignored) {}
+ return;
+ }
+ if ("Unnamed Script".equals(meta.name)) {
+ String cleanName = file.getName();
+ int dot = cleanName.lastIndexOf('.');
+ if (dot != -1) cleanName = cleanName.substring(0, dot);
+ meta.name = cleanName.replace('_', ' ');
+ }
+ if (meta.type == null || meta.type.isEmpty()) {
+ meta.type = defaultType;
+ }
+
+ ScriptInterpreter.Environment env = ScriptInterpreter.compile(source);
+
+ if ("plugin".equalsIgnoreCase(meta.type)) {
+ container.plugins.add(new ScriptInterpreter.InterpretedPlugin(meta, env));
+ System.out.println("Loaded external plugin: " + meta.name + " from " + file.getName());
+ } else {
+ container.scripts.add(new ScriptInterpreter.InterpretedScript(meta, env));
+ System.out.println("Loaded external script: " + meta.name + " from " + file.getName());
+ }
+ }
+
+ private static void loadJarOrDex(File file, LoadedContainer container) {
+ if (ClientSettings.ANDROID) {
+ // Android uses DexClassLoader via AndroidHooks
+ AndroidHooks.loadExternalDexPlugins(file, container.plugins, container.scripts);
+ return;
+ }
+
+ // Desktop Java URLClassLoader
+ try {
+ URL url = file.toURI().toURL();
+ URLClassLoader classLoader = new URLClassLoader(new URL[]{url}, ExternalPluginLoader.class.getClassLoader());
+
+ try (JarFile jar = new JarFile(file)) {
+ Enumeration entries = jar.entries();
+ while (entries.hasMoreElements()) {
+ JarEntry entry = entries.nextElement();
+ if (entry.isDirectory() || !entry.getName().endsWith(".class")) continue;
+
+ String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6);
+ try {
+ Class> cls = classLoader.loadClass(className);
+ if (ClientPlugin.class.isAssignableFrom(cls) && !cls.isInterface()) {
+ ClientPlugin plugin = (ClientPlugin) cls.getDeclaredConstructor().newInstance();
+ container.plugins.add(plugin);
+ System.out.println("Loaded JAR plugin: " + plugin.getName());
+ } else if (ClientScript.class.isAssignableFrom(cls) && !cls.isInterface()) {
+ ClientScript script = (ClientScript) cls.getDeclaredConstructor().newInstance();
+ container.scripts.add(script);
+ System.out.println("Loaded JAR script: " + script.getName());
+ }
+ } catch (Throwable ignored) {
+ }
+ }
+ }
+ } catch (Throwable t) {
+ System.err.println("Error loading JAR: " + file.getName() + " - " + t.getMessage());
+ }
+ }
+}
diff --git a/2006Scape Client/src/main/java/Game.java b/2006Scape Client/src/main/java/Game.java
index a790337e..c49afc2a 100644
--- a/2006Scape Client/src/main/java/Game.java
+++ b/2006Scape Client/src/main/java/Game.java
@@ -21,6 +21,7 @@ import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.CRC32;
/**
@@ -496,7 +497,9 @@ public class Game extends RSApplet {
if (menuOpen && menuScreenArea == 2) {
drawMenu();
}
- aRSImageProducer_1166.drawGraphics(357, super.graphics, 17);
+ if (!ClientSettings.isDesktopModern()) {
+ aRSImageProducer_1166.drawGraphics(357, super.graphics, 17);
+ }
if (aRSImageProducer_1165 != null) {
aRSImageProducer_1165.initDrawingArea();
Texture.lineOffsets = chatBoxAreaOffsets;
@@ -540,6 +543,16 @@ public class Game extends RSApplet {
}
public boolean processMenuClick() {
+ if (PluginPanelUI.isModalOpen()) {
+ PluginPanelUI.processInput(this);
+ if (super.clickMode3 == 1 || super.clickMode3 == 2) {
+ PluginPanelUI.handleModalClick(super.saveClickX, super.saveClickY);
+ super.clickMode3 = 0;
+ super.saveClickX = -1;
+ super.saveClickY = -1;
+ }
+ return true;
+ }
if (activeInterfaceType != 0) {
return false;
}
@@ -780,6 +793,8 @@ public class Game extends RSApplet {
}
stream.createFrame(0);
objectManager.method171(aClass11Array1230, worldController);
+ DesktopHooks.initHdBackend();
+ HD317Pipeline.onSceneLoad(this, objectManager, worldController);
if(aRSImageProducer_1165 != null) {
aRSImageProducer_1165.initDrawingArea();
Texture.lineOffsets = chatBoxAreaOffsets;
@@ -965,6 +980,11 @@ public class Game extends RSApplet {
l *= item.amount + 1;
// notifyItemSpawn(item, i + baseX, j + baseY);
}
+ try {
+ if (PluginManager.get() != null) {
+ PluginManager.get().onGroundItemSpawn(item.ID, item.amount, i + baseX, j + baseY, plane);
+ }
+ } catch (Throwable ignored) {}
if (l > k) {
k = l;
@@ -1071,6 +1091,11 @@ public class Game extends RSApplet {
}
}
if (class9_1.type == 0) {
+ // Remember the scrollable container under the mouse (scrollbar included) for mouse wheel scrolling,
+ // set before recursing so a nested scrollable container takes priority over its parent
+ if (class9_1.scrollMax > class9_1.height && k >= i2 && k < i2 + class9_1.width + 16 && i1 >= j2 && i1 < j2 + class9_1.height) {
+ wheelScrollTarget = class9_1;
+ }
buildInterfaceMenu(i2, class9_1, k, j2, i1, class9_1.scrollPosition);
if (class9_1.scrollMax > class9_1.height) {
method65(i2 + class9_1.width, class9_1.height, k, i1, class9_1, j2, true, class9_1.scrollMax);
@@ -1278,7 +1303,20 @@ public class Game extends RSApplet {
if (k1 < 8) {
k1 = 8;
}
- int l1 = (j - 32 - k1) * k / (j1 - j);
+ if (k1 > j - 32) {
+ k1 = j - 32;
+ }
+ int trackAvail = j - 32 - k1;
+ int l1 = 0;
+ if (trackAvail > 0 && j1 > j) {
+ l1 = trackAvail * k / (j1 - j);
+ if (l1 < 0) {
+ l1 = 0;
+ }
+ if (l1 > trackAvail) {
+ l1 = trackAvail;
+ }
+ }
DrawingArea.fillArea(k1, l + 16 + l1, anInt1063, 16, i1);
DrawingArea.drawVerticalLine(l + 16 + l1, anInt902, k1, i1);
DrawingArea.drawVerticalLine(l + 16 + l1, anInt902, k1, i1 + 1);
@@ -1318,7 +1356,7 @@ public class Game extends RSApplet {
}
public void processChatModeClick() {
- if (ClientSettings.ANDROID && ClientSettings.VIEWPORT_WIDTH > 512 && touchTargetArea == TARGET_VIEWPORT) {
+ if (ClientSettings.isModernLayout() && touchTargetArea != TARGET_CHAT) {
return;
}
if (super.clickMode3 == 1) {
@@ -1795,11 +1833,30 @@ public class Game extends RSApplet {
}
}
+ private Sprite buttonLeftEnabled = null;
+ private Sprite buttonRightEnabled = null;
+ private Sprite buttonLeftDisabled = null;
+ private Sprite buttonRightDisabled = null;
+
public void drawButton(boolean enabled, int x, int y, int width) {
- StreamLoader streamLoader_2 = streamLoaderForName(4, "2d graphics", "media", expectedCRCs[4], 40);
- // All these sprites are 30x30
- Sprite buttonLeft = new Sprite(streamLoader_2, "miscgraphics", enabled ? 7 : 4);
- Sprite buttonRight = new Sprite(streamLoader_2, "miscgraphics", enabled ? 8 : 6);
+ if (buttonLeftEnabled == null || buttonRightEnabled == null || buttonLeftDisabled == null || buttonRightDisabled == null) {
+ try {
+ StreamLoader streamLoader_2 = streamLoaderForName(4, "2d graphics", "media", expectedCRCs[4], 40);
+ if (streamLoader_2 != null) {
+ buttonLeftEnabled = new Sprite(streamLoader_2, "miscgraphics", 7);
+ buttonRightEnabled = new Sprite(streamLoader_2, "miscgraphics", 8);
+ buttonLeftDisabled = new Sprite(streamLoader_2, "miscgraphics", 4);
+ buttonRightDisabled = new Sprite(streamLoader_2, "miscgraphics", 6);
+ }
+ } catch (Throwable ignored) {}
+ }
+ Sprite buttonLeft = enabled ? buttonLeftEnabled : buttonLeftDisabled;
+ Sprite buttonRight = enabled ? buttonRightEnabled : buttonRightDisabled;
+ if (buttonLeft == null || buttonRight == null) {
+ DrawingArea.fillPixels(y, 30, 0x000000, x, width);
+ DrawingArea.fillArea(28, y + 1, enabled ? 0x8a2626 : 0x483e32, width - 2, x + 1);
+ return;
+ }
int curWidth = 30;
buttonLeft.drawSprite(x, y);
while ((curWidth + 26) < width) {
@@ -1810,47 +1867,28 @@ public class Game extends RSApplet {
}
public void drawCheckbox(boolean enabled, int x, int y) {
- StreamLoader streamLoader_2 = streamLoaderForName(4, "2d graphics", "media", expectedCRCs[4], 40);
- Sprite checkboxUnchecked = new Sprite(streamLoader_2, "miscgraphics", 10);
- Sprite checkboxChecked = new Sprite(streamLoader_2, "miscgraphics", 11);
+ try {
+ StreamLoader streamLoader_2 = streamLoaderForName(4, "2d graphics", "media", expectedCRCs[4], 40);
+ Sprite checkboxUnchecked = new Sprite(streamLoader_2, "miscgraphics", 10);
+ Sprite checkboxChecked = new Sprite(streamLoader_2, "miscgraphics", 11);
+ } catch (Throwable ignored) {}
}
public void drawTabArea() {
- aRSImageProducer_1163.initDrawingArea();
+ if (aRSImageProducer_1163 == null) {
+ aRSImageProducer_1163 = new RSImageProducer(190, 261, getGameComponent());
+ }
+ if (aRSImageProducer_1163 != null) {
+ aRSImageProducer_1163.initDrawingArea();
+ }
Texture.lineOffsets = tabAreaOffsets;
- invBack.method361(0, 0);
+ if (invBack != null) {
+ invBack.method361(0, 0);
+ }
if (invOverlayInterfaceID == -1) {
if (tabInterfaceIDs[tabID] != -1 || (tabID == 7 && ClientSettings.CUSTOM_SETTINGS_TAB)) {
if (tabID == 7 && ClientSettings.CUSTOM_SETTINGS_TAB) {
- try {
- int centerX = 95;
- int currentY = 10;
- int textMiddle = 22;
- int textTop = 14;
- int textBottom = 29;
-
- drawButton(customSettingVisiblePlayerNames, centerX - 73, currentY, 146);
- // buttonLeftDisabled.drawSprite(centerX - 73, currentY);
- aTextDrawingArea_1271.textCenterShadow(RSColors.YELLOW, centerX, "always visible", currentY + textTop, true);
- aTextDrawingArea_1271.textCenterShadow(RSColors.YELLOW, centerX, "player names", currentY + textBottom, true);
-
- drawButton(true, centerX - 73, currentY += 40, 146);
- aTextDrawingArea_1271.textCenterShadow(RSColors.YELLOW, centerX, "item drops visible", currentY + textTop, true);
- aTextDrawingArea_1271.textCenterShadow(RSColors.WHITE, centerX, intToKOrMil(customSettingMinItemValue) + " gp", currentY + textBottom, true);
-
- drawButton(true, centerX - 73, currentY += 40, 146);
- aTextDrawingArea_1271.textCenterShadow(RSColors.YELLOW, centerX, "draw distance", currentY + textTop, true);
- aTextDrawingArea_1271.textCenterShadow(RSColors.WHITE, centerX, WorldController.drawDistance + " tiles", currentY + textBottom, true);
-
- drawButton(customSettingShowExperiencePerHour, centerX - 73, currentY += 40, 146);
- aTextDrawingArea_1271.textCenterShadow(RSColors.YELLOW, centerX, "show exp info", currentY + textMiddle, true);
-
- drawButton(showInfo, centerX - 73, currentY += 40, 146);
- aTextDrawingArea_1271.textCenterShadow(RSColors.YELLOW, centerX, "show debug info", currentY + textMiddle, true);
-
- drawButton(customSettingVisualFixes, centerX - 73, currentY += 40, 146);
- aTextDrawingArea_1271.textCenterShadow(RSColors.YELLOW, centerX, "visual fixes", currentY + textMiddle, true);
- } catch (Exception e) { }
+ PluginPanelUI.drawTab7(this);
}
}
}
@@ -1862,7 +1900,9 @@ public class Game extends RSApplet {
if (menuOpen && menuScreenArea == 1) {
drawMenu();
}
- aRSImageProducer_1163.drawGraphics(205, super.graphics, 553);
+ if (!ClientSettings.isDesktopModern() && aRSImageProducer_1163 != null) {
+ aRSImageProducer_1163.drawGraphics(205, super.graphics, 553);
+ }
if (aRSImageProducer_1165 != null) {
aRSImageProducer_1165.initDrawingArea();
Texture.lineOffsets = chatBoxAreaOffsets;
@@ -2213,6 +2253,10 @@ public class Game extends RSApplet {
}
socketStream = null;
loggedIn = false;
+ ModernLayout.inGame = false;
+ if (PluginManager.get() != null) {
+ PluginManager.get().onLogout();
+ }
if (ClientSettings.ANDROID) {
aRSImageProducer_1107 = null;
super.fullGameScreen = null;
@@ -2866,6 +2910,24 @@ public class Game extends RSApplet {
sprite.drawSprite(382 - sprite.width / 2 - 128, 18);
sprite = null;
System.gc();
+ welcomeScreenRaised = true;
+ if (!ClientSettings.ANDROID) {
+ if (ClientSettings.RESIZABLE) {
+ DesktopHooks.checkResize(getGameComponent());
+ }
+ DesktopHooks.updateLoginTile(aRSImageProducer_1110.anIntArray315, 0, 0, 128, 265);
+ DesktopHooks.updateLoginTile(aRSImageProducer_1111.anIntArray315, 637, 0, 128, 265);
+ DesktopHooks.updateLoginTile(aRSImageProducer_1107.anIntArray315, 128, 0, 509, 171);
+ DesktopHooks.updateLoginTile(aRSImageProducer_1108.anIntArray315, 202, 371, 360, 132);
+ DesktopHooks.updateLoginTile(aRSImageProducer_1109.anIntArray315, 202, 171, 360, 200);
+ DesktopHooks.updateLoginTile(aRSImageProducer_1112.anIntArray315, 0, 265, 202, 238);
+ DesktopHooks.updateLoginTile(aRSImageProducer_1113.anIntArray315, 562, 265, 203, 238);
+ DesktopHooks.updateLoginTile(aRSImageProducer_1114.anIntArray315, 128, 171, 74, 94);
+ DesktopHooks.updateLoginTile(aRSImageProducer_1115.anIntArray315, 562, 171, 75, 94);
+ if (ClientSettings.isDesktopModern()) {
+ DesktopHooks.redrawScaledLoginScreen(super.graphics);
+ }
+ }
}
@@ -3041,6 +3103,11 @@ public class Game extends RSApplet {
if (!loggedIn) {
return;
}
+ if (PluginManager.get() != null) {
+ try {
+ PluginManager.get().onGameTick();
+ } catch (Throwable ignored) {}
+ }
synchronized (mouseDetection.syncObject) {
if (flagged) {
if (super.clickMode3 != 0 || mouseDetection.coordsIndex >= 40) {
@@ -3380,6 +3447,12 @@ public class Game extends RSApplet {
}
void drawLoadingText(int i, String s) {
+ if (!loggedIn) {
+ ModernLayout.inGame = false;
+ }
+ if (!ClientSettings.ANDROID && ClientSettings.RESIZABLE) {
+ DesktopHooks.checkResize(getGameComponent());
+ }
anInt1079 = i;
aString1049 = s;
resetImageProducers();
@@ -3412,6 +3485,7 @@ public class Game extends RSApplet {
aRSImageProducer_1114.drawGraphics(171, super.graphics, 128);
aRSImageProducer_1115.drawGraphics(171, super.graphics, 562);
}
+ DesktopHooks.yieldUi();
}
public void method65(int i, int j, int k, int l, RSInterface class9, int i1, boolean flag, int j1) {
@@ -3617,6 +3691,7 @@ public class Game extends RSApplet {
destX = 0;
RSSocket rsSocket = socketStream;
loggedIn = false;
+ ModernLayout.inGame = false;
loginFailures = 0;
login(myUsername, myPassword, true);
if (!loggedIn) {
@@ -3685,6 +3760,13 @@ public class Game extends RSApplet {
if (i < 0) {
return;
}
+ if (PluginManager.get() != null) {
+ try {
+ if (!PluginManager.get().onMenuAction(i)) {
+ return;
+ }
+ } catch (Throwable ignored) {}
+ }
if (inputDialogState != 0) {
if (!ClientSettings.ANDROID || (super.saveClickX > 516 || super.saveClickY < 357 || super.saveClickY > 467)) {
inputDialogState = 0;
@@ -4767,6 +4849,9 @@ public class Game extends RSApplet {
}
socketStream = null;
stopMidi();
+ if (PluginManager.get() != null) {
+ PluginManager.get().onLogout();
+ }
if (mouseDetection != null) {
mouseDetection.running = false;
}
@@ -4815,6 +4900,10 @@ public class Game extends RSApplet {
mapBack = null;
chatBack = null;
backBase1 = null;
+ buttonLeftEnabled = null;
+ buttonRightEnabled = null;
+ buttonLeftDisabled = null;
+ buttonRightDisabled = null;
backBase2 = null;
backHmid1 = null;
sideIcons = null;
@@ -4920,6 +5009,10 @@ public class Game extends RSApplet {
if (j == -1) {
break;
}
+ if (PluginPanelUI.isSearchFocused()) {
+ PluginPanelUI.handleKeyChar(j);
+ continue;
+ }
if (customTabAction == 1 || customTabAction == 2) {
if (j >= 48 && j <= 57 && promptInput.length() < 10 && !promptInput.toLowerCase().contains("k") && !promptInput.toLowerCase().contains("m") && !promptInput.toLowerCase().contains("b")) {
promptInput += (char) j;
@@ -4948,7 +5041,7 @@ public class Game extends RSApplet {
}
if (customTabAction == 2) {
WorldController.drawDistance = Math.max(10, Math.min(100, Integer.parseInt(promptInput)));
- zoom = Math.min(zoom, WorldController.drawDistance / 3);
+ zoom = Math.min(zoom, getMaxZoom());
}
}
customTabAction = 0;
@@ -5087,52 +5180,19 @@ public class Game extends RSApplet {
if (j >= 32 && j <= 122 && inputString.length() < 80) {
inputString += (char) j;
inputTaken = true;
- if (inputString.startsWith("::search")) {
- String[] args = inputString.split(" ");
- inputDialogState = 3;
- int searchType = 1;
- String searchString = "";
- if (args.length < 2) {
- return;
- }
- try {
- searchType = Integer.parseInt(args[1]);
- if (args.length >= 3) {
- searchString = inputString.substring(inputString.indexOf(args[1]) + args[1].length() + 1);
- }
- } catch (Exception e) {
- searchType = 1;
- searchString = inputString.substring(args[0].length() + 1);
- }
- definitionSearch(searchString, searchType);
- }
}
// deleting characters
if (j == 8 && inputString.length() > 0) {
inputString = inputString.substring(0, inputString.length() - 1);
inputTaken = true;
- if (inputString.startsWith("::search")) {
- String[] args = inputString.split(" ");
- inputDialogState = 3;
- int searchType = 1;
- String searchString = "";
- if (args.length < 2) {
- return;
- }
- try {
- searchType = Integer.parseInt(args[1]);
- if (args.length >= 3) {
- searchString = inputString.substring(inputString.indexOf(args[1]) + args[1].length() + 1);
- }
- } catch (Exception e) {
- searchType = 1;
- searchString = inputString.substring(args[0].length() + 1);
- }
- definitionSearch(searchString, searchType);
- }
}
// submitted string
if ((j == 13 || j == 10) && inputString.length() > 0) {
+ if (PluginManager.get() != null && PluginManager.get().onCommand(inputString)) {
+ inputString = "";
+ inputTaken = true;
+ return;
+ }
if (inputString.equals("::gfxtgl") || inputString.equals("::tglgfx") || inputString.equals("::togglerender") || inputString.equals("::togglegfx")) {
graphicsEnabled = !graphicsEnabled;
}
@@ -5189,8 +5249,8 @@ public class Game extends RSApplet {
distance = 25;
}
WorldController.drawDistance = distance;
- if (zoom > (WorldController.drawDistance / 3))
- zoom = WorldController.drawDistance / 3;
+ if (zoom > getMaxZoom())
+ zoom = getMaxZoom();
inputString = "";
inputTaken = true;
return;
@@ -5709,10 +5769,15 @@ public class Game extends RSApplet {
chatTypes[0] = i;
chatNames[0] = s1;
chatMessages[0] = s;
+ if (PluginManager.get() != null) {
+ try {
+ PluginManager.get().onChatMessage(i, s1, s);
+ } catch (Throwable ignored) {}
+ }
}
public void processMinimapActions() {
- if (ClientSettings.ANDROID && ClientSettings.VIEWPORT_WIDTH > 512 && touchTargetArea != TARGET_MINIMAP) {
+ if (ClientSettings.isModernLayout() && touchTargetArea != TARGET_MINIMAP) {
return;
}
int x = super.mouseX;
@@ -5734,16 +5799,16 @@ public class Game extends RSApplet {
boolean customSettingVisualFixes = true;
public void processTabClick() {
- if (ClientSettings.ANDROID) {
+ if (ClientSettings.usesTouchTargets()) {
if (touchTargetArea == TARGET_VIEWPORT) {
return;
}
- if (ClientSettings.VIEWPORT_WIDTH > 512 && touchTargetArea != TARGET_TAB) {
+ if (ClientSettings.isModernLayout() && touchTargetArea != TARGET_TAB) {
return;
}
}
if (super.clickMode3 == 1) {
- if (!ClientSettings.ANDROID || ClientSettings.VIEWPORT_WIDTH <= 512) {
+ if (ClientSettings.usesClassicTabHitboxes()) {
if (super.saveClickX >= 539 && super.saveClickX <= 573 && super.saveClickY >= 169 && super.saveClickY < 205 && tabInterfaceIDs[0] != -1) {
needDrawTabArea = true;
tabID = 0;
@@ -5829,47 +5894,8 @@ public class Game extends RSApplet {
if (invOverlayInterfaceID == -1) {
if (tabInterfaceIDs[tabID] != -1 || (tabID == 7 && ClientSettings.CUSTOM_SETTINGS_TAB)) {
// Handle our custom tab
- if (tabID == 7 && ClientSettings.CUSTOM_SETTINGS_TAB && (ClientSettings.VIEWPORT_WIDTH <= 512 || touchTargetArea == TARGET_TAB) && super.saveClickX >= 575 && super.saveClickX <= 720 && super.saveClickY >= 210 && super.saveClickY <= 465) {
- int startY = 217 + 3;
- if (super.saveClickY >= startY && super.saveClickY <= (startY + 30)) {
- customSettingVisiblePlayerNames = !customSettingVisiblePlayerNames;
- }
- startY += 40;
- if (super.saveClickY >= startY && super.saveClickY <= (startY + 30)) {
- inputTaken = true;
- inputDialogState = 0;
- messagePromptRaised = true;
- promptInput = "";
- aString1121 = "Enter minimum item value";
- customTabAction = 1;
- }
- startY += 40;
- if (super.saveClickY >= startY && super.saveClickY <= (startY + 30)) {
- inputTaken = true;
- inputDialogState = 0;
- messagePromptRaised = true;
- promptInput = "";
- aString1121 = "Enter new draw distance";
- customTabAction = 2;
- }
- startY += 40;
- if (super.saveClickY >= startY && super.saveClickY <= (startY + 30)) {
- customSettingShowExperiencePerHour= !customSettingShowExperiencePerHour;
- customSettingShowExperiencePerHourStart = System.currentTimeMillis();
- customSettingShowExperiencePerHourStartExp = calculateTotalExp();
- customSettingShowExperiencePerHourStartLevels = calculateTotalLevels();
- }
- startY += 40;
- if (super.saveClickY >= startY && super.saveClickY <= (startY + 30)) {
- showInfo= !showInfo;
- }
- startY += 40;
- if (super.saveClickY >= startY && super.saveClickY <= (startY + 30)) {
- customSettingVisualFixes = !customSettingVisualFixes;
- ClientSettings.BILINEAR_MINIMAP_FILTERING = !ClientSettings.BILINEAR_MINIMAP_FILTERING;
- ClientSettings.FIX_TRANSPARENCY_OVERFLOW = !ClientSettings.FIX_TRANSPARENCY_OVERFLOW;
- ClientSettings.FULL_512PX_VIEWPORT = !ClientSettings.FULL_512PX_VIEWPORT;
- }
+ if (tabID == 7 && ClientSettings.CUSTOM_SETTINGS_TAB && ((!ClientSettings.isModernLayout()) || touchTargetArea == TARGET_TAB) && super.saveClickX >= 575 && super.saveClickX <= 720 && super.saveClickY >= 210 && super.saveClickY <= 465) {
+ PluginPanelUI.handleTab7Click(this, super.saveClickX, super.saveClickY);
}
}
}
@@ -5945,7 +5971,7 @@ public class Game extends RSApplet {
}
public void resetImageProducers2() {
- if (aRSImageProducer_1166 != null && (!ClientSettings.ANDROID || aRSImageProducer_1165 != null)) {
+ if (aRSImageProducer_1166 != null && ((!ClientSettings.ANDROID && !ClientSettings.isDesktopModern()) || aRSImageProducer_1165 != null)) {
return;
}
nullLoader();
@@ -5975,6 +6001,91 @@ public class Game extends RSApplet {
// SignLink.midii.fadeOut();
}
+ private int currentViewportWidth = -1;
+ private int currentViewportHeight = -1;
+
+ public synchronized void updateViewportSize(int width, int height) {
+ if (!ClientSettings.ANDROID && !ClientSettings.RESIZABLE) {
+ return;
+ }
+ if (aRSImageProducer_1165 != null && currentViewportWidth == width && currentViewportHeight == height) {
+ return;
+ }
+ currentViewportWidth = width;
+ currentViewportHeight = height;
+ ClientSettings.VIEWPORT_WIDTH = width;
+ ClientSettings.VIEWPORT_HEIGHT = height;
+ if (aRSImageProducer_1165 != null) {
+ aRSImageProducer_1165 = new RSImageProducer(width, height, getGameComponent());
+ aRSImageProducer_1165.initDrawingArea();
+ }
+ Texture.method365(width, height);
+ chatBoxAreaOffsets = Texture.lineOffsets;
+ int ai[] = new int[9];
+ for (int i8 = 0; i8 < 9; i8++) {
+ int k8 = 128 + i8 * 32 + 15;
+ int l8 = 600 + k8 * 3;
+ int i9 = Texture.anIntArray1470[k8];
+ ai[i8] = l8 * i9 >> 16;
+ }
+ WorldController.method310(500, 800, width, height, ai);
+ }
+
+ void onResize(int w, int h) {
+ applyWindowSize(w, h);
+ }
+
+ public synchronized void switchToFixedLayout() {
+ currentViewportWidth = 512;
+ currentViewportHeight = 334;
+ ClientSettings.VIEWPORT_WIDTH = 512;
+ ClientSettings.VIEWPORT_HEIGHT = 334;
+ ModernLayout.updateWindowSize(765, 503);
+ if (!loggedIn) {
+ aRSImageProducer_1165 = null;
+ aRSImageProducer_1166 = null;
+ resetImageProducers();
+ welcomeScreenRaised = true;
+ return;
+ }
+ aRSImageProducer_1165 = null;
+ aRSImageProducer_1166 = null;
+ resetImageProducers2();
+ Texture.method365(512, 334);
+ chatBoxAreaOffsets = Texture.lineOffsets;
+ int ai[] = new int[9];
+ for (int i8 = 0; i8 < 9; i8++) {
+ int k8 = 128 + i8 * 32 + 15;
+ int l8 = 600 + k8 * 3;
+ int i9 = Texture.anIntArray1470[k8];
+ ai[i8] = l8 * i9 >> 16;
+ }
+ WorldController.method310(500, 800, 512, 334, ai);
+ welcomeScreenRaised = true;
+ needDrawFrameBorders = true;
+ needDrawTabArea = true;
+ inputTaken = true;
+ tabAreaAltered = true;
+ aBoolean1233 = true;
+ }
+
+ public synchronized void applyWindowSize(int w, int h) {
+ ModernLayout.updateWindowSize(w, h);
+ int vpW = ClientSettings.isDesktopModern() ? w : 512;
+ int vpH = ClientSettings.isDesktopModern() ? h : 334;
+ updateViewportSize(vpW, vpH);
+ if (!loggedIn && ClientSettings.isDesktopModern()) {
+ DesktopHooks.redrawScaledLoginScreen(super.graphics);
+ return;
+ }
+ welcomeScreenRaised = true;
+ needDrawFrameBorders = !ClientSettings.isDesktopModern();
+ needDrawTabArea = true;
+ inputTaken = true;
+ tabAreaAltered = true;
+ aBoolean1233 = true;
+ }
+
public void method81(Sprite sprite, int y, int x) {
int l = x * x + y * y;
if (l > 4225 && l < 90000) {
@@ -5996,8 +6107,12 @@ public class Game extends RSApplet {
public void processRightClick() {
if (activeInterfaceType != 0) {
+ // Drop wheel input while dragging so it does not all apply at once when the drag ends
+ pendingWheelScrollNotches.set(0);
return;
}
+ wheelScrollTarget = null;
+ wheelScrollChatHistory = false;
menuActionName[0] = "Cancel";
menuActionID[0] = 1107;
menuActionRow = 1;
@@ -6007,23 +6122,27 @@ public class Game extends RSApplet {
if (anInt886 != anInt1026) {
anInt1026 = anInt886;
}
+ processWheelScrolling();
return;
}
buildSplitPrivateChatMenu();
anInt886 = 0;
boolean inTabArea;
boolean inChatArea;
- if (ClientSettings.ANDROID && ClientSettings.VIEWPORT_WIDTH > 512) {
+ boolean inViewportArea;
+ if (ClientSettings.isModernLayout()) {
inTabArea = (touchTargetArea == TARGET_TAB);
inChatArea = (touchTargetArea == TARGET_CHAT);
+ inViewportArea = (touchTargetArea == TARGET_VIEWPORT && super.mouseX > 4 && super.mouseY > 4 && super.mouseX < ClientSettings.VIEWPORT_WIDTH + 4 && super.mouseY < ClientSettings.VIEWPORT_HEIGHT + 4);
} else {
inTabArea = (super.mouseX > 553 && super.mouseY > 205 && super.mouseX < 743 && super.mouseY < 466);
inChatArea = (super.mouseX > 17 && super.mouseY > 357 && super.mouseX < 496 && super.mouseY < 453);
+ inViewportArea = (!inTabArea && !inChatArea && super.mouseX > 4 && super.mouseY > 4 && super.mouseX < ClientSettings.VIEWPORT_WIDTH + 4 && super.mouseY < ClientSettings.VIEWPORT_HEIGHT + 4);
}
- if (!inTabArea && !inChatArea && super.mouseX > 4 && super.mouseY > 4 && super.mouseX < ClientSettings.VIEWPORT_WIDTH + 4 && super.mouseY < ClientSettings.VIEWPORT_HEIGHT + 4) {
+ if (inViewportArea) {
if (openInterfaceID != -1) {
- int ifX = Math.max(0, (ClientSettings.VIEWPORT_WIDTH - 512) / 2);
- int ifY = Math.max(0, (ClientSettings.VIEWPORT_HEIGHT - 334) / 2);
+ int ifX = (ClientSettings.ANDROID && ClientSettings.RESIZABLE) ? 0 : Math.max(0, (ClientSettings.VIEWPORT_WIDTH - 512) / 2);
+ int ifY = (ClientSettings.ANDROID && ClientSettings.RESIZABLE) ? 0 : Math.max(0, (ClientSettings.VIEWPORT_HEIGHT - 334) / 2);
RSInterface openInt = RSInterface.interfaceCache[openInterfaceID];
int ifW = openInt != null ? openInt.width : 512;
int ifH = openInt != null ? openInt.height : 334;
@@ -6065,6 +6184,12 @@ public class Game extends RSApplet {
inputTaken = true;
anInt1039 = anInt886;
}
+ // Chat history is only drawn when no prompt or dialogue is in the chat area (same checks as drawChatArea)
+ if (!messagePromptRaised && inputDialogState != 1 && inputDialogState != 2 && aString844 == null && backDialogID == -1 && dialogID == -1
+ && super.mouseX > 17 && super.mouseY > 357 && super.mouseX < 496 && super.mouseY < 434) {
+ wheelScrollChatHistory = true;
+ }
+ processWheelScrolling();
processMinimapActions();
boolean flag = false;
while (!flag) {
@@ -6091,6 +6216,11 @@ public class Game extends RSApplet {
}
}
+ if (PluginManager.get() != null) {
+ try {
+ PluginManager.get().onPostBuildMenu();
+ } catch (Throwable ignored) {}
+ }
}
public int method83(int i, int j, int k) {
@@ -7466,6 +7596,7 @@ public class Game extends RSApplet {
Animable_Sub5.clientInstance = this;
ObjectDef.clientInstance = this;
EntityDef.clientInstance = this;
+ PluginManager.init(this);
if (myUsername != null && !myUsername.isEmpty()) {
loginScreenState = 2;
@@ -7519,7 +7650,7 @@ public class Game extends RSApplet {
if (anInt1021 != 0) {
return;
}
- if (ClientSettings.ANDROID && ClientSettings.VIEWPORT_WIDTH > 512 && touchTargetArea != TARGET_MINIMAP) {
+ if (ClientSettings.isModernLayout() && touchTargetArea != TARGET_MINIMAP) {
return;
}
if (super.clickMode3 == 1) {
@@ -7952,8 +8083,36 @@ public class Game extends RSApplet {
}
}
+ public void drawModernDesktopOverlays() {
+ // Minimap with authentic circular stone/lizard bezel
+ drawMinimap();
+ if (aRSImageProducer_1164 != null) {
+ DesktopHooks.drawModernMinimap(DesktopHooks.getRenderGraphics(super.graphics), aRSImageProducer_1164.anIntArray315, ModernLayout.windowWidth);
+ }
+
+ // Tab area: complete unified floating stone tab block
+ int[] topTab = (aRSImageProducer_1125 != null) ? aRSImageProducer_1125.anIntArray315 : null;
+ int[] leftPillarTop = (backVmidIP2 != null) ? backVmidIP2.anIntArray315 : null;
+ int[] leftPillarMid = (backVmidIP2_2 != null) ? backVmidIP2_2.anIntArray315 : null;
+ int[] leftPillarBot = (backVmidIP3 != null) ? backVmidIP3.anIntArray315 : null;
+ int[] tabBody = (aRSImageProducer_1163 != null) ? aRSImageProducer_1163.anIntArray315 : null;
+ int[] rightPillar = (backRightIP2 != null) ? backRightIP2.anIntArray315 : null;
+ int[] botTab = (aRSImageProducer_1124 != null) ? aRSImageProducer_1124.anIntArray315 : null;
+ DesktopHooks.drawModernTab(DesktopHooks.getRenderGraphics(super.graphics), topTab, leftPillarTop, leftPillarMid, leftPillarBot, tabBody, rightPillar, botTab, ModernLayout.windowWidth, ModernLayout.windowHeight);
+
+ // Chat area: authentic floating stone chatbox
+ int[] chatContent = (aRSImageProducer_1166 != null) ? aRSImageProducer_1166.anIntArray315 : null;
+ int[] chatButtons = (aRSImageProducer_1123 != null) ? aRSImageProducer_1123.anIntArray315 : null;
+ DesktopHooks.drawModernChat(DesktopHooks.getRenderGraphics(super.graphics), chatContent, chatButtons, ModernLayout.windowHeight);
+
+ if (aRSImageProducer_1165 != null) {
+ aRSImageProducer_1165.initDrawingArea();
+ Texture.lineOffsets = chatBoxAreaOffsets;
+ }
+ }
+
public void drawFixedFrameBorders() {
- if (ClientSettings.ANDROID && ClientSettings.VIEWPORT_WIDTH <= 512) {
+ if (ClientSettings.ANDROID && !ClientSettings.RESIZABLE && ClientSettings.VIEWPORT_WIDTH <= 512) {
if (backLeftIP1 != null) backLeftIP1.drawGraphics(4, super.graphics, 0);
if (backLeftIP2 != null) backLeftIP2.drawGraphics(357, super.graphics, 0);
if (backRightIP1 != null) backRightIP1.drawGraphics(4, super.graphics, 722);
@@ -7967,6 +8126,7 @@ public class Game extends RSApplet {
}
public void drawGameScreen() {
+ ModernLayout.inGame = (fullScreenInterfaceId == -1);
if (ClientSettings.ANDROID) {
if (fullScreenInterfaceId != -1) {
resetAllImageProducers();
@@ -8007,7 +8167,7 @@ public class Game extends RSApplet {
super.fullGameScreen.drawGraphics(0, super.graphics, 0);
return;
}
- if (welcomeScreenRaised || aRSImageProducer_1165 == null || (ClientSettings.VIEWPORT_WIDTH <= 512 && needDrawFrameBorders)) {
+ if (welcomeScreenRaised || aRSImageProducer_1165 == null || (!ClientSettings.ANDROID && needDrawFrameBorders) || (ClientSettings.ANDROID && !ClientSettings.RESIZABLE && ClientSettings.VIEWPORT_WIDTH <= 512 && needDrawFrameBorders)) {
resetImageProducers2();
welcomeScreenRaised = false;
needDrawFrameBorders = false;
@@ -8151,7 +8311,9 @@ public class Game extends RSApplet {
}
if (loadingStage == 2) {
drawMinimap();
- aRSImageProducer_1164.drawGraphics(4, super.graphics, 550);
+ if (!ClientSettings.isDesktopModern()) {
+ aRSImageProducer_1164.drawGraphics(4, super.graphics, 550);
+ }
}
if (anInt1054 != -1) {
tabAreaAltered = true;
@@ -8211,7 +8373,9 @@ public class Game extends RSApplet {
sideIcons[6].method361(208, 13);
}
}
- aRSImageProducer_1125.drawGraphics(160, super.graphics, 516);
+ if (!ClientSettings.isDesktopModern()) {
+ aRSImageProducer_1125.drawGraphics(160, super.graphics, 516);
+ }
aRSImageProducer_1124.initDrawingArea();
backBase2.method361(0, 0);
if (invOverlayInterfaceID == -1) {
@@ -8260,7 +8424,9 @@ public class Game extends RSApplet {
sideIcons[12].method361(226, 2);
}
}
- aRSImageProducer_1124.drawGraphics(466, super.graphics, 496);
+ if (!ClientSettings.isDesktopModern()) {
+ aRSImageProducer_1124.drawGraphics(466, super.graphics, 496);
+ }
if (aRSImageProducer_1165 != null) {
aRSImageProducer_1165.initDrawingArea();
Texture.lineOffsets = chatBoxAreaOffsets;
@@ -8304,12 +8470,18 @@ public class Game extends RSApplet {
aTextDrawingArea_1271.textCenterShadow(0xff0000, 324, "Off", 41, true);
}
aTextDrawingArea_1271.textCenterShadow(0xffffff, 458, "Report abuse", 33, true);
- aRSImageProducer_1123.drawGraphics(453, super.graphics, 0);
+ if (!ClientSettings.isDesktopModern()) {
+ aRSImageProducer_1123.drawGraphics(453, super.graphics, 0);
+ }
if (aRSImageProducer_1165 != null) {
aRSImageProducer_1165.initDrawingArea();
Texture.lineOffsets = chatBoxAreaOffsets;
}
}
+ if (ClientSettings.isDesktopModern()) {
+ drawModernDesktopOverlays();
+ DesktopHooks.flip(super.graphics);
+ }
anInt945 = 0;
}
@@ -8960,6 +9132,7 @@ public class Game extends RSApplet {
anInt1213 = 0;
return;
}
+ DesktopHooks.checkResize(this);
if (!loggedIn) {
drawLoginScreen(false);
} else {
@@ -9036,9 +9209,49 @@ public class Game extends RSApplet {
}
if (openInterfaceID != -1) {
method119(anInt945, openInterfaceID);
- int ifX = Math.max(0, (ClientSettings.VIEWPORT_WIDTH - 512) / 2);
- int ifY = Math.max(0, (ClientSettings.VIEWPORT_HEIGHT - 334) / 2);
- drawInterface(0, ifX, RSInterface.interfaceCache[openInterfaceID], ifY);
+ if (ClientSettings.ANDROID && ClientSettings.RESIZABLE) {
+ if (openInterfaceOffsets == null) {
+ openInterfaceOffsets = new int[334];
+ for (int l = 0; l < 334; l++) {
+ openInterfaceOffsets[l] = 512 * l;
+ }
+ }
+ if (openInterfaceProducer == null) {
+ openInterfaceProducer = new RSImageProducer(512, 334, getGameComponent());
+ }
+ openInterfaceProducer.initDrawingArea();
+ Texture.lineOffsets = openInterfaceOffsets;
+ DrawingArea.setAllPixelsToZero();
+ drawInterface(0, 0, RSInterface.interfaceCache[openInterfaceID], 0);
+ openInterfaceProducer.drawGraphics(0, super.graphics, 0);
+ if (aRSImageProducer_1165 != null) {
+ aRSImageProducer_1165.initDrawingArea();
+ Texture.lineOffsets = chatBoxAreaOffsets;
+ }
+ } else {
+ int ifX = (ClientSettings.ANDROID && ClientSettings.RESIZABLE) ? 0 : Math.max(0, (ClientSettings.VIEWPORT_WIDTH - 512) / 2);
+ int ifY = (ClientSettings.ANDROID && ClientSettings.RESIZABLE) ? 0 : Math.max(0, (ClientSettings.VIEWPORT_HEIGHT - 334) / 2);
+ drawInterface(0, ifX, RSInterface.interfaceCache[openInterfaceID], ifY);
+ }
+ } else if (PluginPanelUI.isModalOpen() && ClientSettings.ANDROID && ClientSettings.RESIZABLE) {
+ if (openInterfaceOffsets == null) {
+ openInterfaceOffsets = new int[334];
+ for (int l = 0; l < 334; l++) {
+ openInterfaceOffsets[l] = 512 * l;
+ }
+ }
+ if (openInterfaceProducer == null) {
+ openInterfaceProducer = new RSImageProducer(512, 334, getGameComponent());
+ }
+ openInterfaceProducer.initDrawingArea();
+ Texture.lineOffsets = openInterfaceOffsets;
+ DrawingArea.setAllPixelsToZero();
+ PluginPanelUI.drawViewportModal(this);
+ openInterfaceProducer.drawGraphics(0, super.graphics, 0);
+ if (aRSImageProducer_1165 != null) {
+ aRSImageProducer_1165.initDrawingArea();
+ Texture.lineOffsets = chatBoxAreaOffsets;
+ }
}
method70();
if (!menuOpen) {
@@ -9199,7 +9412,7 @@ public class Game extends RSApplet {
i += 8;
int l = 15 * menuActionRow + 21;
- if (ClientSettings.ANDROID && ClientSettings.VIEWPORT_WIDTH > 512) {
+ if (ClientSettings.isModernLayout()) {
if (touchTargetArea == TARGET_TAB) {
int j1 = super.saveClickX - 553 - i / 2;
if (j1 < 0) j1 = 0;
@@ -9439,6 +9652,10 @@ public class Game extends RSApplet {
int l = Math.max(0, Math.min(103, yCameraPos >> 7));
int i1 = myPlayer.x >> 7;
int j1 = myPlayer.y >> 7;
+ if (ClientSettings.ANDROID) {
+ k = Math.max(i1 - 5, Math.min(i1 + 5, k));
+ l = Math.max(j1 - 5, Math.min(j1 + 5, l));
+ }
if ((byteGroundArray[plane][k][l] & 4) != 0) {
j = plane;
}
@@ -9706,7 +9923,15 @@ public class Game extends RSApplet {
if (menuActionRow > 2) {
s = s + "@whi@ / " + (menuActionRow - 2) + " more options";
}
- chatTextDrawingArea.method390(ClientSettings.ANDROID && ClientSettings.VIEWPORT_WIDTH > 512 ? 72 : 4, 0xffffff, s, loopCycle / 1000, 15);
+ boolean isModern = ClientSettings.isModernLayout();
+ boolean isPortrait = isModern && (ClientSettings.VIEWPORT_WIDTH < ClientSettings.VIEWPORT_HEIGHT);
+ int tooltipX = isModern ? (ClientSettings.ANDROID ? (isPortrait ? 16 : 72) : 8) : 4;
+ int tooltipY = isModern ? (ClientSettings.ANDROID ? 28 : 20) : 15;
+ if (HD317Pipeline.isGpuActive()) {
+ chatTextDrawingArea.textLeftShadow(true, tooltipX, 0xffffff, s, tooltipY);
+ } else {
+ chatTextDrawingArea.method390(tooltipX, 0xffffff, s, loopCycle / 1000, tooltipY);
+ }
}
public void drawMinimap() {
@@ -10135,6 +10360,7 @@ public class Game extends RSApplet {
}
public void drawLoginScreen(boolean flag) {
+ ModernLayout.inGame = false;
resetImageProducers();
aRSImageProducer_1109.initDrawingArea();
aBackground_966.method361(0, 0);
@@ -10591,15 +10817,17 @@ public class Game extends RSApplet {
}
public void processLoginScreenInput() {
+ int screenWidth = 765;
+ int screenHeight = 503;
if (loginScreenState == 0) {
- int i = super.myWidth / 2 - 80;
- int l = super.myHeight / 2 + 20;
+ int i = screenWidth / 2 - 80;
+ int l = screenHeight / 2 + 20;
l += 20;
if (super.clickMode3 == 1 && super.saveClickX >= i - 75 && super.saveClickX <= i + 75 && super.saveClickY >= l - 20 && super.saveClickY <= l + 20) {
loginScreenState = 3;
loginScreenCursorPos = 0;
}
- i = super.myWidth / 2 + 80;
+ i = screenWidth / 2 + 80;
if (super.clickMode3 == 1 && super.saveClickX >= i - 75 && super.saveClickX <= i + 75 && super.saveClickY >= l - 20 && super.saveClickY <= l + 20) {
loginMessage1 = "";
loginMessage2 = "Enter your username & password.";
@@ -10608,7 +10836,7 @@ public class Game extends RSApplet {
}
} else {
if (loginScreenState == 2) {
- int j = super.myHeight / 2 - 40;
+ int j = screenHeight / 2 - 40;
j += 30;
j += 25;
if (super.clickMode3 == 1 && super.saveClickY >= j - 15 && super.saveClickY < j) {
@@ -10619,8 +10847,8 @@ public class Game extends RSApplet {
loginScreenCursorPos = 1;
}
j += 15;
- int i1 = super.myWidth / 2 - 80;
- int k1 = super.myHeight / 2 + 50;
+ int i1 = screenWidth / 2 - 80;
+ int k1 = screenHeight / 2 + 50;
k1 += 20;
if (super.clickMode3 == 1 && super.saveClickX >= i1 - 75 && super.saveClickX <= i1 + 75 && super.saveClickY >= k1 - 20 && super.saveClickY <= k1 + 20) {
loginFailures = 0;
@@ -10629,7 +10857,7 @@ public class Game extends RSApplet {
return;
}
}
- i1 = super.myWidth / 2 + 80;
+ i1 = screenWidth / 2 + 80;
if (super.clickMode3 == 1 && super.saveClickX >= i1 - 75 && super.saveClickX <= i1 + 75 && super.saveClickY >= k1 - 20 && super.saveClickY <= k1 + 20) {
loginScreenState = 0;
// myUsername = "";
@@ -10681,8 +10909,8 @@ public class Game extends RSApplet {
return;
}
if (loginScreenState == 3) {
- int k = super.myWidth / 2;
- int j1 = super.myHeight / 2 + 50;
+ int k = screenWidth / 2;
+ int j1 = screenHeight / 2 + 50;
j1 += 20;
if (super.clickMode3 == 1 && super.saveClickX >= k - 75 && super.saveClickX <= k + 75 && super.saveClickY >= j1 - 20 && super.saveClickY <= j1 + 20) {
loginScreenState = 0;
@@ -11003,6 +11231,11 @@ public class Game extends RSApplet {
maxStats[skillID] = k20 + 2;
}
}
+ if (PluginManager.get() != null) {
+ try {
+ PluginManager.get().onSkillUpdate(skillID, experience, level);
+ } catch (Throwable ignored) {}
+ }
pktType = -1;
return true;
@@ -12070,6 +12303,9 @@ public class Game extends RSApplet {
}
public static int zoom = 3;
+ public static int getMaxZoom() {
+ return Math.min(12, WorldController.drawDistance / 3);
+ }
public void method146() {
anInt1265++;
@@ -12129,13 +12365,17 @@ public class Game extends RSApplet {
}
}
- if (ClientSettings.ANDROID) {
+ if (ClientSettings.ANDROID || ClientSettings.isDesktopModern()) {
if (aRSImageProducer_1165 == null) {
resetImageProducers2();
}
if (aRSImageProducer_1165 != null) {
aRSImageProducer_1165.initDrawingArea();
+ Texture.lineOffsets = chatBoxAreaOffsets;
}
+ } else if (aRSImageProducer_1165 != null) {
+ aRSImageProducer_1165.initDrawingArea();
+ Texture.lineOffsets = chatBoxAreaOffsets;
}
int k2 = Texture.anInt1481;
@@ -12145,7 +12385,21 @@ public class Game extends RSApplet {
Model.anInt1686 = super.mouseY - 4;
DrawingArea.setAllPixelsToZero();
if(graphicsEnabled){
+ if (ClientSettings.ANDROID || ClientSettings.HD_317) {
+ DesktopHooks.initHdBackend();
+ if (myPlayer != null) {
+ WorldController.hdPlayerTileX = Math.max(0, Math.min(103, myPlayer.x >> 7));
+ WorldController.hdPlayerTileZ = Math.max(0, Math.min(103, myPlayer.y >> 7));
+ WorldController.hdCamDistToPlayer = (int) Math.hypot(xCameraPos - myPlayer.x, yCameraPos - myPlayer.y);
+ }
+ if (ClientSettings.HD_317 && HD317Pipeline.isGpuActive()) {
+ HD317Pipeline.beginFrame(this, xCameraPos, zCameraPos, yCameraPos, yCameraCurve, xCameraCurve);
+ }
+ }
worldController.method313(xCameraPos, yCameraPos, xCameraCurve, zCameraPos, j, yCameraCurve);
+ if (ClientSettings.HD_317 && HD317Pipeline.isGpuActive()) {
+ HD317Pipeline.endFrame(DrawingArea.pixels, DrawingArea.width, DrawingArea.height);
+ }
worldController.clearObj5Cache();
updateEntities();
drawHeadIcon();
@@ -12157,8 +12411,9 @@ public class Game extends RSApplet {
if (showInfo) {
int debugX;
int debugY;
- if (ClientSettings.VIEWPORT_WIDTH > 512) {
- debugX = 72;
+ if (ClientSettings.isModernLayout()) {
+ int startX = ClientSettings.ANDROID ? ((ClientSettings.VIEWPORT_WIDTH < ClientSettings.VIEWPORT_HEIGHT) ? 16 : 72) : 8;
+ debugX = startX;
debugY = 30;
} else {
debugX = 0;
@@ -12201,8 +12456,9 @@ public class Game extends RSApplet {
int debugHeight = 25 + (debugItems * 15);
int debugX;
int debugY;
- if (ClientSettings.VIEWPORT_WIDTH > 512) {
- debugX = (showInfo ? 72 + 140 + 8 : 72);
+ if (ClientSettings.isModernLayout()) {
+ int startX = ClientSettings.ANDROID ? ((ClientSettings.VIEWPORT_WIDTH < ClientSettings.VIEWPORT_HEIGHT) ? 16 : 72) : 8;
+ debugX = (showInfo ? startX + 140 + 8 : startX);
debugY = 30;
} else {
debugX = (511 - debugWidth);
@@ -12232,9 +12488,19 @@ public class Game extends RSApplet {
chatTextDrawingArea.textRightShadow(true, debugX + debugWidth - 4, RSColors.YELLOW, "" + (calculateTotalLevels() - customSettingShowExperiencePerHourStartLevels), debugY);
}
+ // Plugin overlays and modal
+ if (PluginManager.get() != null) {
+ try {
+ PluginManager.get().onRenderOverlays();
+ if (!(ClientSettings.ANDROID && ClientSettings.RESIZABLE)) {
+ PluginPanelUI.drawViewportModal(this);
+ }
+ } catch (Throwable ignored) {}
+ }
+
// Draw main screen
if (aRSImageProducer_1165 != null) {
- aRSImageProducer_1165.drawGraphics(4, super.graphics, 4);
+ aRSImageProducer_1165.drawGraphics(4, DesktopHooks.getRenderGraphics(super.graphics), 4);
}
if(graphicsEnabled) {
@@ -12263,12 +12529,16 @@ public class Game extends RSApplet {
if (openInterfaceID != -1) {
openInterfaceID = -1;
}
+ if (PluginPanelUI.isModalOpen()) {
+ PluginPanelUI.closeModal();
+ }
}
public Game() {
if (!ClientSettings.ANDROID) {
DesktopHooks.checkJavaVersion();
}
+ PluginManager.init(this);
server = ClientSettings.SERVER_IP;
anIntArrayArray825 = new int[104][104];
friendsNodeIDs = new int[200];
@@ -12380,6 +12650,7 @@ public class Game extends RSApplet {
musicEnabled = true;
needDrawTabArea = false;
loggedIn = false;
+ ModernLayout.inGame = false;
canMute = false;
aBoolean1159 = false;
aBoolean1160 = false;
@@ -12753,6 +13024,8 @@ public class Game extends RSApplet {
public int[] chatAreaOffsets;
public int[] tabAreaOffsets;
public int[] chatBoxAreaOffsets;
+ public int[] openInterfaceOffsets;
+ public RSImageProducer openInterfaceProducer;
public byte[][] aByteArrayArray1183;
public int anInt1184;
public int minimapInt1;
@@ -12981,7 +13254,7 @@ public class Game extends RSApplet {
}
break;
case 34: // VK_PAGE_DOWN
- if (zoom < (WorldController.drawDistance / 3)) {
+ if (zoom < getMaxZoom()) {
zoom++;
if (ClientSettings.SHOW_ZOOM_LEVEL_MESSAGES) {
pushMessage("Your zoom level is now: " + zoom, 0, "");
@@ -13020,118 +13293,6 @@ public class Game extends RSApplet {
return levels - 4;
}
-
- public void definitionSearch(String name, int type) {
- int amount = 0;
- int definitionResultsTotal = 0;
- int definitionResultIDs[] = new int[352];
- String definitionResults[] = new String[352];
- String sType = "";
- if (type == 1) {
- amount = ItemDef.totalItems;
- sType = "Item";
- } else if (type == 2) {
- amount = EntityDef.totalNPCs;
- sType = "NPC";
- } else if (type == 3) {
- amount = ObjectDef.totalObjects;
- sType = "Object";
- } else {
- type = 1;
- amount = ItemDef.totalItems;
- sType = "Item";
- }
- if (type != 1) {
- for (int line = 0; line < 100; line++) {
- pushMessage("", 0, "");
- }
- }
- if (name == null || name.length() == 0) {
- definitionResultsTotal = 0;
- return;
- }
-
- String search = name;
- String parts[] = new String[100];
- int found = 0;
- do {
- int regex = search.indexOf(" ");
- if (regex == -1) {
- break;
- }
- String part = search.substring(0, regex).trim();
- if (part.length() > 0) {
- parts[found++] = part.toLowerCase();
- }
- search = search.substring(regex + 1);
- } while (true);
- search = search.trim();
- if (search.length() > 0) {
- parts[found++] = search.toLowerCase();
- }
- definitionResultsTotal = 0;
- label0: for (int definition = 0; definition < amount; definition++) {
- String result = "";
- if (type == 1) {
- ItemDef item = ItemDef.forID(definition);
- if (item.certTemplateID != -1 || item.name == null) {
- continue;
- }
- result = item.name + "@bla@ - " + new String(item.description, StandardCharsets.UTF_8);
- } else if (type == 2) {
- EntityDef npc = EntityDef.forID(definition);
- if (npc.name == null) {
- continue;
- }
- result = npc.name;
- } else if (type == 3) {
- ObjectDef object = ObjectDef.forID(definition);
- if (object.name == null) {
- continue;
- }
- result = object.name;
- }
- for (int index = 0; index < found; index++) {
- if (!result.toLowerCase().contains(parts[index])) {
- continue label0;
- }
- }
-
- if (type != 1) {
- pushMessage("@whi@[" + definition + "] @blu@" + result + "", 0, "");
- }
- definitionResults[definitionResultsTotal] = result;
- definitionResultIDs[definitionResultsTotal] = definition;
- definitionResultsTotal++;
- if (definitionResultsTotal >= definitionResults.length) {
- break;
- }
- }
-
- if (type == 1) {
- // Open bank interface
- needDrawTabArea = true;
- int interfaceID = 5382;
- RSInterface class9_1 = RSInterface.interfaceCache[interfaceID];
- openInterface(5292); // Bank interface
- RSInterface.interfaceCache[5383].disabledText = "Search results for @yel@" + name; // The Bank of Text
-
- int itemCount = 0;
- for (int ID : definitionResultIDs) {
- if (ID > 0 && itemCount < class9_1.inv.length) {
- class9_1.inv[itemCount] = ID + 1; // Sets item ID;
- class9_1.invStackSizes[itemCount++] = 1; // Sets item amoounts
- }
- }
- while (itemCount < class9_1.inv.length) {
- class9_1.inv[itemCount] = 0;
- class9_1.invStackSizes[itemCount++] = 0;
- }
- } else {
- pushMessage("@blu@" + sType + " @bla@search results for @blu@" + name + "@bla@ displayed above (@blu@" + definitionResultsTotal + "@bla@ results).", 0, "");
- }
- }
-
public void openInterface(int interfaceID) {
method60(interfaceID);
if (invOverlayInterfaceID != -1) {
@@ -13169,7 +13330,62 @@ public class Game extends RSApplet {
tabAreaAltered = true;
}
+ /**
+ * Mouse wheel notches waiting to be applied on the game thread by processWheelScrolling(), positive scrolls down.
+ * Written from the AWT event thread, hence atomic.
+ */
+ private final AtomicInteger pendingWheelScrollNotches = new AtomicInteger();
+
+ /**
+ * Innermost scrollable interface under the mouse, found each frame while processRightClick() builds the menu.
+ */
+ private RSInterface wheelScrollTarget;
+
+ /**
+ * Whether the mouse is over the chat history this frame, found while processRightClick() builds the menu.
+ */
+ private boolean wheelScrollChatHistory;
+
+ /**
+ * Pixels scrolled per mouse wheel notch.
+ */
+ private static final int WHEEL_SCROLL_AMOUNT = 30;
+
+ /**
+ * Applies pending mouse wheel notches to the scrollable interface or chat history under the mouse, otherwise drops them.
+ */
+ private void processWheelScrolling() {
+ int notches = pendingWheelScrollNotches.getAndSet(0);
+ if (notches == 0) {
+ return;
+ }
+ int amount = notches * WHEEL_SCROLL_AMOUNT;
+ if (wheelScrollTarget != null) {
+ int maxPosition = wheelScrollTarget.scrollMax - wheelScrollTarget.height;
+ int position = Math.max(0, Math.min(maxPosition, wheelScrollTarget.scrollPosition + amount));
+ if (position != wheelScrollTarget.scrollPosition) {
+ wheelScrollTarget.scrollPosition = position;
+ // The target can be in the tab area or the chat area, which only redraw when flagged
+ needDrawTabArea = true;
+ inputTaken = true;
+ }
+ } else if (wheelScrollChatHistory) {
+ // anInt1089 is how far the chat history is scrolled up from the newest message, anInt1211 is its total height.
+ // 77 is the visible height of the chat history area (see drawChatArea), so anInt1211 - 77 is the furthest it
+ // can scroll up, the same limit the chat scrollbar drag code uses
+ int position = Math.max(0, Math.min(anInt1211 - 77, anInt1089 - amount));
+ if (position != anInt1089) {
+ anInt1089 = position;
+ inputTaken = true;
+ }
+ }
+ }
+
public void adjustZoom(int notches) {
+ if (!ClientSettings.RESIZABLE && !ClientSettings.ENABLE_QOL) {
+ zoom = 0;
+ return;
+ }
if (openInterfaceID == -1) {
if (notches < 0) {
if (zoom > -1) {
@@ -13179,7 +13395,7 @@ public class Game extends RSApplet {
}
}
} else {
- if (zoom < (WorldController.drawDistance / 3)) {
+ if (zoom < getMaxZoom()) {
zoom++;
if (ClientSettings.SHOW_ZOOM_LEVEL_MESSAGES) {
pushMessage("Your zoom level is now: " + zoom, 0, "");
@@ -13190,6 +13406,17 @@ public class Game extends RSApplet {
}
public void handleMouseWheel(int notches, boolean isControlDown) {
+ if (PluginPanelUI.isModalOpen()) {
+ PluginPanelUI.handleMouseWheel(notches);
+ return;
+ }
+ // Interface and chat scrolling is applied on the game thread, ignore it while a right click menu is open
+ if (!menuOpen) {
+ pendingWheelScrollNotches.addAndGet(notches);
+ }
+ if (!ClientSettings.RESIZABLE && !ClientSettings.ENABLE_QOL) {
+ return;
+ }
if (!ClientSettings.ANDROID && ClientSettings.CONTROL_KEY_ZOOMING && !isControlDown) {
return;
}
@@ -13275,7 +13502,10 @@ public class Game extends RSApplet {
if (!loggedIn) {
return false;
}
- if (ClientSettings.ANDROID && ClientSettings.VIEWPORT_WIDTH > 512) {
+ if (PluginPanelUI.isModalOpen() && PluginPanelUI.isScrollBarAt(x, y)) {
+ return true;
+ }
+ if (ClientSettings.isModernLayout()) {
if (touchTargetArea == TARGET_VIEWPORT) {
if (fullScreenInterfaceId != -1) {
if (checkInterfaceScrollBar(fullScreenInterfaceId, 0, 0, x, y)) {
@@ -13283,8 +13513,8 @@ public class Game extends RSApplet {
}
}
if (openInterfaceID != -1) {
- int ifX = Math.max(0, (ClientSettings.VIEWPORT_WIDTH - 512) / 2);
- int ifY = Math.max(0, (ClientSettings.VIEWPORT_HEIGHT - 334) / 2);
+ int ifX = (ClientSettings.ANDROID && ClientSettings.RESIZABLE) ? 0 : Math.max(0, (ClientSettings.VIEWPORT_WIDTH - 512) / 2);
+ int ifY = (ClientSettings.ANDROID && ClientSettings.RESIZABLE) ? 0 : Math.max(0, (ClientSettings.VIEWPORT_HEIGHT - 334) / 2);
return checkInterfaceScrollBar(openInterfaceID, ifX + 4, ifY + 4, x, y);
}
return false;
@@ -13415,4 +13645,27 @@ public class Game extends RSApplet {
anInt1187 = 0;
anInt1184 = 128;
}
+
+ public void setHD317Enabled(boolean enabled) {
+ DesktopHooks.initHdBackend();
+ ClientSettings.HD_317 = enabled;
+ HD317Pipeline.onToggle(enabled);
+ PluginManager pm = PluginManager.get();
+ if (pm != null) {
+ pm.syncPluginEnabledState("317 HD", enabled);
+ }
+ try {
+ Texture.method367();
+ Texture.method372(0.8D);
+ } catch (Throwable ignored) {
+ }
+ }
+
+ public int getOpenInterfaceWidth() {
+ return 512;
+ }
+
+ public int getOpenInterfaceHeight() {
+ return 334;
+ }
}
diff --git a/2006Scape Client/src/main/java/GroundItemsOverlayPlugin.java b/2006Scape Client/src/main/java/GroundItemsOverlayPlugin.java
new file mode 100644
index 00000000..5c0e0706
--- /dev/null
+++ b/2006Scape Client/src/main/java/GroundItemsOverlayPlugin.java
@@ -0,0 +1,449 @@
+import java.text.DecimalFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * RuneLite-style Ground Items Plugin for Revision 377 client.
+ * Features:
+ * - Highlighted items with custom magenta/cyan colors and wildcard matching.
+ * - Hidden items filter (omitted from overlay).
+ * - Tile collapsing (merges identical items on the same ground tile).
+ * - Vertical stacked offsets per tile (prevents overlapping labels).
+ * - Price & value tiers: Common, Low, Medium, High, and Insane value coloring.
+ * - Radiant 3D lootbeams for high-value and highlighted drops.
+ * - Deprioritizes left-click 'Take' for hidden ground items below 'Walk here'.
+ * - Chat commands (::highlight, ::hide, ::unhighlight, ::unhide, ::grounditems).
+ */
+public class GroundItemsOverlayPlugin extends ClientPlugin {
+
+ // Configurable Settings
+ private boolean showNames = true;
+ private boolean showQuantities = true;
+ private boolean showValues = true;
+ private boolean collapseEntries = true;
+ private boolean showLootbeam = true;
+ private boolean deprioritizeHidden = true;
+
+ private String highlightedItems = "clue scroll*, *whip, rune *, dragon *, dark bow";
+ private String hiddenItems = "vial, empty vial, ashes, pot, jug, bucket, bones";
+
+ private int lowValueThreshold = 1000;
+ private int mediumValueThreshold = 10000;
+ private int highValueThreshold = 100000;
+ private int insaneValueThreshold = 1000000;
+
+ // Opacity & Transparency settings (0 = transparent, 255 = solid)
+ private int boxOpacity = 100;
+ private int textOpacity = 200;
+
+ // Color Palette (RuneLite Authentic)
+ public static final int COLOR_HIGHLIGHT = 0xdc00ff; // Magenta
+ public static final int COLOR_INSANE = 0xff9810; // Orange/Amber
+ public static final int COLOR_HIGH = 0xffd700; // Gold/Yellow
+ public static final int COLOR_MEDIUM = 0x00ffff; // Cyan
+ public static final int COLOR_LOW = 0x66ff66; // Light Green
+ public static final int COLOR_COMMON = 0xffffff; // White
+
+ @Override
+ public String getName() {
+ return "Ground Items";
+ }
+
+ @Override
+ public String getDescription() {
+ return "RuneLite-style ground item labels, price tiers, lootbeams, and tile collapsing.";
+ }
+
+ @Override
+ public String getAuthor() {
+ return "2006Scape";
+ }
+
+ @Override
+ public boolean isEnabledByDefault() {
+ return true;
+ }
+
+ @Override
+ public List getConfigItems() {
+ List list = new ArrayList<>();
+ list.add(new PluginConfigItem("showNames", "Show Ground Items", "Render names and values over ground items", showNames));
+ list.add(new PluginConfigItem("highlightedItems", "Highlighted Items", "Comma-separated items or wildcards to highlight (e.g. rune *, whip)", highlightedItems));
+ list.add(new PluginConfigItem("hiddenItems", "Hidden Items", "Comma-separated items or wildcards to hide (e.g. ashes, vial)", hiddenItems));
+ list.add(new PluginConfigItem("collapseEntries", "Collapse Duplicates", "Collapse identical ground items on the same tile", collapseEntries));
+ list.add(new PluginConfigItem("showQuantities", "Show Quantities", "Display quantity stack size next to item names", showQuantities));
+ list.add(new PluginConfigItem("showValues", "Show Values", "Display store/alch value in gold next to items", showValues));
+ list.add(new PluginConfigItem("showLootbeam", "Show Lootbeams", "Display radiant vertical light beams on valuable drops", showLootbeam));
+ list.add(new PluginConfigItem("deprioritizeHidden", "Deprioritize Hidden", "Move left-click 'Take' below 'Walk here' for hidden items", deprioritizeHidden));
+ list.add(new PluginConfigItem("lowValueThreshold", "Low Value (Green)", "Threshold for low value items (gp)", lowValueThreshold, 0, 1000000));
+ list.add(new PluginConfigItem("mediumValueThreshold", "Medium Value (Cyan)", "Threshold for medium value items (gp)", mediumValueThreshold, 0, 10000000));
+ list.add(new PluginConfigItem("highValueThreshold", "High Value (Gold)", "Threshold for high value items (gp)", highValueThreshold, 0, 100000000));
+ list.add(new PluginConfigItem("insaneValueThreshold", "Insane Value (Orange)", "Threshold for insane value items (gp)", insaneValueThreshold, 0, 2000000000));
+ list.add(new PluginConfigItem("boxOpacity", "Box Opacity", "Background pill box opacity (0 = transparent, 255 = solid)", boxOpacity, 0, 255));
+ list.add(new PluginConfigItem("textOpacity", "Text Opacity", "Font transparency for item labels (50 = faint, 255 = solid)", textOpacity, 50, 255));
+ list.add(new PluginConfigItem("chatCommands", "Chat Commands", "Allow ::highlight / ::unhighlight / ::hide in chat", true));
+ return list;
+ }
+
+ @Override
+ public void onConfigChanged(String key, Object value) {
+ if ("showNames".equals(key)) showNames = (Boolean) value;
+ else if ("highlightedItems".equals(key)) highlightedItems = (String) value;
+ else if ("hiddenItems".equals(key)) hiddenItems = (String) value;
+ else if ("collapseEntries".equals(key)) collapseEntries = (Boolean) value;
+ else if ("showQuantities".equals(key)) showQuantities = (Boolean) value;
+ else if ("showValues".equals(key)) showValues = (Boolean) value;
+ else if ("showLootbeam".equals(key)) showLootbeam = (Boolean) value;
+ else if ("deprioritizeHidden".equals(key)) deprioritizeHidden = (Boolean) value;
+ else if ("lowValueThreshold".equals(key)) lowValueThreshold = ((Number) value).intValue();
+ else if ("mediumValueThreshold".equals(key)) mediumValueThreshold = ((Number) value).intValue();
+ else if ("highValueThreshold".equals(key)) highValueThreshold = ((Number) value).intValue();
+ else if ("insaneValueThreshold".equals(key)) insaneValueThreshold = ((Number) value).intValue();
+ else if ("boxOpacity".equals(key)) boxOpacity = ((Number) value).intValue();
+ else if ("textOpacity".equals(key)) textOpacity = ((Number) value).intValue();
+ }
+
+ /**
+ * Grouped item entry for rendering vertically stacked on a tile.
+ */
+ private static class DisplayItem {
+ final int id;
+ final String name;
+ int amount;
+ final int singleValue;
+ long totalValue;
+ final boolean isHighlighted;
+ final int color;
+
+ DisplayItem(PluginContext.GroundItemWrapper item, boolean isHighlighted, int color) {
+ this.id = item.id;
+ this.name = item.name;
+ this.amount = item.amount;
+ this.singleValue = item.value;
+ this.totalValue = item.totalValue;
+ this.isHighlighted = isHighlighted;
+ this.color = color;
+ }
+
+ void addAmount(int add) {
+ this.amount += add;
+ this.totalValue = (long) this.singleValue * this.amount;
+ }
+ }
+
+ @Override
+ public void onRenderOverlay(PluginGraphics g) {
+ if (!showNames || ctx == null || !ctx.isLoggedIn()) return;
+
+ List rawItems = ctx.getGroundItems();
+ if (rawItems == null || rawItems.isEmpty()) return;
+
+ // Group items by tile: key = (worldX << 16) | (worldY & 0xffff)
+ Map> tileMap = new LinkedHashMap<>();
+ Map tileCoords = new HashMap<>();
+
+ for (PluginContext.GroundItemWrapper raw : rawItems) {
+ if (raw.getDistance() > 20) continue;
+
+ // Check hidden filter
+ if (isItemHidden(raw.name)) {
+ continue;
+ }
+
+ boolean isHl = isItemHighlighted(raw.name);
+ int color = getItemColor(raw.name, raw.totalValue, isHl);
+
+ long tileKey = (((long) raw.worldX) << 32) | (raw.worldY & 0xffffffffL);
+ List list = tileMap.computeIfAbsent(tileKey, k -> new ArrayList<>());
+ tileCoords.putIfAbsent(tileKey, new int[]{raw.worldX, raw.worldY});
+
+ if (collapseEntries) {
+ // Check if identical item already on tile
+ DisplayItem existing = null;
+ for (DisplayItem d : list) {
+ if (d.id == raw.id) {
+ existing = d;
+ break;
+ }
+ }
+ if (existing != null) {
+ existing.addAmount(raw.amount);
+ continue;
+ }
+ }
+
+ list.add(new DisplayItem(raw, isHl, color));
+ }
+
+ // Render each tile's stacked items
+ for (Map.Entry> entry : tileMap.entrySet()) {
+ long tileKey = entry.getKey();
+ List itemsOnTile = entry.getValue();
+ if (itemsOnTile.isEmpty()) continue;
+
+ int[] coords = tileCoords.get(tileKey);
+ int tileX = coords[0];
+ int tileY = coords[1];
+
+ // Sort so most valuable / highlighted items are on top
+ Collections.sort(itemsOnTile, (a, b) -> {
+ if (a.isHighlighted != b.isHighlighted) {
+ return a.isHighlighted ? 1 : -1;
+ }
+ return Long.compare(a.totalValue, b.totalValue);
+ });
+
+ // Check if tile qualifies for a lootbeam
+ if (showLootbeam) {
+ DisplayItem bestItem = itemsOnTile.get(itemsOnTile.size() - 1);
+ if (bestItem.isHighlighted || bestItem.totalValue >= highValueThreshold) {
+ g.drawLootbeam(tileX, tileY, bestItem.color);
+ }
+ }
+
+ // Project ground coordinates
+ int[] screen = g.worldToScreen(tileX, tileY, 20);
+ if (screen == null) continue;
+
+ int baseX = screen[0];
+ int baseY = screen[1];
+
+ // Render items vertically stacked with offset
+ for (int i = 0; i < itemsOnTile.size(); i++) {
+ DisplayItem item = itemsOnTile.get(i);
+ int rowY = baseY - (i * 14);
+
+ String label = buildItemLabel(item);
+ int textW = g.getTextWidth(label);
+ int boxX = baseX - (textW / 2) - 3;
+ int boxY = rowY - 11;
+ int boxW = textW + 6;
+ int boxH = 13;
+
+ // Soft translucent background pill box
+ if (boxOpacity > 0) {
+ g.fillRect(boxX, boxY, boxW, boxH, 0x000000, boxOpacity);
+ }
+
+ // Highlighted / Insane items get colored borders
+ if (item.isHighlighted || item.totalValue >= insaneValueThreshold) {
+ g.drawRect(boxX, boxY, boxW, boxH, item.color);
+ } else if (item.totalValue >= highValueThreshold) {
+ g.drawRect(boxX, boxY, boxW, boxH, 0x4a4338);
+ }
+
+ // Render text with configured alpha transparency
+ g.drawCenteredString(label, baseX, rowY - 1, item.color, textOpacity);
+ }
+ }
+ }
+
+ /**
+ * Deprioritizes left-click Take for hidden items below 'Walk here'.
+ */
+ @Override
+ public void onPreMenuRender(List entries) {
+ if (!deprioritizeHidden || entries == null || entries.size() <= 1) return;
+
+ // Default left-click action is at the end of the entries list
+ int topIdx = entries.size() - 1;
+ MenuEntry top = entries.get(topIdx);
+
+ if ("Take".equalsIgnoreCase(top.getAction())) {
+ String targetName = MenuEntry.stripColorTags(top.getTarget());
+ if (isItemHidden(targetName)) {
+ // Find Walk here entry
+ int walkIdx = -1;
+ for (int i = 0; i < entries.size(); i++) {
+ String clean = MenuEntry.stripColorTags(entries.get(i).getRawText()).toLowerCase();
+ if (clean.startsWith("walk here") || clean.startsWith("walk")) {
+ walkIdx = i;
+ break;
+ }
+ }
+ if (walkIdx != -1 && walkIdx != topIdx) {
+ // Promote Walk here to the top (default left click)
+ MenuEntry walk = entries.remove(walkIdx);
+ entries.add(walk);
+ }
+ }
+ }
+ }
+
+ private String buildItemLabel(DisplayItem item) {
+ StringBuilder sb = new StringBuilder(item.name);
+ if (showQuantities && item.amount > 1) {
+ sb.append(" (").append(formatQuantity(item.amount)).append(")");
+ }
+ if (showValues && item.totalValue > 0) {
+ sb.append(" [").append(formatValue(item.totalValue)).append("]");
+ }
+ return sb.toString();
+ }
+
+ private int getItemColor(String name, long totalValue, boolean isHighlighted) {
+ if (isHighlighted) return COLOR_HIGHLIGHT;
+ if (totalValue >= insaneValueThreshold) return COLOR_INSANE;
+ if (totalValue >= highValueThreshold) return COLOR_HIGH;
+ if (totalValue >= mediumValueThreshold) return COLOR_MEDIUM;
+ if (totalValue >= lowValueThreshold) return COLOR_LOW;
+ return COLOR_COMMON;
+ }
+
+ public boolean isItemHighlighted(String name) {
+ return matchesAnyPattern(name, highlightedItems);
+ }
+
+ public boolean isItemHidden(String name) {
+ return matchesAnyPattern(name, hiddenItems);
+ }
+
+ private static boolean matchesAnyPattern(String text, String commaSeparatedPatterns) {
+ if (text == null || commaSeparatedPatterns == null || commaSeparatedPatterns.trim().isEmpty()) {
+ return false;
+ }
+ String cleanText = text.trim().toLowerCase();
+ String[] patterns = commaSeparatedPatterns.split(",");
+ for (String p : patterns) {
+ String pat = p.trim().toLowerCase();
+ if (pat.isEmpty()) continue;
+ if (matchesWildcard(cleanText, pat)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean matchesWildcard(String text, String pattern) {
+ if ("*".equals(pattern)) return true;
+ if (pattern.startsWith("*") && pattern.endsWith("*")) {
+ String mid = pattern.substring(1, pattern.length() - 1);
+ return text.contains(mid);
+ }
+ if (pattern.startsWith("*")) {
+ return text.endsWith(pattern.substring(1));
+ }
+ if (pattern.endsWith("*")) {
+ return text.startsWith(pattern.substring(0, pattern.length() - 1));
+ }
+ return text.equals(pattern);
+ }
+
+ private static String formatQuantity(int amount) {
+ if (amount >= 10000000) return (amount / 1000000) + "m";
+ if (amount >= 100000) return (amount / 1000) + "k";
+ if (amount >= 1000) {
+ DecimalFormat df = new DecimalFormat("#,###");
+ return df.format(amount);
+ }
+ return String.valueOf(amount);
+ }
+
+ private static String formatValue(long value) {
+ if (value >= 10000000) return (value / 1000000) + "M gp";
+ if (value >= 1000000) return String.format("%.1fM gp", value / 1000000.0);
+ if (value >= 1000) return (value / 1000) + "k gp";
+ return value + " gp";
+ }
+
+ @Override
+ public boolean onCommand(String command, String[] args) {
+ String cmd = command.toLowerCase();
+
+ if ("highlight".equals(cmd) || "hl".equals(cmd)) {
+ if (args.length > 0) {
+ String item = joinArgs(args);
+ highlightedItems = (highlightedItems != null && !highlightedItems.isEmpty()) ? highlightedItems + ", " + item : item;
+ if (ctx != null) ctx.sendClientMessage("Added to ground item highlights: " + item);
+ } else if (ctx != null) {
+ ctx.sendClientMessage("Usage: ::highlight - ");
+ }
+ return true;
+ }
+
+ if ("unhighlight".equals(cmd) || "unhl".equals(cmd)) {
+ if (args.length > 0) {
+ String item = joinArgs(args);
+ highlightedItems = removePattern(highlightedItems, item);
+ if (ctx != null) ctx.sendClientMessage("Removed from ground item highlights: " + item);
+ }
+ return true;
+ }
+
+ if ("hide".equals(cmd)) {
+ if (args.length > 0) {
+ String item = joinArgs(args);
+ hiddenItems = (hiddenItems != null && !hiddenItems.isEmpty()) ? hiddenItems + ", " + item : item;
+ if (ctx != null) ctx.sendClientMessage("Added to hidden ground items: " + item);
+ } else if (ctx != null) {
+ ctx.sendClientMessage("Usage: ::hide
- ");
+ }
+ return true;
+ }
+
+ if ("unhide".equals(cmd)) {
+ if (args.length > 0) {
+ String item = joinArgs(args);
+ hiddenItems = removePattern(hiddenItems, item);
+ if (ctx != null) ctx.sendClientMessage("Removed from hidden ground items: " + item);
+ }
+ return true;
+ }
+
+ if ("grounditems".equals(cmd) || "gi".equals(cmd)) {
+ if (ctx != null) {
+ ctx.sendClientMessage("Ground Items Config: [Highlighted: " + highlightedItems + "]");
+ ctx.sendClientMessage("Hidden: [" + hiddenItems + "]");
+ ctx.sendClientMessage("Tiers: Low=" + lowValueThreshold + "gp, Med=" + mediumValueThreshold + "gp, High=" + highValueThreshold + "gp, Insane=" + insaneValueThreshold + "gp");
+ }
+ return true;
+ }
+
+ return false;
+ }
+
+ private static String joinArgs(String[] args) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < args.length; i++) {
+ if (i > 0) sb.append(" ");
+ sb.append(args[i]);
+ }
+ return sb.toString().trim();
+ }
+
+ private static String removePattern(String csv, String target) {
+ if (csv == null || target == null) return csv;
+ String[] parts = csv.split(",");
+ StringBuilder sb = new StringBuilder();
+ for (String p : parts) {
+ String trimmed = p.trim();
+ if (!trimmed.equalsIgnoreCase(target.trim()) && !trimmed.isEmpty()) {
+ if (sb.length() > 0) sb.append(", ");
+ sb.append(trimmed);
+ }
+ }
+ return sb.toString();
+ }
+
+ public int getBoxOpacity() {
+ return boxOpacity;
+ }
+
+ public void setBoxOpacity(int boxOpacity) {
+ this.boxOpacity = Math.max(0, Math.min(255, boxOpacity));
+ }
+
+ public int getTextOpacity() {
+ return textOpacity;
+ }
+
+ public void setTextOpacity(int textOpacity) {
+ this.textOpacity = Math.max(50, Math.min(255, textOpacity));
+ }
+}
diff --git a/2006Scape Client/src/main/java/HD317Pipeline.java b/2006Scape Client/src/main/java/HD317Pipeline.java
new file mode 100644
index 00000000..24ac0835
--- /dev/null
+++ b/2006Scape Client/src/main/java/HD317Pipeline.java
@@ -0,0 +1,577 @@
+// 317HD / RLHD Pure-Java Bridge & Shared Shader/Matrix Definitions for 2006Scape Client
+// Compiles safely across both Desktop and Android targets with zero platform imports.
+
+public final class HD317Pipeline {
+
+ public interface HdRendererBackend {
+ boolean isGpuReady();
+ void onSceneLoad(Game game, ObjectManager objectManager, WorldController worldController);
+ void beginFrame(Game game, int xCam, int yCam, int zCam, int pitch, int yaw);
+ void drawSimpleTile(Class43 tile, int plane, int tileX, int tileZ);
+ void drawShapedTile(Class40 tile, int plane, int tileX, int tileZ);
+ void drawModel(Model model, int orientation, int sinPitch, int cosPitch, int sinYaw, int cosYaw,
+ int relX, int relY, int relZ, int uid);
+ void endFrame(int[] dstPixels, int width, int height);
+ void onToggle(boolean enabled);
+ default void onStaticChunkInvalidated(int tileX, int tileZ) {}
+ }
+
+ public static volatile HdRendererBackend backend = null;
+ public static boolean useStaticScenery = true;
+ public static boolean drawingWall = false;
+ public static boolean drawingAnimatedObj = false;
+ public static int drawingPlane = 0;
+
+ // Runtime 317HD Plugin Configuration
+ public static volatile boolean cfgShadowsEnabled = true;
+ public static volatile int cfgShadowResolution = 1024;
+ public static volatile boolean cfgShadowSoftPcf = true;
+ public static volatile boolean cfgDynamicLights = true;
+ public static volatile boolean cfgAtmosphericFog = true;
+ public static volatile boolean cfgGroundTextures = true;
+ public static volatile boolean cfgNormalMapping = true;
+ public static volatile boolean cfgWaterShader = true;
+ public static volatile float cfgSaturation = 1.0f;
+ public static volatile float cfgBrightness = 1.0f;
+ public static volatile boolean cfgContrastCurve = true;
+
+ public static boolean isGpuActive() {
+ return ClientSettings.HD_317 && backend != null && backend.isGpuReady();
+ }
+
+ public static void onSceneLoad(Game game, ObjectManager objectManager, WorldController worldController) {
+ HdRendererBackend b = backend;
+ if (b != null) {
+ b.onSceneLoad(game, objectManager, worldController);
+ }
+ }
+
+ public static void beginFrame(Game game, int xCam, int yCam, int zCam, int pitch, int yaw) {
+ if (!ClientSettings.HD_317) return;
+ HdRendererBackend b = backend;
+ if (b != null) {
+ b.beginFrame(game, xCam, yCam, zCam, pitch, yaw);
+ }
+ }
+
+ public static void drawSimpleTile(Class43 tile, int plane, int tileX, int tileZ) {
+ HdRendererBackend b = backend;
+ if (b != null) {
+ b.drawSimpleTile(tile, plane, tileX, tileZ);
+ }
+ }
+
+ public static void drawShapedTile(Class40 tile, int plane, int tileX, int tileZ) {
+ HdRendererBackend b = backend;
+ if (b != null) {
+ b.drawShapedTile(tile, plane, tileX, tileZ);
+ }
+ }
+
+ public static void drawModel(Model model, int orientation, int sinPitch, int cosPitch, int sinYaw, int cosYaw,
+ int relX, int relY, int relZ, int uid) {
+ HdRendererBackend b = backend;
+ if (b != null) {
+ b.drawModel(model, orientation, sinPitch, cosPitch, sinYaw, cosYaw, relX, relY, relZ, uid);
+ }
+ }
+
+ public static void endFrame(int[] dstPixels, int width, int height) {
+ if (!ClientSettings.HD_317) return;
+ HdRendererBackend b = backend;
+ if (b != null) {
+ b.endFrame(dstPixels, width, height);
+ }
+ }
+
+ public static void onToggle(boolean enabled) {
+ HdRendererBackend b = backend;
+ if (b != null) {
+ b.onToggle(enabled);
+ }
+ }
+
+ public static void invalidateStaticChunk(int tileX, int tileZ) {
+ if (!useStaticScenery || !isGpuActive()) return;
+ HdRendererBackend b = backend;
+ if (b != null) {
+ b.onStaticChunkInvalidated(tileX, tileZ);
+ }
+ }
+
+ // =========================================================================
+ // SHARED GLSL SHADERS (GLSL ES 3.00 / Desktop GLSL 3.30 Core)
+ // =========================================================================
+
+ public static final String SHADOW_VERT =
+ "#version 300 es\n" +
+ "precision highp float;\n" +
+ "layout(location = 0) in vec3 aPos;\n" +
+ "layout(location = 2) in vec2 aUv;\n" +
+ "layout(location = 4) in vec4 aMatAndBary;\n" +
+ "uniform mat4 uLightViewProj;\n" +
+ "out vec2 vUv;\n" +
+ "flat out float vMatId;\n" +
+ "void main() {\n" +
+ " vUv = aUv;\n" +
+ " vMatId = aMatAndBary.x;\n" +
+ " gl_Position = uLightViewProj * vec4(aPos, 1.0);\n" +
+ "}\n";
+
+ public static final String SHADOW_FRAG =
+ "#version 300 es\n" +
+ "precision mediump float;\n" +
+ "precision mediump sampler2DArray;\n" +
+ "in vec2 vUv;\n" +
+ "flat in float vMatId;\n" +
+ "uniform sampler2DArray uDiffuseArray;\n" +
+ "void main() {\n" +
+ " if (vMatId >= 0.0 && vMatId < 49.5) {\n" +
+ " float a = textureLod(uDiffuseArray, vec3(vUv, floor(vMatId + 0.5)), 0.0).a;\n" +
+ " if (a < 0.5) discard;\n" +
+ " }\n" +
+ "}\n";
+
+ public static final String SCENE_VERT =
+ "#version 300 es\n" +
+ "precision highp float;\n" +
+ "layout(location = 0) in vec3 aPos;\n" +
+ "layout(location = 1) in vec3 aNormal;\n" +
+ "layout(location = 2) in vec2 aUv;\n" +
+ "layout(location = 3) in vec4 aColor;\n" +
+ "layout(location = 4) in vec4 aMatAndBary;\n" +
+ "\n" +
+ "uniform mat4 uViewProj;\n" +
+ "uniform mat4 uLightViewProj;\n" +
+ "\n" +
+ "out vec3 vWorldPos;\n" +
+ "out vec3 vNormal;\n" +
+ "out vec2 vUv;\n" +
+ "out vec4 vColor;\n" +
+ "out vec3 vBary;\n" +
+ "out vec4 vLightSpacePos;\n" +
+ "flat out vec3 vMatIds;\n" +
+ "flat out float vSurfType;\n" +
+ "\n" +
+ "void main() {\n" +
+ " vWorldPos = aPos;\n" +
+ " vNormal = aNormal;\n" +
+ " vUv = aUv;\n" +
+ " vColor = aColor;\n" +
+ " vMatIds = aMatAndBary.xyz;\n" +
+ " float packedVal = aMatAndBary.w;\n" +
+ " float intPart = floor(packedVal);\n" +
+ " float faceBias = packedVal - intPart;\n" +
+ " float bIdx = mod(intPart, 4.0);\n" +
+ " float planeAndSurf = floor(intPart / 4.0);\n" +
+ " float vPlane = floor(planeAndSurf / 8.0);\n" +
+ " vSurfType = planeAndSurf - vPlane * 8.0;\n" +
+ " if (bIdx < 0.5) vBary = vec3(1.0, 0.0, 0.0);\n" +
+ " else if (bIdx < 1.5) vBary = vec3(0.0, 1.0, 0.0);\n" +
+ " else vBary = vec3(0.0, 0.0, 1.0);\n" +
+ " vLightSpacePos = uLightViewProj * vec4(aPos, 1.0);\n" +
+ " vec4 pos = uViewProj * vec4(aPos, 1.0);\n" +
+ " float worldBias = vPlane * 3.0;\n" +
+ " if (vSurfType > 3.5) {\n" +
+ " worldBias += faceBias * 0.4;\n" +
+ " } else if (vSurfType > 2.5) {\n" +
+ " worldBias += 1.8 + faceBias * 0.8;\n" +
+ " } else if (vSurfType > 0.5 && vSurfType < 1.5) {\n" +
+ " worldBias += 0.5 + faceBias * 1.2;\n" +
+ " }\n" +
+ " pos.z -= (worldBias * 100.0) / max(pos.w, 100.0);\n" +
+ " gl_Position = pos;\n" +
+ "}\n";
+
+ public static final String SCENE_FRAG =
+ "#version 300 es\n" +
+ "precision highp float;\n" +
+ "precision highp sampler2DArray;\n" +
+ "\n" +
+ "in vec3 vWorldPos;\n" +
+ "in vec3 vNormal;\n" +
+ "in vec2 vUv;\n" +
+ "in vec4 vColor;\n" +
+ "in vec3 vBary;\n" +
+ "in vec4 vLightSpacePos;\n" +
+ "flat in vec3 vMatIds;\n" +
+ "flat in float vSurfType;\n" +
+ "\n" +
+ "uniform sampler2DArray uDiffuseArray;\n" +
+ "uniform sampler2DArray uNormalArray;\n" +
+ "uniform sampler2DShadow uShadowMap;\n" +
+ "\n" +
+ "uniform vec3 uCameraPos;\n" +
+ "uniform vec3 uSunDir;\n" +
+ "uniform vec3 uSunColor;\n" +
+ "uniform vec3 uAmbientColor;\n" +
+ "uniform vec3 uSkyColor;\n" +
+ "uniform vec3 uFogColor;\n" +
+ "uniform float uFogMin;\n" +
+ "uniform float uFogMax;\n" +
+ "uniform float uTime;\n" +
+ "uniform float uShadowTexelSize;\n" +
+ "uniform int uShadowsEnabled;\n" +
+ "uniform int uShadowSoftPcf;\n" +
+ "uniform int uGroundTextures;\n" +
+ "uniform int uNormalMapping;\n" +
+ "uniform int uWaterShader;\n" +
+ "uniform float uSaturation;\n" +
+ "uniform float uBrightness;\n" +
+ "uniform int uContrastCurve;\n" +
+ "\n" +
+ "uniform int uLightCount;\n" +
+ "uniform vec4 uLightPosRad[16];\n" +
+ "uniform vec4 uLightColorInt[16];\n" +
+ "\n" +
+ "out vec4 fragColor;\n" +
+ "\n" +
+ "vec3 perturbTerrainNormal(vec3 N, vec3 tsNormal) {\n" +
+ " vec3 T = normalize(vec3(1.0, 0.0, 0.0) - N * N.x);\n" +
+ " vec3 B = cross(N, T);\n" +
+ " return normalize(T * tsNormal.x + B * tsNormal.y + N * tsNormal.z);\n" +
+ "}\n" +
+ "\n" +
+ "vec3 perturbNormalAnalytical(vec3 N, vec3 tsNormal) {\n" +
+ " vec3 up = abs(N.y) < 0.999 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0);\n" +
+ " vec3 T = normalize(cross(up, N));\n" +
+ " vec3 B = cross(N, T);\n" +
+ " return normalize(T * tsNormal.x + B * tsNormal.y + N * tsNormal.z);\n" +
+ "}\n" +
+ "\n" +
+ "float sampleShadowMap(vec4 lightSpacePos, vec3 geomN) {\n" +
+ " vec3 projCoords = lightSpacePos.xyz / lightSpacePos.w;\n" +
+ " projCoords = projCoords * 0.5 + 0.5;\n" +
+ " if (projCoords.x <= 0.01 || projCoords.x >= 0.99 || projCoords.y <= 0.01 || projCoords.y >= 0.99 || projCoords.z >= 0.999) {\n" +
+ " return 0.0;\n" +
+ " }\n" +
+ " float currentDepth = projCoords.z;\n" +
+ " float cosTheta = max(dot(geomN, uSunDir), 0.0);\n" +
+ " float bias = max(0.0016 * (1.0 - cosTheta), 0.0004);\n" +
+ " float refDepth = currentDepth - bias;\n" +
+ " float shadow;\n" +
+ " if (uShadowSoftPcf == 0) {\n" +
+ " shadow = 1.0 - texture(uShadowMap, vec3(projCoords.xy, refDepth));\n" +
+ " } else {\n" +
+ " float r = uShadowTexelSize * 0.75;\n" +
+ " float lit = texture(uShadowMap, vec3(projCoords.xy + vec2(-r, -r), refDepth));\n" +
+ " lit += texture(uShadowMap, vec3(projCoords.xy + vec2( r, -r), refDepth));\n" +
+ " lit += texture(uShadowMap, vec3(projCoords.xy + vec2(-r, r), refDepth));\n" +
+ " lit += texture(uShadowMap, vec3(projCoords.xy + vec2( r, r), refDepth));\n" +
+ " shadow = 1.0 - lit * 0.25;\n" +
+ " }\n" +
+ " vec2 edgeDist = min(projCoords.xy, 1.0 - projCoords.xy);\n" +
+ " float edgeFade = smoothstep(0.01, 0.08, min(edgeDist.x, edgeDist.y));\n" +
+ " return shadow * edgeFade;\n" +
+ "}\n" +
+ "\n" +
+ "void main() {\n" +
+ " vec3 geomN = length(vNormal) > 1e-4 ? normalize(vNormal) : vec3(0.0, -1.0, 0.0);\n" +
+ " vec3 viewVec = uCameraPos - vWorldPos;\n" +
+ " float distToCam = length(viewVec);\n" +
+ " vec3 V = viewVec / max(distToCam, 1e-4);\n" +
+ "\n" +
+ " float texLod = clamp(log2(max(distToCam, 550.0) / 720.0), 0.0, 2.2);\n" +
+ "\n" +
+ " vec3 baseAlbedo = vColor.rgb;\n" +
+ " float outAlpha = vColor.a;\n" +
+ " vec3 N = geomN;\n" +
+ " float specStrength = 0.10;\n" +
+ " float specGloss = 16.0;\n" +
+ " bool isEmissive = false;\n" +
+ "\n" +
+ " if (vSurfType > 1.5 && vSurfType < 2.5) {\n" +
+ " if (uWaterShader != 0) {\n" +
+ " vec2 wUv1 = vWorldPos.xz / 160.0 + vec2(uTime * 0.028, uTime * 0.018);\n" +
+ " vec2 wUv2 = vWorldPos.xz / 120.0 - vec2(uTime * 0.022, -uTime * 0.025);\n" +
+ " vec3 wn1 = textureLod(uNormalArray, vec3(wUv1, 62.0), texLod).rgb * 2.0 - 1.0;\n" +
+ " vec3 wn2 = textureLod(uNormalArray, vec3(wUv2, 63.0), texLod).rgb * 2.0 - 1.0;\n" +
+ " vec3 waveTs = normalize(vec3(wn1.xy + wn2.xy, 1.6));\n" +
+ " N = perturbNormalAnalytical(geomN, normalize(vec3(waveTs.x * 0.32, waveTs.y * 0.32, waveTs.z)));\n" +
+ " float fresnel = pow(1.0 - max(dot(N, V), 0.0), 3.0);\n" +
+ " vec3 deepWater = vec3(0.14, 0.28, 0.42);\n" +
+ " vec3 shallowWater = vec3(0.24, 0.44, 0.54);\n" +
+ " baseAlbedo = mix(deepWater, mix(shallowWater, uSkyColor, 0.55), clamp(fresnel * 0.80, 0.0, 0.88));\n" +
+ " specStrength = 0.45;\n" +
+ " specGloss = 96.0;\n" +
+ " } else {\n" +
+ " baseAlbedo = vec3(0.16, 0.32, 0.48);\n" +
+ " specStrength = 0.15;\n" +
+ " specGloss = 32.0;\n" +
+ " }\n" +
+ " } else if (vSurfType < 0.5) {\n" +
+ " if (uGroundTextures != 0) {\n" +
+ " float mA = floor(vMatIds.x + 0.5);\n" +
+ " float mB = floor(vMatIds.y + 0.5);\n" +
+ " float mC = floor(vMatIds.z + 0.5);\n" +
+ " vec4 dSample;\n" +
+ " vec4 nSample;\n" +
+ " if (abs(mA - mB) < 0.1 && abs(mB - mC) < 0.1) {\n" +
+ " dSample = textureLod(uDiffuseArray, vec3(vUv, max(0.0, mA)), texLod);\n" +
+ " nSample = (uNormalMapping != 0) ? textureLod(uNormalArray, vec3(vUv, max(0.0, mA)), texLod) : vec4(0.5, 0.5, 1.0, 0.0);\n" +
+ " } else {\n" +
+ " vec4 dA = textureLod(uDiffuseArray, vec3(vUv, max(0.0, mA)), texLod);\n" +
+ " vec4 dB = textureLod(uDiffuseArray, vec3(vUv, max(0.0, mB)), texLod);\n" +
+ " vec4 dC = textureLod(uDiffuseArray, vec3(vUv, max(0.0, mC)), texLod);\n" +
+ "\n" +
+ " float hA = dA.a * 0.90 + vBary.x;\n" +
+ " float hB = dB.a * 0.90 + vBary.y;\n" +
+ " float hC = dC.a * 0.90 + vBary.z;\n" +
+ " float maxH = max(hA, max(hB, hC)) - 0.20;\n" +
+ " vec3 w = max(vec3(hA, hB, hC) - maxH, 0.0001);\n" +
+ " w /= (w.x + w.y + w.z);\n" +
+ " dSample = dA * w.x + dB * w.y + dC * w.z;\n" +
+ " if (uNormalMapping != 0) {\n" +
+ " vec4 nA = textureLod(uNormalArray, vec3(vUv, max(0.0, mA)), texLod);\n" +
+ " vec4 nB = textureLod(uNormalArray, vec3(vUv, max(0.0, mB)), texLod);\n" +
+ " vec4 nC = textureLod(uNormalArray, vec3(vUv, max(0.0, mC)), texLod);\n" +
+ " nSample = nA * w.x + nB * w.y + nC * w.z;\n" +
+ " } else {\n" +
+ " nSample = vec4(0.5, 0.5, 1.0, 0.0);\n" +
+ " }\n" +
+ " }\n" +
+ "\n" +
+ " baseAlbedo = vColor.rgb * dSample.rgb;\n" +
+ " if (uNormalMapping != 0) {\n" +
+ " vec3 tsN = normalize(nSample.rgb * 2.0 - 1.0);\n" +
+ " float dominantMat = (vBary.x > vBary.y && vBary.x > vBary.z) ? mA : (vBary.y > vBary.z ? mB : mC);\n" +
+ " if (dominantMat >= 53.0 && dominantMat <= 57.5) {\n" +
+ " specStrength = 0.08 * nSample.a;\n" +
+ " specGloss = 18.0;\n" +
+ " N = perturbTerrainNormal(geomN, normalize(vec3(tsN.xy * 0.40, tsN.z)));\n" +
+ " } else {\n" +
+ " specStrength = 0.02 * nSample.a;\n" +
+ " specGloss = 10.0;\n" +
+ " N = perturbTerrainNormal(geomN, normalize(vec3(tsN.xy * 0.25, tsN.z)));\n" +
+ " }\n" +
+ " }\n" +
+ " }\n" +
+ " } else {\n" +
+ " float mId = floor(vMatIds.x + 0.5);\n" +
+ " if (mId >= 0.0) {\n" +
+ " vec2 modelUv = vUv;\n" +
+ " bool isWaterDroplet = (mId == 24.0 || mId == 17.0);\n" +
+ " if (isWaterDroplet) {\n" +
+ " modelUv.y -= uTime * 0.48;\n" +
+ " }\n" +
+ " float modelLod = isWaterDroplet ? 0.0 : texLod;\n" +
+ " vec4 dSample = textureLod(uDiffuseArray, vec3(modelUv, mId), modelLod);\n" +
+ " if (isWaterDroplet) {\n" +
+ " if (dSample.a < 0.25) discard;\n" +
+ " baseAlbedo = dSample.rgb;\n" +
+ " outAlpha = clamp(dSample.a * 0.85, 0.0, 0.85) * vColor.a;\n" +
+ " } else {\n" +
+ " if (mId < 49.5 && dSample.a < 0.5) discard;\n" +
+ " baseAlbedo = dSample.rgb * vColor.rgb;\n" +
+ " }\n" +
+ " if (uNormalMapping != 0) {\n" +
+ " vec4 nSample = textureLod(uNormalArray, vec3(modelUv, mId), modelLod);\n" +
+ " vec3 tsN = normalize(nSample.rgb * 2.0 - 1.0);\n" +
+ " N = perturbNormalAnalytical(geomN, tsN);\n" +
+ " specStrength = isWaterDroplet ? 0.45 : (0.12 * nSample.a);\n" +
+ " specGloss = isWaterDroplet ? 48.0 : 18.0;\n" +
+ " }\n" +
+ " isEmissive = (mId == 31.0 || mId == 40.0);\n" +
+ " }\n" +
+ " }\n" +
+ "\n" +
+ " float wrapDiff = max(0.0, (dot(N, uSunDir) + 0.18) / 1.18);\n" +
+ " float shadow = (uShadowsEnabled != 0 && !isEmissive && wrapDiff > 0.001) ? sampleShadowMap(vLightSpacePos, geomN) : 0.0;\n" +
+ " float sunVis = 1.0 - shadow * 0.65;\n" +
+ "\n" +
+ " vec3 ambient = uAmbientColor * (0.58 + 0.18 * max(-N.y, 0.0));\n" +
+ " vec3 direct = uSunColor * wrapDiff * 0.64 * sunVis;\n" +
+ "\n" +
+ " vec3 H = normalize(uSunDir + V);\n" +
+ " float spec = pow(max(dot(N, H), 0.0), specGloss) * specStrength * sunVis;\n" +
+ " vec3 specColor = uSunColor * spec;\n" +
+ "\n" +
+ " vec3 pointLightSum = vec3(0.0);\n" +
+ " for (int i = 0; i < uLightCount; ++i) {\n" +
+ " vec3 lVec = uLightPosRad[i].xyz - vWorldPos;\n" +
+ " float rad = uLightPosRad[i].w;\n" +
+ " float d2 = dot(lVec, lVec);\n" +
+ " if (d2 < rad * rad) {\n" +
+ " float d = sqrt(d2);\n" +
+ " float atten = 1.0 - (d / rad);\n" +
+ " atten = atten * atten;\n" +
+ " vec3 L = lVec / max(d, 1.0);\n" +
+ " float pDiff = max(dot(N, L), 0.25);\n" +
+ " pointLightSum += uLightColorInt[i].rgb * (uLightColorInt[i].w * atten * pDiff);\n" +
+ " }\n" +
+ " }\n" +
+ "\n" +
+ " vec3 litColor = isEmissive ? (baseAlbedo * 1.35) : (baseAlbedo * (ambient + direct + pointLightSum) + specColor);\n" +
+ "\n" +
+ " if (distToCam > uFogMin) {\n" +
+ " float fogT = clamp((distToCam - uFogMin) / max(1.0, uFogMax - uFogMin), 0.0, 1.0);\n" +
+ " fogT = fogT * fogT * (3.0 - 2.0 * fogT);\n" +
+ " litColor = mix(litColor, uFogColor, fogT);\n" +
+ " }\n" +
+ "\n" +
+ " litColor *= uBrightness;\n" +
+ " float luma = dot(litColor, vec3(0.299, 0.587, 0.114));\n" +
+ " litColor = mix(vec3(luma), litColor, uSaturation);\n" +
+ "\n" +
+ " fragColor = vec4(clamp(litColor, 0.0, 1.0), outAlpha);\n" +
+ "}\n";
+
+ public static final String SCENE_FRAG_DIRECT = SCENE_FRAG.replace(
+ " fragColor = vec4(clamp(litColor, 0.0, 1.0), outAlpha);\n",
+ " vec3 col = clamp(litColor, 0.0, 1.0);\n" +
+ " if (uContrastCurve != 0) {\n" +
+ " col = mix(col, col * col * (3.0 - 2.0 * col), 0.12);\n" +
+ " }\n" +
+ " fragColor = vec4(col.b, col.g, col.r, outAlpha);\n"
+ );
+
+ public static final String POST_VERT =
+ "#version 300 es\n" +
+ "precision highp float;\n" +
+ "layout(location = 0) in vec2 aQuadPos;\n" +
+ "out vec2 vUv;\n" +
+ "void main() {\n" +
+ " vUv = vec2(aQuadPos.x * 0.5 + 0.5, 0.5 - aQuadPos.y * 0.5);\n" +
+ " gl_Position = vec4(aQuadPos, 0.0, 1.0);\n" +
+ "}\n";
+
+ public static final String POST_FRAG =
+ "#version 300 es\n" +
+ "precision mediump float;\n" +
+ "in vec2 vUv;\n" +
+ "uniform sampler2D uSceneTex;\n" +
+ "uniform vec2 uTexelSize;\n" +
+ "out vec4 fragColor;\n" +
+ "void main() {\n" +
+ " vec4 scene = texture(uSceneTex, vUv);\n" +
+ " vec3 col = scene.rgb;\n" +
+ " if (scene.a < 0.01) {\n" +
+ " float skyT = clamp((vUv.y - 0.25) * 1.35, 0.0, 1.0);\n" +
+ " col = mix(col, col * vec3(0.52, 0.72, 0.95), skyT);\n" +
+ " }\n" +
+ " vec3 b1 = texture(uSceneTex, vUv + vec2(-2.5, -2.5) * uTexelSize).rgb;\n" +
+ " vec3 b2 = texture(uSceneTex, vUv + vec2( 2.5, -2.5) * uTexelSize).rgb;\n" +
+ " vec3 b3 = texture(uSceneTex, vUv + vec2(-2.5, 2.5) * uTexelSize).rgb;\n" +
+ " vec3 b4 = texture(uSceneTex, vUv + vec2( 2.5, 2.5) * uTexelSize).rgb;\n" +
+ " vec3 avg = (b1 + b2 + b3 + b4) * 0.25;\n" +
+ " vec3 bloom = max(avg - 0.88, 0.0) * 0.35;\n" +
+ " col = clamp(col + bloom, 0.0, 1.0);\n" +
+ " col = mix(col, col * col * (3.0 - 2.0 * col), 0.12);\n" +
+ " fragColor = vec4(col.b, col.g, col.r, 1.0);\n" +
+ "}\n";
+
+ /**
+ * Converts a "#version 300 es" shader string to "#version 330 core" for desktop OpenGL 3.3 Core Profile.
+ */
+ public static String adaptGlslForDesktop330(String src) {
+ return src.replace("#version 300 es\n", "#version 330 core\n")
+ .replace("precision highp float;\n", "")
+ .replace("precision mediump float;\n", "")
+ .replace("precision highp sampler2DArray;\n", "")
+ .replace("precision mediump sampler2DArray;\n", "");
+ }
+
+ // =========================================================================
+ // PURE-JAVA 4x4 MATRIX UTILITIES (replaces android.opengl.Matrix)
+ // =========================================================================
+
+ public static void setLookAtM(float[] rm, int rmOffset,
+ float eyeX, float eyeY, float eyeZ,
+ float centerX, float centerY, float centerZ,
+ float upX, float upY, float upZ) {
+ float fx = centerX - eyeX;
+ float fy = centerY - eyeY;
+ float fz = centerZ - eyeZ;
+ float rlf = 1.0f / (float) Math.sqrt(fx * fx + fy * fy + fz * fz);
+ fx *= rlf;
+ fy *= rlf;
+ fz *= rlf;
+
+ float sx = fy * upZ - fz * upY;
+ float sy = fz * upX - fx * upZ;
+ float sz = fx * upY - fy * upX;
+ float rls = 1.0f / (float) Math.sqrt(sx * sx + sy * sy + sz * sz);
+ sx *= rls;
+ sy *= rls;
+ sz *= rls;
+
+ float ux = sy * fz - sz * fy;
+ float uy = sz * fx - sx * fz;
+ float uz = sx * fy - sy * fx;
+
+ rm[rmOffset] = sx;
+ rm[rmOffset + 1] = ux;
+ rm[rmOffset + 2] = -fx;
+ rm[rmOffset + 3] = 0.0f;
+
+ rm[rmOffset + 4] = sy;
+ rm[rmOffset + 5] = uy;
+ rm[rmOffset + 6] = -fy;
+ rm[rmOffset + 7] = 0.0f;
+
+ rm[rmOffset + 8] = sz;
+ rm[rmOffset + 9] = uz;
+ rm[rmOffset + 10] = -fz;
+ rm[rmOffset + 11] = 0.0f;
+
+ rm[rmOffset + 12] = -(sx * eyeX + sy * eyeY + sz * eyeZ);
+ rm[rmOffset + 13] = -(ux * eyeX + uy * eyeY + uz * eyeZ);
+ rm[rmOffset + 14] = (fx * eyeX + fy * eyeY + fz * eyeZ);
+ rm[rmOffset + 15] = 1.0f;
+ }
+
+ public static void orthoM(float[] m, int mOffset,
+ float left, float right, float bottom, float top,
+ float near, float far) {
+ float r_width = 1.0f / (right - left);
+ float r_height = 1.0f / (top - bottom);
+ float r_depth = 1.0f / (far - near);
+ float x = 2.0f * r_width;
+ float y = 2.0f * r_height;
+ float z = -2.0f * r_depth;
+ float tx = -(right + left) * r_width;
+ float ty = -(top + bottom) * r_height;
+ float tz = -(far + near) * r_depth;
+
+ m[mOffset] = x;
+ m[mOffset + 5] = y;
+ m[mOffset + 10] = z;
+ m[mOffset + 12] = tx;
+ m[mOffset + 13] = ty;
+ m[mOffset + 14] = tz;
+ m[mOffset + 15] = 1.0f;
+ m[mOffset + 1] = 0.0f;
+ m[mOffset + 2] = 0.0f;
+ m[mOffset + 3] = 0.0f;
+ m[mOffset + 4] = 0.0f;
+ m[mOffset + 6] = 0.0f;
+ m[mOffset + 7] = 0.0f;
+ m[mOffset + 8] = 0.0f;
+ m[mOffset + 9] = 0.0f;
+ m[mOffset + 11] = 0.0f;
+ }
+
+ public static void multiplyMM(float[] result, int resultOffset,
+ float[] lhs, int lhsOffset,
+ float[] rhs, int rhsOffset) {
+ for (int i = 0; i < 4; i++) {
+ final float rhs_i0 = rhs[rhsOffset + (i << 2)];
+ float ri0 = lhs[lhsOffset] * rhs_i0;
+ float ri1 = lhs[lhsOffset + 1] * rhs_i0;
+ float ri2 = lhs[lhsOffset + 2] * rhs_i0;
+ float ri3 = lhs[lhsOffset + 3] * rhs_i0;
+ for (int j = 1; j < 4; j++) {
+ final float rhs_ij = rhs[rhsOffset + (i << 2) + j];
+ final int lhsCol = lhsOffset + (j << 2);
+ ri0 += lhs[lhsCol] * rhs_ij;
+ ri1 += lhs[lhsCol + 1] * rhs_ij;
+ ri2 += lhs[lhsCol + 2] * rhs_ij;
+ ri3 += lhs[lhsCol + 3] * rhs_ij;
+ }
+ result[resultOffset + (i << 2)] = ri0;
+ result[resultOffset + (i << 2) + 1] = ri1;
+ result[resultOffset + (i << 2) + 2] = ri2;
+ result[resultOffset + (i << 2) + 3] = ri3;
+ }
+ }
+}
diff --git a/2006Scape Client/src/main/java/Hd317Plugin.java b/2006Scape Client/src/main/java/Hd317Plugin.java
new file mode 100644
index 00000000..0dee48ef
--- /dev/null
+++ b/2006Scape Client/src/main/java/Hd317Plugin.java
@@ -0,0 +1,162 @@
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * 317HD / RLHD Hardware-Accelerated Graphics Plugin.
+ * Exposes 317HD visual & performance settings in the Plugin Hub and synchronizes
+ * with ClientSettings.HD_317 and HD317Pipeline.
+ */
+public class Hd317Plugin extends ClientPlugin {
+
+ private boolean shadowsEnabled = true;
+ private String shadowResolution = "1024";
+ private String shadowSoftness = "PCF 4-Tap";
+ private boolean dynamicLights = true;
+ private boolean atmosphericFog = true;
+ private int drawDistance = 25;
+ private boolean groundTextures = true;
+ private boolean normalMapping = true;
+ private boolean waterShader = true;
+ private int saturation = 100;
+ private int brightness = 100;
+ private boolean contrastCurve = true;
+
+ @Override
+ public String getName() {
+ return "317 HD";
+ }
+
+ @Override
+ public String getDescription() {
+ return "Hardware-accelerated OpenGL 317HD lighting, shadows, water, and textures.";
+ }
+
+ @Override
+ public String getAuthor() {
+ return "2006Scape";
+ }
+
+ @Override
+ public String getVersion() {
+ return "1.0.0";
+ }
+
+ @Override
+ public boolean isEnabledByDefault() {
+ return ClientSettings.HD_317;
+ }
+
+ @Override
+ public List getConfigItems() {
+ List list = new ArrayList<>();
+ list.add(new PluginConfigItem("shadowsEnabled", "Shadows", "Render directional sun shadows", shadowsEnabled));
+ list.add(new PluginConfigItem("shadowResolution", "Shadow Resolution", "Shadow map resolution (higher = sharper, slower)", shadowResolution, new String[]{"512", "1024", "2048"}).setVisibleWhen("shadowsEnabled"));
+ list.add(new PluginConfigItem("shadowSoftness", "Shadow Quality", "1-Tap bilinear or 4-Tap soft PCF shadows", shadowSoftness, new String[]{"Hard (1-Tap)", "PCF 4-Tap"}).setVisibleWhen("shadowsEnabled"));
+ list.add(new PluginConfigItem("dynamicLights", "Dynamic Lighting", "Point lights from fires, torches, braziers, and altars", dynamicLights));
+ list.add(new PluginConfigItem("atmosphericFog", "Atmospheric Fog", "Distance fog and regional color grading", atmosphericFog));
+ list.add(new PluginConfigItem("drawDistance", "Draw Distance", "Maximum render distance in tiles", drawDistance, 15, 55));
+ list.add(new PluginConfigItem("groundTextures", "Ground Textures", "Procedural 317HD ground textures and height splatting", groundTextures));
+ list.add(new PluginConfigItem("normalMapping", "Normal Mapping", "Surface bump detail and specular highlights", normalMapping));
+ list.add(new PluginConfigItem("waterShader", "HD Water Shader", "Animated dual-wave water with Fresnel sky reflection", waterShader));
+ list.add(new PluginConfigItem("saturation", "Saturation (%)", "Color saturation percentage", saturation, 50, 150));
+ list.add(new PluginConfigItem("brightness", "Brightness (%)", "Scene brightness percentage", brightness, 60, 140));
+ list.add(new PluginConfigItem("contrastCurve", "Contrast Tonemapping", "317HD S-curve contrast enhancement", contrastCurve));
+ return list;
+ }
+
+ @Override
+ public void onConfigChanged(String key, Object value) {
+ if ("shadowsEnabled".equals(key)) {
+ shadowsEnabled = (Boolean) value;
+ HD317Pipeline.cfgShadowsEnabled = shadowsEnabled;
+ } else if ("shadowResolution".equals(key)) {
+ shadowResolution = String.valueOf(value);
+ try {
+ HD317Pipeline.cfgShadowResolution = Integer.parseInt(shadowResolution);
+ } catch (NumberFormatException ignored) {
+ HD317Pipeline.cfgShadowResolution = 1024;
+ }
+ } else if ("shadowSoftness".equals(key)) {
+ shadowSoftness = String.valueOf(value);
+ HD317Pipeline.cfgShadowSoftPcf = !"Hard (1-Tap)".equals(shadowSoftness);
+ } else if ("dynamicLights".equals(key)) {
+ dynamicLights = (Boolean) value;
+ HD317Pipeline.cfgDynamicLights = dynamicLights;
+ } else if ("atmosphericFog".equals(key)) {
+ atmosphericFog = (Boolean) value;
+ HD317Pipeline.cfgAtmosphericFog = atmosphericFog;
+ } else if ("drawDistance".equals(key)) {
+ drawDistance = ((Number) value).intValue();
+ WorldController.drawDistance = Math.max(15, Math.min(55, drawDistance));
+ } else if ("groundTextures".equals(key)) {
+ groundTextures = (Boolean) value;
+ HD317Pipeline.cfgGroundTextures = groundTextures;
+ } else if ("normalMapping".equals(key)) {
+ normalMapping = (Boolean) value;
+ HD317Pipeline.cfgNormalMapping = normalMapping;
+ } else if ("waterShader".equals(key)) {
+ waterShader = (Boolean) value;
+ HD317Pipeline.cfgWaterShader = waterShader;
+ } else if ("saturation".equals(key)) {
+ saturation = ((Number) value).intValue();
+ HD317Pipeline.cfgSaturation = saturation / 100.0f;
+ } else if ("brightness".equals(key)) {
+ brightness = ((Number) value).intValue();
+ HD317Pipeline.cfgBrightness = brightness / 100.0f;
+ } else if ("contrastCurve".equals(key)) {
+ contrastCurve = (Boolean) value;
+ HD317Pipeline.cfgContrastCurve = contrastCurve;
+ }
+ }
+
+ private void syncAllConfig() {
+ HD317Pipeline.cfgShadowsEnabled = shadowsEnabled;
+ try {
+ HD317Pipeline.cfgShadowResolution = Integer.parseInt(shadowResolution);
+ } catch (NumberFormatException ignored) {
+ HD317Pipeline.cfgShadowResolution = 1024;
+ }
+ HD317Pipeline.cfgShadowSoftPcf = !"Hard (1-Tap)".equals(shadowSoftness);
+ HD317Pipeline.cfgDynamicLights = dynamicLights;
+ HD317Pipeline.cfgAtmosphericFog = atmosphericFog;
+ WorldController.drawDistance = Math.max(15, Math.min(55, drawDistance));
+ HD317Pipeline.cfgGroundTextures = groundTextures;
+ HD317Pipeline.cfgNormalMapping = normalMapping;
+ HD317Pipeline.cfgWaterShader = waterShader;
+ HD317Pipeline.cfgSaturation = saturation / 100.0f;
+ HD317Pipeline.cfgBrightness = brightness / 100.0f;
+ HD317Pipeline.cfgContrastCurve = contrastCurve;
+ }
+
+ @Override
+ public void onStart(PluginContext ctx) {
+ super.onStart(ctx);
+ syncAllConfig();
+ if (ctx != null && ctx.getGame() != null && !ClientSettings.HD_317) {
+ ctx.getGame().setHD317Enabled(true);
+ }
+ }
+
+ @Override
+ public void onStop() {
+ if (ctx != null && ctx.getGame() != null && ClientSettings.HD_317) {
+ ctx.getGame().setHD317Enabled(false);
+ }
+ }
+
+ @Override
+ public boolean handlesCommandsWhenDisabled() {
+ return true;
+ }
+
+ @Override
+ public boolean onCommand(String command, String[] args) {
+ if ("hd".equalsIgnoreCase(command) || "317hd".equalsIgnoreCase(command)) {
+ if (PluginManager.get() != null) {
+ PluginManager.get().togglePlugin(this);
+ }
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/2006Scape Client/src/main/java/HdGroundMaterial.java b/2006Scape Client/src/main/java/HdGroundMaterial.java
new file mode 100644
index 00000000..dc277d75
--- /dev/null
+++ b/2006Scape Client/src/main/java/HdGroundMaterial.java
@@ -0,0 +1,114 @@
+/**
+ * 317HD / RLHD GroundMaterial system.
+ * Maps 317 Floor IDs (underlays & overlays) and HSL colors to multi-material groups,
+ * picking deterministic per-vertex materials via spatial hashing so adjacent tiles blend seamlessly.
+ */
+public enum HdGroundMaterial {
+
+ NONE(HdMaterial.NONE),
+ OVERWORLD_GRASS(HdMaterial.HD_GRASS_1, HdMaterial.HD_GRASS_2, HdMaterial.HD_GRASS_3),
+ COBBLESTONE_PATH(HdMaterial.HD_COBBLESTONE_1, HdMaterial.HD_COBBLESTONE_2, HdMaterial.HD_GRAVEL),
+ GRAVEL_PATH(HdMaterial.HD_GRAVEL),
+ STONE_PAVERS(HdMaterial.HD_STONE_PAVERS_1, HdMaterial.HD_STONE_PAVERS_2),
+ VARIED_DIRT(HdMaterial.HD_DIRT_1, HdMaterial.HD_DIRT_2),
+ SAND_DUNES(HdMaterial.HD_SAND_1),
+ WOOD_FLOOR(HdMaterial.HD_WOOD_FLOOR);
+
+ private final int[] materials;
+
+ HdGroundMaterial(int... materials) {
+ this.materials = materials;
+ }
+
+ /**
+ * Deterministically selects a material layer for a specific world vertex (plane, worldTileX, worldTileZ).
+ * Mirrors 317HD's ProceduralGenerator vertex hash so shared vertices across adjacent tiles always match.
+ */
+ public int getMaterialForVertex(int plane, int worldTileX, int worldTileZ) {
+ if (materials == null || materials.length == 0) {
+ return HdMaterial.NONE;
+ }
+ if (materials.length == 1) {
+ return materials[0];
+ }
+ long seed = (long) (plane + 1) * 73856093L
+ ^ (long) worldTileX * 19349663L
+ ^ (long) worldTileZ * 83492791L;
+ seed = (seed ^ (seed >>> 30)) * 0xbf58476d1ce4e5b9L;
+ seed = (seed ^ (seed >>> 27)) * 0x94d049bb133111ebL;
+ seed = seed ^ (seed >>> 31);
+ int idx = (int) (Math.abs(seed) % materials.length);
+ return materials[idx];
+ }
+
+ public static HdGroundMaterial resolve(int floorId, int hsl, boolean isOverlay) {
+ return resolve(0, floorId, hsl, isOverlay);
+ }
+
+ public static HdGroundMaterial resolve(int plane, int floorId, int hsl, boolean isOverlay) {
+ if (floorId > 0 && Flo.cache != null && floorId - 1 < Flo.cache.length) {
+ Flo flo = Flo.cache[floorId - 1];
+ if (flo != null) {
+ if (flo.anInt391 >= 0) {
+ return NONE;
+ }
+ int rgb = flo.anInt390;
+ if (rgb == 0xFF00FF) {
+ return NONE;
+ }
+ }
+ }
+
+ int hue = (hsl >> 10) & 0x3F;
+ int sat = (hsl >> 7) & 0x07;
+ int lum = hsl & 0x7F;
+
+ if (plane >= 1 && !isOverlay) {
+ if (sat <= 2) {
+ if (lum >= 90) return STONE_PAVERS;
+ return COBBLESTONE_PATH;
+ }
+ return COBBLESTONE_PATH;
+ }
+
+ if (!isOverlay) {
+ if (sat <= 2) {
+ if (lum >= 90) {
+ return STONE_PAVERS;
+ }
+ return VARIED_DIRT;
+ }
+ if (hue >= 7 && hue <= 38) {
+ return OVERWORLD_GRASS;
+ }
+ if (hue >= 5 && hue <= 14 && lum >= 64 && sat >= 2) {
+ return SAND_DUNES;
+ }
+ if (hue >= 2 && hue <= 6 && sat >= 2) {
+ return VARIED_DIRT;
+ }
+ return OVERWORLD_GRASS;
+ }
+
+ if (hue >= 7 && hue <= 38 && sat >= 2) {
+ return OVERWORLD_GRASS;
+ }
+
+ if (sat <= 2) {
+ if (lum >= 90) {
+ return STONE_PAVERS;
+ }
+ return COBBLESTONE_PATH;
+ }
+
+ if (hue >= 5 && hue <= 14 && lum >= 64 && sat >= 2) {
+ return SAND_DUNES;
+ }
+
+ if (hue >= 2 && hue <= 6 && sat >= 2) {
+ return VARIED_DIRT;
+ }
+
+ return COBBLESTONE_PATH;
+ }
+}
diff --git a/2006Scape Client/src/main/java/HdMaterial.java b/2006Scape Client/src/main/java/HdMaterial.java
new file mode 100644
index 00000000..62d90d61
--- /dev/null
+++ b/2006Scape Client/src/main/java/HdMaterial.java
@@ -0,0 +1,558 @@
+import java.nio.Buffer;
+import java.nio.ByteBuffer;
+import java.util.Random;
+
+/**
+ * 317HD / RLHD Material definition and 64-layer 128x128 RGBA texture array generator.
+ * Layer indices 0..49 correspond to enhanced RS2 cache textures;
+ * Layer indices 50..63 correspond to dedicated 317HD procedural PBR materials.
+ */
+public final class HdMaterial {
+
+ public static final int LAYER_COUNT = 64;
+ public static final int TEX_SIZE = 128;
+
+ // Dedicated 317HD Material Layer IDs (50..63)
+ public static final int NONE = -1;
+ public static final int HD_GRASS_1 = 50;
+ public static final int HD_GRASS_2 = 51;
+ public static final int HD_GRASS_3 = 52;
+ public static final int HD_COBBLESTONE_1 = 53;
+ public static final int HD_COBBLESTONE_2 = 54;
+ public static final int HD_GRAVEL = 55;
+ public static final int HD_STONE_PAVERS_1 = 56;
+ public static final int HD_STONE_PAVERS_2 = 57;
+ public static final int HD_DIRT_1 = 58;
+ public static final int HD_DIRT_2 = 59;
+ public static final int HD_SAND_1 = 60;
+ public static final int HD_WOOD_FLOOR = 61;
+ public static final int HD_WATER_WAVE_1 = 62;
+ public static final int HD_WATER_WAVE_2 = 63;
+
+ public final int layerId;
+ public final float specularStrength;
+ public final float specularGloss;
+ public final float normalStrength;
+ public final float uvScale;
+ public final boolean isWater;
+ public final boolean isEmissive;
+
+ public static final HdMaterial[] MATERIALS = new HdMaterial[LAYER_COUNT];
+
+ static {
+ // Initialize default cache texture slots (0..49)
+ for (int i = 0; i < 50; i++) {
+ boolean water = (i == 1 || i == 17 || i == 24 || i == 34);
+ boolean emissive = (i == 31 || i == 40);
+ float spec = 0.12f;
+ float gloss = 14.0f;
+ float norm = 0.75f;
+ if (water) {
+ spec = 0.90f;
+ gloss = 72.0f;
+ norm = 1.0f;
+ } else if (i == 2 || i == 11 || i == 23) {
+ // Castle stone masonry walls
+ spec = 0.25f;
+ gloss = 18.0f;
+ norm = 1.15f;
+ } else if (i == 5 || i == 16) {
+ // Roof shingles
+ spec = 0.28f;
+ gloss = 22.0f;
+ norm = 1.05f;
+ } else if (i == 3 || i == 4 || i == 0) {
+ // Wood planks
+ spec = 0.16f;
+ gloss = 12.0f;
+ norm = 0.85f;
+ }
+ MATERIALS[i] = new HdMaterial(i, spec, gloss, norm, 1.0f, water, emissive);
+ }
+
+ // Initialize 317HD Ground & Architectural Materials (50..63)
+ MATERIALS[HD_GRASS_1] = new HdMaterial(HD_GRASS_1, 0.08f, 10.0f, 0.70f, 1.0f, false, false);
+ MATERIALS[HD_GRASS_2] = new HdMaterial(HD_GRASS_2, 0.08f, 10.0f, 0.75f, 1.0f, false, false);
+ MATERIALS[HD_GRASS_3] = new HdMaterial(HD_GRASS_3, 0.10f, 12.0f, 0.70f, 1.0f, false, false);
+ MATERIALS[HD_COBBLESTONE_1] = new HdMaterial(HD_COBBLESTONE_1, 0.28f, 22.0f, 0.75f, 1.0f, false, false);
+ MATERIALS[HD_COBBLESTONE_2] = new HdMaterial(HD_COBBLESTONE_2, 0.26f, 20.0f, 0.70f, 1.0f, false, false);
+ MATERIALS[HD_GRAVEL] = new HdMaterial(HD_GRAVEL, 0.20f, 16.0f, 0.65f, 1.0f, false, false);
+ MATERIALS[HD_STONE_PAVERS_1] = new HdMaterial(HD_STONE_PAVERS_1, 0.35f, 28.0f, 1.10f, 1.0f, false, false);
+ MATERIALS[HD_STONE_PAVERS_2] = new HdMaterial(HD_STONE_PAVERS_2, 0.30f, 24.0f, 1.05f, 1.0f, false, false);
+ MATERIALS[HD_DIRT_1] = new HdMaterial(HD_DIRT_1, 0.10f, 10.0f, 0.90f, 1.0f, false, false);
+ MATERIALS[HD_DIRT_2] = new HdMaterial(HD_DIRT_2, 0.14f, 12.0f, 0.95f, 1.0f, false, false);
+ MATERIALS[HD_SAND_1] = new HdMaterial(HD_SAND_1, 0.20f, 18.0f, 0.80f, 1.0f, false, false);
+ MATERIALS[HD_WOOD_FLOOR] = new HdMaterial(HD_WOOD_FLOOR, 0.22f, 18.0f, 0.85f, 1.0f, false, false);
+ MATERIALS[HD_WATER_WAVE_1] = new HdMaterial(HD_WATER_WAVE_1, 0.95f, 80.0f, 1.0f, 1.0f, true, false);
+ MATERIALS[HD_WATER_WAVE_2] = new HdMaterial(HD_WATER_WAVE_2, 0.95f, 80.0f, 1.0f, 1.0f, true, false);
+ }
+
+ public HdMaterial(int layerId, float specularStrength, float specularGloss, float normalStrength,
+ float uvScale, boolean isWater, boolean isEmissive) {
+ this.layerId = layerId;
+ this.specularStrength = specularStrength;
+ this.specularGloss = specularGloss;
+ this.normalStrength = normalStrength;
+ this.uvScale = uvScale;
+ this.isWater = isWater;
+ this.isEmissive = isEmissive;
+ }
+
+ public static HdMaterial get(int layerId) {
+ if (layerId >= 0 && layerId < LAYER_COUNT) {
+ return MATERIALS[layerId];
+ }
+ return MATERIALS[HD_COBBLESTONE_1];
+ }
+
+ /**
+ * Populates the 64-layer 128x128 RGBA8 diffuse+heightfield and Sobel normal+specular buffers.
+ */
+ public static void populateTextureBuffers(ByteBuffer diffuseBuf, ByteBuffer normalBuf) {
+ final int size = TEX_SIZE;
+ final int layers = LAYER_COUNT;
+ final int layerPixels = size * size;
+
+ float[] heightField = new float[layerPixels];
+ int[] rgbField = new int[layerPixels];
+ boolean[] cutoutField = new boolean[layerPixels];
+
+ // 1. Build Layers 0..49 from RS2 Cache Textures + 317HD Architectural Enhancements
+ for (int texId = 0; texId < 50; texId++) {
+ buildCacheTextureLayer(texId, rgbField, heightField, cutoutField);
+ writeLayerToBuffers(texId, rgbField, heightField, cutoutField, get(texId).normalStrength, diffuseBuf, normalBuf);
+ }
+
+ // 2. Build Layers 50..63 (Dedicated 317HD Procedural PBR Materials)
+ for (int matId = 50; matId < layers; matId++) {
+ buildProceduralHdLayer(matId, rgbField, heightField, cutoutField);
+ writeLayerToBuffers(matId, rgbField, heightField, cutoutField, get(matId).normalStrength, diffuseBuf, normalBuf);
+ }
+
+ ((Buffer) diffuseBuf).position(0);
+ ((Buffer) normalBuf).position(0);
+ }
+
+ private static void buildCacheTextureLayer(int texId, int[] rgbField, float[] heightField, boolean[] cutoutField) {
+ int[] srcPixels = null;
+ try {
+ srcPixels = Texture.method371(texId);
+ } catch (Throwable ignored) {
+ }
+
+ Background bg = (Texture.aBackgroundArray1474s != null && texId < Texture.aBackgroundArray1474s.length)
+ ? Texture.aBackgroundArray1474s[texId] : null;
+ int[] palette = (Texture.anIntArrayArray1483 != null && texId < Texture.anIntArrayArray1483.length)
+ ? Texture.anIntArrayArray1483[texId] : null;
+
+ // Upsample 64x64 cache textures with bilinear filtering while preserving cutout transparency
+ if (bg != null && palette != null && bg.aByteArray1450 != null && bg.anInt1452 == 64 && bg.anInt1453 == 64) {
+ byte[] raw = bg.aByteArray1450;
+ for (int y = 0; y < 128; y++) {
+ int sy0 = y >> 1;
+ int sy1 = (sy0 + 1) & 63;
+ int wy1 = (y & 1) * 128;
+ int wy0 = 256 - wy1;
+ for (int x = 0; x < 128; x++) {
+ int sx0 = x >> 1;
+ int sx1 = (sx0 + 1) & 63;
+ int wx1 = (x & 1) * 128;
+ int wx0 = 256 - wx1;
+
+ int i00 = raw[(sy0 << 6) + sx0] & 0xFF;
+ int i10 = raw[(sy0 << 6) + sx1] & 0xFF;
+ int i01 = raw[(sy1 << 6) + sx0] & 0xFF;
+ int i11 = raw[(sy1 << 6) + sx1] & 0xFF;
+
+ int idx = (y << 7) | x;
+ if (i00 == 0 || i10 == 0 || i01 == 0 || i11 == 0) {
+ int c = palette[i00];
+ cutoutField[idx] = (i00 == 0 || c == 0);
+ rgbField[idx] = c;
+ heightField[idx] = cutoutField[idx] ? 0f : 0.5f;
+ continue;
+ }
+
+ int c00 = palette[i00];
+ int c10 = palette[i10];
+ int c01 = palette[i01];
+ int c11 = palette[i11];
+
+ int r = (((c00 >> 16 & 0xFF) * wx0 + (c10 >> 16 & 0xFF) * wx1) * wy0
+ + ((c01 >> 16 & 0xFF) * wx0 + (c11 >> 16 & 0xFF) * wx1) * wy1) >> 16;
+ int g = (((c00 >> 8 & 0xFF) * wx0 + (c10 >> 8 & 0xFF) * wx1) * wy0
+ + ((c01 >> 8 & 0xFF) * wx0 + (c11 >> 8 & 0xFF) * wx1) * wy1) >> 16;
+ int b = (((c00 & 0xFF) * wx0 + (c10 & 0xFF) * wx1) * wy0
+ + ((c01 & 0xFF) * wx0 + (c11 & 0xFF) * wx1) * wy1) >> 16;
+
+ cutoutField[idx] = false;
+ rgbField[idx] = (r << 16) | (g << 8) | b;
+ float lum = (r * 0.299f + g * 0.587f + b * 0.114f) / 255.0f;
+ heightField[idx] = Math.max(0.08f, Math.min(0.95f, lum));
+ }
+ }
+ } else if (srcPixels != null && srcPixels.length >= 16384) {
+ for (int i = 0; i < 16384; i++) {
+ int c = srcPixels[i];
+ if (c == 0) {
+ cutoutField[i] = true;
+ rgbField[i] = 0;
+ heightField[i] = 0f;
+ } else {
+ cutoutField[i] = false;
+ rgbField[i] = c & 0xFFFFFF;
+ int r = (c >> 16) & 0xFF;
+ int g = (c >> 8) & 0xFF;
+ int b = c & 0xFF;
+ float lum = (r * 0.299f + g * 0.587f + b * 0.114f) / 255.0f;
+ heightField[i] = Math.max(0.08f, Math.min(0.95f, lum));
+ }
+ }
+ } else {
+ for (int i = 0; i < 16384; i++) {
+ cutoutField[i] = false;
+ rgbField[i] = 0x808080;
+ heightField[i] = 0.5f;
+ }
+ }
+
+ // Dilate opaque neighbor RGB into transparent cutout pixels (4 passes) so GL_LINEAR never bleeds black
+ for (int pass = 0; pass < 4; pass++) {
+ for (int y = 0; y < 128; y++) {
+ int ym1 = (y - 1) & 127;
+ int yp1 = (y + 1) & 127;
+ for (int x = 0; x < 128; x++) {
+ int idx = (y << 7) | x;
+ if (rgbField[idx] != 0) continue;
+ int xm1 = (x - 1) & 127;
+ int xp1 = (x + 1) & 127;
+ int n1 = rgbField[(ym1 << 7) | x];
+ int n2 = rgbField[(yp1 << 7) | x];
+ int n3 = rgbField[(y << 7) | xm1];
+ int n4 = rgbField[(y << 7) | xp1];
+ if (n1 != 0) rgbField[idx] = n1;
+ else if (n2 != 0) rgbField[idx] = n2;
+ else if (n3 != 0) rgbField[idx] = n3;
+ else if (n4 != 0) rgbField[idx] = n4;
+ }
+ }
+ }
+ }
+
+ private static void buildProceduralHdLayer(int matId, int[] rgbField, float[] heightField, boolean[] cutoutField) {
+ for (int i = 0; i < 16384; i++) {
+ cutoutField[i] = false;
+ }
+
+ if (matId == HD_GRASS_1 || matId == HD_GRASS_2 || matId == HD_GRASS_3) {
+ int variant = matId - HD_GRASS_1;
+ Random rnd = new Random(5001L + variant * 313L);
+ float[] noise = new float[16384];
+ for (int i = 0; i < 16384; i++) {
+ noise[i] = rnd.nextFloat();
+ }
+ for (int y = 0; y < 128; y++) {
+ int ym1 = (y - 1) & 127;
+ int yp1 = (y + 1) & 127;
+ double ny = y * 2.0 * Math.PI / 128.0;
+ for (int x = 0; x < 128; x++) {
+ int xm1 = (x - 1) & 127;
+ int xp1 = (x + 1) & 127;
+ double nx = x * 2.0 * Math.PI / 128.0;
+
+ float fine = (noise[(y << 7) | x] * 0.40f
+ + noise[(ym1 << 7) | x] * 0.15f
+ + noise[(yp1 << 7) | x] * 0.15f
+ + noise[(y << 7) | xm1] * 0.15f
+ + noise[(y << 7) | xp1] * 0.15f);
+ float patch = (float) (Math.sin(nx * 2.0 + variant) * Math.cos(ny * 2.0 - variant) * 0.5 + 0.5);
+ float blade = fine * 0.72f + patch * 0.28f;
+ float h = Math.max(0.24f, Math.min(0.68f, 0.28f + blade * 0.34f));
+
+ int modV = clampByte((int) (222 + blade * 28));
+ int idx = (y << 7) | x;
+ rgbField[idx] = (modV << 16) | (modV << 8) | modV;
+ heightField[idx] = h;
+ }
+ }
+ } else if (matId == HD_COBBLESTONE_1 || matId == HD_COBBLESTONE_2 || matId == HD_GRAVEL) {
+ int gridN = (matId == HD_GRAVEL) ? 13 : (matId == HD_COBBLESTONE_1 ? 10 : 11);
+ double cellSize = 128.0 / gridN;
+ int numCells = gridN * gridN;
+ double[] cx = new double[numCells];
+ double[] cy = new double[numCells];
+ int[] stoneTintR = new int[numCells];
+ int[] stoneTintG = new int[numCells];
+ int[] stoneTintB = new int[numCells];
+
+ Random rnd = new Random(11700L + matId * 97L);
+ for (int gy = 0; gy < gridN; gy++) {
+ for (int gx = 0; gx < gridN; gx++) {
+ int ci = gy * gridN + gx;
+ cx[ci] = (gx + 0.5 + (rnd.nextDouble() - 0.5) * 0.65) * cellSize;
+ cy[ci] = (gy + 0.5 + (rnd.nextDouble() - 0.5) * 0.65) * cellSize;
+ int shade = 224 + rnd.nextInt(20) - 10;
+ stoneTintR[ci] = shade;
+ stoneTintG[ci] = shade;
+ stoneTintB[ci] = shade;
+ }
+ }
+
+ double stoneRadius = cellSize * 0.54;
+ for (int y = 0; y < 128; y++) {
+ for (int x = 0; x < 128; x++) {
+ double minD = 999.0;
+ double secD = 999.0;
+ int closestCell = 0;
+
+ for (int c = 0; c < numCells; c++) {
+ double dx = Math.abs(x - cx[c]);
+ if (dx > 64.0) dx = 128.0 - dx;
+ double dy = Math.abs(y - cy[c]);
+ if (dy > 64.0) dy = 128.0 - dy;
+ double d = Math.sqrt(dx * dx + dy * dy);
+ if (d < minD) {
+ secD = minD;
+ minD = d;
+ closestCell = c;
+ } else if (d < secD) {
+ secD = d;
+ }
+ }
+
+ double edge = secD - minD;
+ int idx = (y << 7) | x;
+
+ if (edge < 1.35) {
+ float t = (float) (edge / 1.35);
+ int v = clampByte((int) (182 + t * 28));
+ rgbField[idx] = (v << 16) | (v << 8) | v;
+ heightField[idx] = 0.28f + t * 0.22f;
+ } else {
+ double normD = Math.min(1.0, minD / stoneRadius);
+ float dome = (float) Math.cos(normD * Math.PI * 0.42);
+ float scale = 0.90f + dome * 0.14f;
+ int r = clampByte((int) (stoneTintR[closestCell] * scale));
+ int g = clampByte((int) (stoneTintG[closestCell] * scale));
+ int b = clampByte((int) (stoneTintB[closestCell] * scale));
+ rgbField[idx] = (r << 16) | (g << 8) | b;
+ heightField[idx] = Math.max(0.55f, Math.min(0.92f, 0.58f + dome * 0.32f));
+ }
+ }
+ }
+ } else if (matId == HD_STONE_PAVERS_1 || matId == HD_STONE_PAVERS_2) {
+ if (matId == HD_STONE_PAVERS_2) {
+ // Smooth, honed indoor architectural stone/marble floor (no sub-tile mortar grid or cobble bumps,
+ // preserving crisp 1x1 castle checkerboard squares and authentic tile colors)
+ Random rnd = new Random(6401L);
+ for (int y = 0; y < 128; y++) {
+ for (int x = 0; x < 128; x++) {
+ int idx = (y << 7) | x;
+ int fine = (int) ((rnd.nextFloat() - 0.5f) * 6.0f);
+ int v = clampByte(244 + fine);
+ rgbField[idx] = (v << 16) | (v << 8) | v;
+ heightField[idx] = 0.75f + fine * 0.002f;
+ }
+ }
+ } else {
+ int tileW = 32;
+ int tileH = 32;
+ for (int y = 0; y < 128; y++) {
+ int row = y / tileH;
+ int shiftX = (row % 2 == 1) ? (tileW / 2) : 0;
+ int cy = y % tileH;
+ for (int x = 0; x < 128; x++) {
+ int cx = (x + shiftX) % tileW;
+ int idx = (y << 7) | x;
+ int grain = (((x * 17 + y * 31) ^ (x * 5)) & 15) - 8;
+ if (cx == 0 || cy == 0) {
+ rgbField[idx] = 0xC8C8C8;
+ heightField[idx] = 0.45f;
+ } else {
+ int v = clampByte(238 + grain / 2);
+ rgbField[idx] = (v << 16) | (v << 8) | v;
+ heightField[idx] = 0.80f + grain * 0.003f;
+ }
+ }
+ }
+ }
+ } else if (matId == HD_DIRT_1 || matId == HD_DIRT_2) {
+ int variant = matId - HD_DIRT_1;
+ Random rnd = new Random(7301L + variant * 443L);
+ float[] dNoise = new float[16384];
+ for (int i = 0; i < 16384; i++) {
+ dNoise[i] = rnd.nextFloat();
+ }
+ float[] blurred = new float[16384];
+ for (int pass = 0; pass < 2; pass++) {
+ float[] src = (pass == 0) ? dNoise : blurred;
+ for (int y = 0; y < 128; y++) {
+ int ym1 = (y - 1) & 127, yp1 = (y + 1) & 127;
+ for (int x = 0; x < 128; x++) {
+ int xm1 = (x - 1) & 127, xp1 = (x + 1) & 127;
+ blurred[(y << 7) | x] = src[(y << 7) | x] * 0.40f
+ + (src[(ym1 << 7) | x] + src[(yp1 << 7) | x]
+ + src[(y << 7) | xm1] + src[(y << 7) | xp1]) * 0.15f;
+ }
+ }
+ }
+ for (int y = 0; y < 128; y++) {
+ double ny = y * 2.0 * Math.PI / 128.0;
+ for (int x = 0; x < 128; x++) {
+ double nx = x * 2.0 * Math.PI / 128.0;
+ float soilLobe = (float) (Math.sin(nx + variant) * Math.cos(ny - variant) * 0.5 + 0.5);
+ float fineGrain = (dNoise[(y << 7) | x] - 0.5f) * 14.0f;
+ float soilVal = blurred[(y << 7) | x] * 0.70f + soilLobe * 0.30f;
+ // Hue-neutral detail multiplier so gray rock/stone never shifts toward muddy brown
+ int v = clampByte((int) (220 + soilVal * 26 + fineGrain));
+ int idx = (y << 7) | x;
+ rgbField[idx] = (v << 16) | (v << 8) | v;
+ heightField[idx] = Math.max(0.20f, Math.min(0.75f, 0.32f + soilVal * 0.38f));
+ }
+ }
+ } else if (matId == HD_SAND_1) {
+ Random rnd = new Random(9901L);
+ for (int y = 0; y < 128; y++) {
+ double ny = y * 2.0 * Math.PI / 128.0;
+ for (int x = 0; x < 128; x++) {
+ double nx = x * 2.0 * Math.PI / 128.0;
+ double gentleDune = Math.sin(nx * 3.0 + Math.sin(ny * 2.0) * 0.8) * 0.5 + 0.5;
+ float fineGrain = (rnd.nextFloat() - 0.5f) * 10.0f;
+ int v = clampByte((int) (228 + gentleDune * 16 + fineGrain));
+ int idx = (y << 7) | x;
+ rgbField[idx] = (v << 16) | (v << 8) | v;
+ heightField[idx] = (float) (0.35 + gentleDune * 0.30);
+ }
+ }
+ } else if (matId == HD_WATER_WAVE_1 || matId == HD_WATER_WAVE_2) {
+ int variant = matId - HD_WATER_WAVE_1;
+ Random rnd = new Random(8821L + variant * 7919L);
+ float[] wNoise = new float[16384];
+ for (int i = 0; i < 16384; i++) {
+ wNoise[i] = rnd.nextFloat();
+ }
+ float[] blurred = new float[16384];
+ for (int pass = 0; pass < 2; pass++) {
+ float[] src = (pass == 0) ? wNoise : blurred;
+ for (int y = 0; y < 128; y++) {
+ int ym1 = (y - 1) & 127, yp1 = (y + 1) & 127;
+ for (int x = 0; x < 128; x++) {
+ int xm1 = (x - 1) & 127, xp1 = (x + 1) & 127;
+ blurred[(y << 7) | x] = src[(y << 7) | x] * 0.40f
+ + (src[(ym1 << 7) | x] + src[(yp1 << 7) | x]
+ + src[(y << 7) | xm1] + src[(y << 7) | xp1]) * 0.15f;
+ }
+ }
+ }
+ for (int y = 0; y < 128; y++) {
+ double ny = y * 2.0 * Math.PI / 128.0;
+ for (int x = 0; x < 128; x++) {
+ double nx = x * 2.0 * Math.PI / 128.0;
+ double wave = Math.sin(nx * 2.0 + ny * 1.0 + variant) * 0.35
+ + Math.sin(-nx * 1.0 + ny * 3.0 - variant * 1.5) * 0.30
+ + Math.cos(nx * 3.0 - ny * 2.0 + variant * 2.0) * 0.20;
+ float noiseVal = blurred[(y << 7) | x];
+ float h = (float) (0.50 + wave * 0.22 + (noiseVal - 0.5) * 0.28);
+ int idx = (y << 7) | x;
+ rgbField[idx] = 0x2A6296;
+ heightField[idx] = Math.max(0.10f, Math.min(0.90f, h));
+ }
+ }
+ } else {
+ for (int y = 0; y < 128; y++) {
+ for (int x = 0; x < 128; x++) {
+ int idx = (y << 7) | x;
+ int px = x % 32;
+ int grain = ((y * 13 + x * 7) & 7) - 4;
+ if (px == 0) {
+ rgbField[idx] = 0x705840;
+ heightField[idx] = 0.20f;
+ } else {
+ int v = clampByte(224 + grain);
+ rgbField[idx] = (v << 16) | (clampByte(v - 12) << 8) | clampByte(v - 24);
+ heightField[idx] = 0.65f;
+ }
+ }
+ }
+ }
+ }
+
+ private static void writeLayerToBuffers(int layerId, int[] rgbField, float[] heightField, boolean[] cutoutField,
+ float normalStrength, ByteBuffer diffuseBuf, ByteBuffer normalBuf) {
+ final int size = TEX_SIZE;
+ final int mask = size - 1;
+ int baseOffset = layerId * size * size * 4;
+
+ ((Buffer) diffuseBuf).position(baseOffset);
+ ((Buffer) normalBuf).position(baseOffset);
+
+ for (int y = 0; y < size; y++) {
+ int ym1 = (y - 1) & mask;
+ int yp1 = (y + 1) & mask;
+ for (int x = 0; x < size; x++) {
+ int xm1 = (x - 1) & mask;
+ int xp1 = (x + 1) & mask;
+ int idx = (y << 7) | x;
+
+ int c = rgbField[idx];
+ int r = (c >> 16) & 0xFF;
+ int g = (c >> 8) & 0xFF;
+ int b = c & 0xFF;
+ int a;
+ if (layerId == 24 || layerId == 17) {
+ if (cutoutField[idx]) {
+ a = 0;
+ } else {
+ a = Math.max(0, Math.min(255, (int) (heightField[idx] * 255.0f)));
+ }
+ } else if (cutoutField[idx]) {
+ a = 0;
+ } else if (layerId < 50) {
+ a = 255;
+ } else {
+ a = Math.max(8, Math.min(255, (int) (heightField[idx] * 255.0f)));
+ }
+
+ diffuseBuf.put((byte) r);
+ diffuseBuf.put((byte) g);
+ diffuseBuf.put((byte) b);
+ diffuseBuf.put((byte) a);
+
+ // Wrapped 3x3 Sobel normal calculation from heightField
+ float hTL = heightField[(ym1 << 7) | xm1];
+ float hT = heightField[(ym1 << 7) | x];
+ float hTR = heightField[(ym1 << 7) | xp1];
+ float hL = heightField[(y << 7) | xm1];
+ float hR = heightField[(y << 7) | xp1];
+ float hBL = heightField[(yp1 << 7) | xm1];
+ float hB = heightField[(yp1 << 7) | x];
+ float hBR = heightField[(yp1 << 7) | xp1];
+
+ float dX = (hTR + 2.0f * hR + hBR) - (hTL + 2.0f * hL + hBL);
+ float dY = (hBL + 2.0f * hB + hBR) - (hTL + 2.0f * hT + hTR);
+
+ float nx = -dX * normalStrength * 2.2f;
+ float ny = -dY * normalStrength * 2.2f;
+ float nz = 1.0f;
+ float invLen = (float) (1.0 / Math.sqrt(nx * nx + ny * ny + nz * nz));
+ nx *= invLen;
+ ny *= invLen;
+ nz *= invLen;
+
+ int nR = clampByte((int) ((nx * 0.5f + 0.5f) * 255.0f));
+ int nG = clampByte((int) ((ny * 0.5f + 0.5f) * 255.0f));
+ int nB = clampByte((int) ((nz * 0.5f + 0.5f) * 255.0f));
+ int specMask = Math.max(0, Math.min(255, (int) (heightField[idx] * 255.0f)));
+
+ normalBuf.put((byte) nR);
+ normalBuf.put((byte) nG);
+ normalBuf.put((byte) nB);
+ normalBuf.put((byte) specMask);
+ }
+ }
+ }
+
+ private static int clampByte(int val) {
+ return val < 0 ? 0 : (val > 255 ? 255 : val);
+ }
+}
diff --git a/2006Scape Client/src/main/java/HdProceduralGenerator.java b/2006Scape Client/src/main/java/HdProceduralGenerator.java
new file mode 100644
index 00000000..f5092a15
--- /dev/null
+++ b/2006Scape Client/src/main/java/HdProceduralGenerator.java
@@ -0,0 +1,282 @@
+/**
+ * Direct port of 317HD / RLHD's ProceduralGenerator:
+ * - Computes smooth 3D terrain normals across the 105x105 heightmap grid.
+ * - Resolves per-tile & per-vertex 317HD GroundMaterials from 317 Floor IDs and HSL colors.
+ * - Computes cross-tile vertex material splatting so cobblestone paths, gravel, dirt, and grass
+ * blend organically via height-map displacement across tile boundaries.
+ * - Extracts dynamic point light emitters from world objects.
+ */
+public final class HdProceduralGenerator {
+
+ // Smooth terrain normals: [plane][vx][vz][0..2 (nx, ny, nz)]
+ public final float[][][][] tileNormals = new float[4][105][105][3];
+
+ // Resolved material layer per tile: [plane][tx][tz]
+ public final int[][][] tileUnderlayMat = new int[4][104][104];
+ public final int[][][] tileOverlayMat = new int[4][104][104];
+ public final boolean[][][] tileHasOverlay = new boolean[4][104][104];
+ public final boolean[][][] tileIsIndoor = new boolean[4][104][104];
+
+ // Per-corner blended material on the 105x105 vertex grid for seamless cross-tile splatting
+ public final int[][][] cornerBlendMat = new int[4][105][105];
+ public final int[][][] cornerBlendColor = new int[4][105][105];
+
+ // Dynamic Point Lights extracted from the scene (x, y, z, radius, r, g, b, intensity)
+ public static final int MAX_SCENE_LIGHTS = 128;
+ public final float[] sceneLightPosRad = new float[MAX_SCENE_LIGHTS * 4];
+ public final float[] sceneLightColorInt = new float[MAX_SCENE_LIGHTS * 4];
+ public int sceneLightCount = 0;
+ public int baseX = 3200;
+ public int baseZ = 3200;
+
+ public HdProceduralGenerator() {
+ for (int p = 0; p < 4; p++) {
+ for (int vx = 0; vx < 105; vx++) {
+ for (int vz = 0; vz < 105; vz++) {
+ tileNormals[p][vx][vz][0] = 0.0f;
+ tileNormals[p][vx][vz][1] = -1.0f;
+ tileNormals[p][vx][vz][2] = 0.0f;
+ cornerBlendMat[p][vx][vz] = HdMaterial.HD_GRASS_1;
+ }
+ }
+ for (int x = 0; x < 104; x++) {
+ for (int z = 0; z < 104; z++) {
+ tileUnderlayMat[p][x][z] = HdMaterial.HD_GRASS_1;
+ tileOverlayMat[p][x][z] = HdMaterial.HD_COBBLESTONE_1;
+ }
+ }
+ }
+ }
+
+ public void generateSceneData(Game game, ObjectManager om, WorldController wc) {
+ if (wc == null) return;
+
+ int baseX = (game != null) ? game.baseX : 3200;
+ int baseZ = (game != null) ? game.baseY : 3200;
+ this.baseX = baseX;
+ this.baseZ = baseZ;
+
+ int[][][] heights = (om != null && om.anIntArrayArrayArray129 != null)
+ ? om.anIntArrayArrayArray129 : wc.anIntArrayArrayArray440;
+ if (heights == null) return;
+
+ byte[][][] underlays = (om != null) ? om.aByteArrayArrayArray142 : null;
+ byte[][][] overlays = (om != null) ? om.aByteArrayArrayArray130 : null;
+ byte[][][] shapes = (om != null) ? om.aByteArrayArrayArray136 : null;
+ byte[][][] tileFlags = (om != null && om.aByteArrayArrayArray149 != null)
+ ? om.aByteArrayArrayArray149
+ : ((game != null) ? game.byteGroundArray : null);
+
+ // 0. Detect indoor/roofed building tiles (RS2 roof flag bit 4 in byteGroundArray)
+ for (int p = 0; p < 4; p++) {
+ for (int x = 0; x < 104; x++) {
+ for (int z = 0; z < 104; z++) {
+ boolean indoor = false;
+ if (tileFlags != null && ((tileFlags[p][x][z] & 4) != 0 || (tileFlags[0][x][z] & 4) != 0)) {
+ indoor = true;
+ // Open-air archways / gatehouses (unroofed on both opposite sides within 4 tiles with no blocking wall)
+ // should keep their outdoor ground/cobblestone material instead of indoor marble.
+ if (p == 0 && (isOpenAirPassThrough(tileFlags, wc, x, z, 1, 0) || isOpenAirPassThrough(tileFlags, wc, x, z, 0, 1))) {
+ indoor = false;
+ }
+ }
+ tileIsIndoor[p][x][z] = indoor;
+ }
+ }
+ }
+
+ // 1. Compute smooth per-vertex terrain normals from central height differences
+ for (int p = 0; p < 4; p++) {
+ for (int vx = 0; vx < 105; vx++) {
+ int xm1 = Math.max(0, vx - 1);
+ int xp1 = Math.min(104, vx + 1);
+ for (int vz = 0; vz < 105; vz++) {
+ int zm1 = Math.max(0, vz - 1);
+ int zp1 = Math.min(104, vz + 1);
+
+ float dhDx = (float) (heights[p][xp1][vz] - heights[p][xm1][vz]);
+ float dhDz = (float) (heights[p][vx][zp1] - heights[p][vx][zm1]);
+ // In RS2 coords: +X is East, -Y is Up, +Z is North; 2 tiles = 256 units
+ float nx = dhDx;
+ float ny = -256.0f;
+ float nz = dhDz;
+ float invLen = (float) (1.0 / Math.sqrt(nx * nx + ny * ny + nz * nz));
+ tileNormals[p][vx][vz][0] = nx * invLen;
+ tileNormals[p][vx][vz][1] = ny * invLen;
+ tileNormals[p][vx][vz][2] = nz * invLen;
+ }
+ }
+ }
+
+ // 2. Resolve per-tile Underlay & Overlay 317HD Materials
+ for (int p = 0; p < 4; p++) {
+ for (int x = 0; x < 104; x++) {
+ for (int z = 0; z < 104; z++) {
+ int uId = (underlays != null) ? (underlays[p][x][z] & 0xFF) : 0;
+ int oId = (overlays != null) ? (overlays[p][x][z] & 0xFF) : 0;
+ Ground g = wc.groundArray[p][x][z];
+
+ int uHsl = (20 << 10) | (4 << 7) | 40; // default grass HSL
+ int oHsl = (8 << 10) | (1 << 7) | 48; // default stone/cobble HSL
+
+ if (g != null) {
+ if (g.aClass43_1311 != null) {
+ int c = g.aClass43_1311.anInt716;
+ if (c != 0xbc614e && c >= 0) {
+ if (oId > 0 || g.aClass43_1311.isOverlay) oHsl = c;
+ else uHsl = c;
+ }
+ } else if (g.aClass40_1312 != null) {
+ Class40 ct = g.aClass40_1312;
+ for (int f = 0; f < ct.anIntArray676.length; f++) {
+ if (ct.isOverlayFace != null && ct.isOverlayFace[f]) {
+ if (ct.anIntArray676[f] != 0xbc614e) oHsl = ct.anIntArray676[f];
+ } else {
+ if (ct.anIntArray676[f] != 0xbc614e) uHsl = ct.anIntArray676[f];
+ }
+ }
+ }
+ }
+
+ HdGroundMaterial uGroup = HdGroundMaterial.resolve(p, uId, uHsl, false);
+ tileUnderlayMat[p][x][z] = uGroup.getMaterialForVertex(p, baseX + x, baseZ + z);
+
+ if (oId > 0 || (g != null && g.aClass43_1311 != null && g.aClass43_1311.isOverlay)) {
+ HdGroundMaterial oGroup = HdGroundMaterial.resolve(p, oId, oHsl, true);
+ int oMat = oGroup.getMaterialForVertex(p, baseX + x, baseZ + z);
+ tileOverlayMat[p][x][z] = oMat;
+ tileHasOverlay[p][x][z] = (oMat != HdMaterial.NONE);
+ } else {
+ tileOverlayMat[p][x][z] = HdMaterial.NONE;
+ tileHasOverlay[p][x][z] = false;
+ }
+ }
+ }
+ }
+
+ // 3. Compute Per-Corner Blended Material & Color on the 105x105 Grid
+ for (int p = 0; p < 4; p++) {
+ for (int vx = 0; vx < 105; vx++) {
+ for (int vz = 0; vz < 105; vz++) {
+ int chosenMat = HdMaterial.HD_GRASS_1;
+ int chosenHsl = -1;
+ boolean foundOverlayPath = false;
+
+ for (int dx = -1; dx <= 0; dx++) {
+ for (int dz = -1; dz <= 0; dz++) {
+ int tx = vx + dx;
+ int tz = vz + dz;
+ if (tx < 0 || tx >= 104 || tz < 0 || tz >= 104) continue;
+
+ Ground g = wc.groundArray[p][tx][tz];
+ if (g == null) continue;
+
+ int shape = (shapes != null) ? (shapes[p][tx][tz] & 0xFF) : 0;
+ if (tileHasOverlay[p][tx][tz] && (g.aClass43_1311 != null || shape == 0)) {
+ chosenMat = tileOverlayMat[p][tx][tz];
+ if (g.aClass43_1311 != null && g.aClass43_1311.anInt716 != 0xbc614e) {
+ chosenHsl = g.aClass43_1311.anInt716;
+ }
+ foundOverlayPath = true;
+ } else if (!foundOverlayPath) {
+ chosenMat = tileUnderlayMat[p][tx][tz];
+ if (g.aClass43_1311 != null && g.aClass43_1311.anInt716 != 0xbc614e) {
+ chosenHsl = g.aClass43_1311.anInt716;
+ }
+ }
+ }
+ }
+
+ cornerBlendMat[p][vx][vz] = chosenMat;
+ cornerBlendColor[p][vx][vz] = chosenHsl;
+ }
+ }
+ }
+
+ // 4. Extract Dynamic Point Lights from Light-Emitting Scene Objects
+ sceneLightCount = 0;
+ for (int p = 0; p < 4 && sceneLightCount < MAX_SCENE_LIGHTS; p++) {
+ for (int x = 0; x < 104 && sceneLightCount < MAX_SCENE_LIGHTS; x++) {
+ for (int z = 0; z < 104 && sceneLightCount < MAX_SCENE_LIGHTS; z++) {
+ Ground g = wc.groundArray[p][x][z];
+ if (g == null) continue;
+
+ if (g.obj1 != null) {
+ checkAndAddObjectLight(g.obj1.uid, g.obj1.anInt274, g.obj1.anInt273, g.obj1.anInt275);
+ }
+ if (g.obj2 != null) {
+ checkAndAddObjectLight(g.obj2.uid, g.obj2.anInt500, g.obj2.anInt499, g.obj2.anInt501);
+ }
+ for (int i = 0; i < g.anInt1317 && sceneLightCount < MAX_SCENE_LIGHTS; i++) {
+ Object5 o5 = g.obj5Array[i];
+ if (o5 != null && o5.anInt523 == x && o5.anInt525 == z) {
+ checkAndAddObjectLight(o5.uid, o5.anInt519, o5.anInt518, o5.anInt520);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private static boolean isOpenAirPassThrough(byte[][][] tileFlags, WorldController wc, int x, int z, int dx, int dz) {
+ return reachesUnroofed(tileFlags, wc, x, z, dx, dz) && reachesUnroofed(tileFlags, wc, x, z, -dx, -dz);
+ }
+
+ private static boolean reachesUnroofed(byte[][][] tileFlags, WorldController wc, int x, int z, int dx, int dz) {
+ for (int step = 1; step <= 4; step++) {
+ int nx = x + dx * step;
+ int nz = z + dz * step;
+ if (nx < 0 || nx >= 104 || nz < 0 || nz >= 104) return false;
+ Ground g = wc.groundArray[0][nx][nz];
+ if (g != null && g.obj1 != null) return false;
+ if ((tileFlags[0][nx][nz] & 4) == 0) return true;
+ }
+ return false;
+ }
+
+ private void checkAndAddObjectLight(int uid, int worldX, int worldY, int worldZ) {
+ if (uid == 0 || sceneLightCount >= MAX_SCENE_LIGHTS) return;
+ int objId = (uid >> 14) & 0x7FFF;
+ if (objId <= 0) return;
+
+ boolean isFireOrTorch = false;
+ boolean isMagicOrWaterLight = false;
+ try {
+ ObjectDef def = ObjectDef.forID(objId);
+ if (def != null && def.name != null) {
+ String n = def.name.toLowerCase();
+ if (n.contains("fire") || n.contains("torch") || n.contains("lamp") || n.contains("candle")
+ || n.contains("furnace") || n.contains("brazier") || n.contains("lantern")
+ || n.contains("stove") || n.contains("range") || n.contains("lava")) {
+ isFireOrTorch = true;
+ } else if (n.contains("altar") || n.contains("portal") || n.contains("fountain") || n.contains("crystal")) {
+ isMagicOrWaterLight = true;
+ }
+ }
+ } catch (Throwable ignored) {
+ }
+
+ if (!isFireOrTorch && !isMagicOrWaterLight) {
+ return;
+ }
+
+ int base = sceneLightCount * 4;
+ sceneLightPosRad[base] = worldX;
+ sceneLightPosRad[base + 1] = worldY - 90.0f;
+ sceneLightPosRad[base + 2] = worldZ;
+ if (isFireOrTorch) {
+ sceneLightPosRad[base + 3] = 640.0f;
+ sceneLightColorInt[base] = 1.00f;
+ sceneLightColorInt[base + 1] = 0.68f;
+ sceneLightColorInt[base + 2] = 0.28f;
+ sceneLightColorInt[base + 3] = 1.35f;
+ } else {
+ sceneLightPosRad[base + 3] = 512.0f;
+ sceneLightColorInt[base] = 0.65f;
+ sceneLightColorInt[base + 1] = 0.85f;
+ sceneLightColorInt[base + 2] = 1.00f;
+ sceneLightColorInt[base + 3] = 0.75f;
+ }
+ sceneLightCount++;
+ }
+}
diff --git a/2006Scape Client/src/main/java/HdSceneUploader.java b/2006Scape Client/src/main/java/HdSceneUploader.java
new file mode 100644
index 00000000..49caed74
--- /dev/null
+++ b/2006Scape Client/src/main/java/HdSceneUploader.java
@@ -0,0 +1,1052 @@
+import java.nio.Buffer;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.FloatBuffer;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * Direct port of 317HD / RLHD's SceneUploader:
+ * - Separates Opaque (shadow-casting, depth-writing) and Translucent (depth-tested, non-shadow-casting) geometry.
+ * - Converts visible RS2 ground tiles (Class43 & Class40) into 3D GPU vertices with
+ * smooth terrain normals, 3-vertex multi-material IDs (matA, matB, matC) for height-splatting,
+ * and world-space UVs.
+ * - Converts 3D Models (walls, roofs, trees, bushes, fountains, players, NPCs) into GPU vertices
+ * using uncorrupted hdVertexNormals and exact (P, M, N) texture triangle UV projection.
+ */
+public final class HdSceneUploader {
+
+ // 16 floats (64 bytes, cache-line aligned) per vertex:
+ // [0..2] vec3 aPos (worldX, worldY, worldZ)
+ // [3..5] vec3 aNormal (nx, ny, nz)
+ // [6..7] vec2 aUv (u, v)
+ // [8..11] vec4 aColor (r, g, b, alpha)
+ // [12..15]vec4 aMatAndBary (matA, matB, matC, baryIndex + surfaceType * 4.0)
+ public static final int FLOATS_PER_VERTEX = 16;
+ public static final int BYTES_PER_VERTEX = FLOATS_PER_VERTEX * 4;
+
+ // Surface type constants encoded into aMatAndBary.w = baryIndex + surfaceType * 4.0
+ public static final int SURF_TERRAIN = 0;
+ public static final int SURF_MODEL = 1;
+ public static final int SURF_WATER = 2;
+ public static final int SURF_ACTOR = 3;
+ public static final int SURF_WALL = 4;
+
+ private static final float[] WATER_NORMAL = {0.0f, -1.0f, 0.0f};
+
+ private static final int MAX_TERRAIN_VERTICES = 120000;
+ private static final int MAX_OPAQUE_VERTICES = 400000;
+ private static final int MAX_TRANS_VERTICES = 80000;
+ private static final int MAX_CACHED_MODEL_FLOATS = 2000000; // 8 MB hard cap
+
+ private static final class CachedModel {
+ float[] opaque;
+ int opaqueVerts;
+ float[] trans;
+ int transVerts;
+ int surfType;
+ int version;
+ int totalFloats;
+ }
+
+ private final LinkedHashMap modelCache = new LinkedHashMap<>(256, 0.75f, true);
+ private int cachedModelFloats = 0;
+
+ private final float[] terrainStaging = new float[MAX_TERRAIN_VERTICES * FLOATS_PER_VERTEX];
+ private final float[] opaqueStaging = new float[MAX_OPAQUE_VERTICES * FLOATS_PER_VERTEX];
+ private final float[] transStaging = new float[MAX_TRANS_VERTICES * FLOATS_PER_VERTEX];
+ private final FloatBuffer terrainBuffer;
+ private final FloatBuffer opaqueBuffer;
+ private final FloatBuffer transBuffer;
+ private int terrainVertexCount = 0;
+ private int opaqueVertexCount = 0;
+ private int transVertexCount = 0;
+
+ private final boolean[] vertexTouchesUnderlay = new boolean[16];
+ private final boolean[] vertexTouchesOverlay = new boolean[16];
+
+ private HdProceduralGenerator procGen;
+ private WorldController worldController;
+
+ public HdSceneUploader() {
+ this.terrainBuffer = ByteBuffer.allocateDirect(MAX_TERRAIN_VERTICES * BYTES_PER_VERTEX)
+ .order(ByteOrder.nativeOrder()).asFloatBuffer();
+ this.opaqueBuffer = ByteBuffer.allocateDirect(MAX_OPAQUE_VERTICES * BYTES_PER_VERTEX)
+ .order(ByteOrder.nativeOrder()).asFloatBuffer();
+ this.transBuffer = ByteBuffer.allocateDirect(MAX_TRANS_VERTICES * BYTES_PER_VERTEX)
+ .order(ByteOrder.nativeOrder()).asFloatBuffer();
+ }
+
+ public static final int CHUNKS_PER_AXIS = 4;
+ public static final int CHUNKS_PER_PLANE = CHUNKS_PER_AXIS * CHUNKS_PER_AXIS; // 16 chunks (26x26 tiles each)
+ public static final int CHUNK_TILE_SIZE = 26;
+ public static final float CHUNK_RADIUS = 19.0f * 128.0f;
+
+ private final float[][] staticTerrainBuckets = new float[4][];
+ private final int[] staticTerrainVertCount = new int[4];
+ private final float[][][] staticSceneryOpaqueBuckets = new float[4][CHUNKS_PER_PLANE][];
+ private final int[][] staticSceneryOpaqueVertCount = new int[4][CHUNKS_PER_PLANE];
+ private final float[][][] staticSceneryTransBuckets = new float[4][CHUNKS_PER_PLANE][];
+ private final int[][] staticSceneryTransVertCount = new int[4][CHUNKS_PER_PLANE];
+ private final int[][] staticSceneryChunkGen = new int[4][CHUNKS_PER_PLANE];
+ private final boolean[] dirtyChunks = new boolean[CHUNKS_PER_PLANE];
+ private int terrainGenerationId = 0;
+ private boolean staticTerrainBuilt = false;
+ private boolean staticSceneryBuilt = false;
+ private boolean buildingStaticScenery = false;
+
+ public void setSceneContext(HdProceduralGenerator procGen, WorldController worldController) {
+ this.procGen = procGen;
+ this.worldController = worldController;
+ clearModelCache();
+ buildStaticTerrain();
+ }
+
+ public int getTerrainGenerationId() {
+ return terrainGenerationId;
+ }
+
+ public int getStaticTerrainVertexCount(int bucket) {
+ return (bucket >= 0 && bucket < 4) ? staticTerrainVertCount[bucket] : 0;
+ }
+
+ public float[] getStaticTerrainBucket(int bucket) {
+ return (bucket >= 0 && bucket < 4) ? staticTerrainBuckets[bucket] : null;
+ }
+
+ public float[] getOpaqueStaging() {
+ return opaqueStaging;
+ }
+
+ public float[] getTransStaging() {
+ return transStaging;
+ }
+
+ public int getStaticSceneryOpaqueCount(int bucket, int chunk) {
+ return (bucket >= 0 && bucket < 4 && chunk >= 0 && chunk < CHUNKS_PER_PLANE) ? staticSceneryOpaqueVertCount[bucket][chunk] : 0;
+ }
+
+ public int getStaticSceneryTransCount(int bucket, int chunk) {
+ return (bucket >= 0 && bucket < 4 && chunk >= 0 && chunk < CHUNKS_PER_PLANE) ? staticSceneryTransVertCount[bucket][chunk] : 0;
+ }
+
+ public float[] getStaticSceneryOpaqueBucket(int bucket, int chunk) {
+ return (bucket >= 0 && bucket < 4 && chunk >= 0 && chunk < CHUNKS_PER_PLANE) ? staticSceneryOpaqueBuckets[bucket][chunk] : null;
+ }
+
+ public float[] getStaticSceneryTransBucket(int bucket, int chunk) {
+ return (bucket >= 0 && bucket < 4 && chunk >= 0 && chunk < CHUNKS_PER_PLANE) ? staticSceneryTransBuckets[bucket][chunk] : null;
+ }
+
+ public int getStaticSceneryChunkGen(int bucket, int chunk) {
+ return (bucket >= 0 && bucket < 4 && chunk >= 0 && chunk < CHUNKS_PER_PLANE) ? staticSceneryChunkGen[bucket][chunk] : 0;
+ }
+
+ public void invalidateChunk(int tx, int tz) {
+ if (!staticSceneryBuilt || tx < 0 || tz < 0 || tx >= 104 || tz >= 104) return;
+ int cx = Math.min(CHUNKS_PER_AXIS - 1, tx / CHUNK_TILE_SIZE);
+ int cz = Math.min(CHUNKS_PER_AXIS - 1, tz / CHUNK_TILE_SIZE);
+ dirtyChunks[cx * CHUNKS_PER_AXIS + cz] = true;
+ }
+
+ public void rebuildDirtyChunks() {
+ if (!staticSceneryBuilt || worldController == null || worldController.groundArray == null) return;
+ for (int c = 0; c < CHUNKS_PER_PLANE; c++) {
+ if (dirtyChunks[c]) {
+ dirtyChunks[c] = false;
+ buildSingleSceneryChunk(c);
+ }
+ }
+ }
+
+ public FloatBuffer prepareStaticBuffer(float[] data, int vertexCount) {
+ if (data == null || vertexCount <= 0) return null;
+ int floatCount = vertexCount * FLOATS_PER_VERTEX;
+ FloatBuffer fb = ByteBuffer.allocateDirect(floatCount * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
+ fb.put(data, 0, floatCount);
+ ((Buffer) fb).position(0);
+ return fb;
+ }
+
+ public FloatBuffer prepareStaticTerrainBucket(int bucket) {
+ int count = getStaticTerrainVertexCount(bucket);
+ if (count <= 0 || staticTerrainBuckets[bucket] == null) return null;
+ ((Buffer) terrainBuffer).position(0);
+ terrainBuffer.put(staticTerrainBuckets[bucket], 0, count * FLOATS_PER_VERTEX);
+ ((Buffer) terrainBuffer).position(0);
+ return terrainBuffer;
+ }
+
+ private void buildStaticTerrain() {
+ staticTerrainBuilt = false;
+ if (procGen == null || worldController == null || worldController.groundArray == null) {
+ for (int b = 0; b < 4; b++) {
+ staticTerrainBuckets[b] = null;
+ staticTerrainVertCount[b] = 0;
+ }
+ terrainGenerationId++;
+ return;
+ }
+ for (int bucket = 0; bucket < 4; bucket++) {
+ terrainVertexCount = 0;
+ for (int p = 0; p < 4; p++) {
+ Ground[][] planeGrid = worldController.groundArray[p];
+ if (planeGrid == null) continue;
+ for (int tx = 0; tx < 104; tx++) {
+ for (int tz = 0; tz < 104; tz++) {
+ Ground g = planeGrid[tx][tz];
+ if (g == null) continue;
+ int minVis = Math.max(0, Math.min(3, g.anInt1321));
+ if (minVis != bucket) continue;
+ if (g.aClass30_Sub3_1329 != null) {
+ Ground bridge = g.aClass30_Sub3_1329;
+ HD317Pipeline.drawingPlane = 0;
+ if (bridge.aClass43_1311 != null) {
+ appendSimpleTileInternal(bridge.aClass43_1311, 0, tx, tz);
+ } else if (bridge.aClass40_1312 != null) {
+ appendShapedTileInternal(bridge.aClass40_1312, 0, tx, tz);
+ }
+ }
+ HD317Pipeline.drawingPlane = g.anInt1310;
+ if (g.aClass43_1311 != null) {
+ appendSimpleTileInternal(g.aClass43_1311, g.anInt1310, tx, tz);
+ } else if (g.aClass40_1312 != null) {
+ appendShapedTileInternal(g.aClass40_1312, g.anInt1310, tx, tz);
+ }
+ }
+ }
+ }
+ staticTerrainVertCount[bucket] = terrainVertexCount;
+ staticTerrainBuckets[bucket] = (terrainVertexCount > 0)
+ ? Arrays.copyOf(terrainStaging, terrainVertexCount * FLOATS_PER_VERTEX)
+ : null;
+ }
+ terrainVertexCount = 0;
+ staticTerrainBuilt = true;
+ if (HD317Pipeline.useStaticScenery) {
+ buildStaticScenery();
+ }
+ terrainGenerationId++;
+ }
+
+ private void buildStaticScenery() {
+ staticSceneryBuilt = false;
+ for (int c = 0; c < CHUNKS_PER_PLANE; c++) {
+ dirtyChunks[c] = false;
+ }
+ if (worldController == null || worldController.groundArray == null) {
+ for (int b = 0; b < 4; b++) {
+ for (int c = 0; c < CHUNKS_PER_PLANE; c++) {
+ staticSceneryOpaqueBuckets[b][c] = null;
+ staticSceneryOpaqueVertCount[b][c] = 0;
+ staticSceneryTransBuckets[b][c] = null;
+ staticSceneryTransVertCount[b][c] = 0;
+ staticSceneryChunkGen[b][c]++;
+ }
+ }
+ return;
+ }
+ for (int c = 0; c < CHUNKS_PER_PLANE; c++) {
+ buildSingleSceneryChunk(c);
+ }
+ staticSceneryBuilt = true;
+ }
+
+ private void buildSingleSceneryChunk(int chunkIdx) {
+ int cx = chunkIdx / CHUNKS_PER_AXIS;
+ int cz = chunkIdx % CHUNKS_PER_AXIS;
+ int startX = cx * CHUNK_TILE_SIZE;
+ int endX = (cx == CHUNKS_PER_AXIS - 1) ? 104 : startX + CHUNK_TILE_SIZE;
+ int startZ = cz * CHUNK_TILE_SIZE;
+ int endZ = (cz == CHUNKS_PER_AXIS - 1) ? 104 : startZ + CHUNK_TILE_SIZE;
+
+ buildingStaticScenery = true;
+ java.util.HashSet seenObj5 = new java.util.HashSet<>();
+ int camX = WorldController.anInt455;
+ int camY = WorldController.anInt456;
+ int camZ = WorldController.anInt457;
+ java.util.ArrayList opaqueChunks = new java.util.ArrayList<>();
+ java.util.ArrayList transChunks = new java.util.ArrayList<>();
+
+ for (int bucket = 0; bucket < 4; bucket++) {
+ opaqueVertexCount = 0;
+ transVertexCount = 0;
+ opaqueChunks.clear();
+ transChunks.clear();
+ for (int p = 0; p < 4; p++) {
+ Ground[][] planeGrid = worldController.groundArray[p];
+ if (planeGrid == null) continue;
+ for (int tx = startX; tx < endX; tx++) {
+ for (int tz = startZ; tz < endZ; tz++) {
+ Ground g = planeGrid[tx][tz];
+ if (g == null) continue;
+ int minVis = Math.max(0, Math.min(3, g.anInt1321));
+ if (minVis != bucket) continue;
+
+ if (g.aClass30_Sub3_1329 != null) {
+ appendTileScenery(g.aClass30_Sub3_1329, 0, camX, camY, camZ, seenObj5, startX, endX, startZ, endZ);
+ }
+ appendTileScenery(g, g.anInt1310, camX, camY, camZ, seenObj5, startX, endX, startZ, endZ);
+
+ if (opaqueVertexCount >= MAX_OPAQUE_VERTICES - 20000) {
+ opaqueChunks.add(Arrays.copyOf(opaqueStaging, opaqueVertexCount * FLOATS_PER_VERTEX));
+ opaqueVertexCount = 0;
+ }
+ if (transVertexCount >= MAX_TRANS_VERTICES - 10000) {
+ transChunks.add(Arrays.copyOf(transStaging, transVertexCount * FLOATS_PER_VERTEX));
+ transVertexCount = 0;
+ }
+ }
+ }
+ }
+ staticSceneryOpaqueBuckets[bucket][chunkIdx] = mergeChunks(opaqueChunks, opaqueStaging, opaqueVertexCount);
+ staticSceneryOpaqueVertCount[bucket][chunkIdx] = (staticSceneryOpaqueBuckets[bucket][chunkIdx] != null)
+ ? staticSceneryOpaqueBuckets[bucket][chunkIdx].length / FLOATS_PER_VERTEX : 0;
+ staticSceneryTransBuckets[bucket][chunkIdx] = mergeChunks(transChunks, transStaging, transVertexCount);
+ staticSceneryTransVertCount[bucket][chunkIdx] = (staticSceneryTransBuckets[bucket][chunkIdx] != null)
+ ? staticSceneryTransBuckets[bucket][chunkIdx].length / FLOATS_PER_VERTEX : 0;
+ staticSceneryChunkGen[bucket][chunkIdx]++;
+ }
+ opaqueVertexCount = 0;
+ transVertexCount = 0;
+ buildingStaticScenery = false;
+ }
+
+ private void appendTileScenery(Ground g, int plane, int camX, int camY, int camZ, java.util.HashSet seenObj5,
+ int startX, int endX, int startZ, int endZ) {
+ HD317Pipeline.drawingPlane = plane;
+ if (g.obj1 != null) {
+ Object1 o1 = g.obj1;
+ HD317Pipeline.drawingWall = true;
+ if (o1.aClass30_Sub2_Sub4_278 instanceof Model) {
+ appendModel((Model) o1.aClass30_Sub2_Sub4_278, 0, o1.anInt274 - camX, o1.anInt273 - camY, o1.anInt275 - camZ, o1.uid);
+ }
+ if (o1.aClass30_Sub2_Sub4_279 instanceof Model) {
+ appendModel((Model) o1.aClass30_Sub2_Sub4_279, 0, o1.anInt274 - camX, o1.anInt273 - camY, o1.anInt275 - camZ, o1.uid);
+ }
+ HD317Pipeline.drawingWall = false;
+ }
+ if (g.obj2 != null && g.obj2.aClass30_Sub2_Sub4_504 instanceof Model && (g.obj2.anInt502 & 0x300) == 0) {
+ Object2 o2 = g.obj2;
+ appendModel((Model) o2.aClass30_Sub2_Sub4_504, o2.anInt503, o2.anInt500 - camX, o2.anInt499 - camY, o2.anInt501 - camZ, o2.uid);
+ }
+ if (g.obj3 != null && g.obj3.aClass30_Sub2_Sub4_814 instanceof Model) {
+ Object3 o3 = g.obj3;
+ appendModel((Model) o3.aClass30_Sub2_Sub4_814, 0, o3.anInt812 - camX, o3.anInt811 - camY, o3.anInt813 - camZ, o3.uid);
+ }
+ for (int i = 0; i < g.anInt1317; i++) {
+ Object5 o5 = g.obj5Array[i];
+ if (o5 != null && o5.aClass30_Sub2_Sub4_521 instanceof Model
+ && o5.anInt523 >= startX && o5.anInt523 < endX
+ && o5.anInt525 >= startZ && o5.anInt525 < endZ
+ && seenObj5.add(o5)) {
+ appendModel((Model) o5.aClass30_Sub2_Sub4_521, o5.anInt522, o5.anInt519 - camX, o5.anInt518 - camY, o5.anInt520 - camZ, o5.uid);
+ }
+ }
+ }
+
+ private static float[] mergeChunks(java.util.ArrayList chunks, float[] tail, int tailVerts) {
+ int totalFloats = tailVerts * FLOATS_PER_VERTEX;
+ for (int i = 0; i < chunks.size(); i++) {
+ totalFloats += chunks.get(i).length;
+ }
+ if (totalFloats <= 0) return null;
+ float[] merged = new float[totalFloats];
+ int pos = 0;
+ for (int i = 0; i < chunks.size(); i++) {
+ float[] c = chunks.get(i);
+ System.arraycopy(c, 0, merged, pos, c.length);
+ pos += c.length;
+ }
+ if (tailVerts > 0) {
+ System.arraycopy(tail, 0, merged, pos, tailVerts * FLOATS_PER_VERTEX);
+ }
+ return merged;
+ }
+
+ public void clearModelCache() {
+ modelCache.clear();
+ cachedModelFloats = 0;
+ }
+
+ public void resetFrame() {
+ terrainVertexCount = 0;
+ opaqueVertexCount = 0;
+ transVertexCount = 0;
+ }
+
+ public int getTerrainVertexCount() {
+ return terrainVertexCount;
+ }
+
+ public int getOpaqueVertexCount() {
+ return opaqueVertexCount;
+ }
+
+ public int getTransVertexCount() {
+ return transVertexCount;
+ }
+
+ public FloatBuffer prepareTerrainBuffer() {
+ ((Buffer) terrainBuffer).position(0);
+ terrainBuffer.put(terrainStaging, 0, terrainVertexCount * FLOATS_PER_VERTEX);
+ ((Buffer) terrainBuffer).position(0);
+ return terrainBuffer;
+ }
+
+ public FloatBuffer prepareOpaqueBuffer() {
+ ((Buffer) opaqueBuffer).position(0);
+ opaqueBuffer.put(opaqueStaging, 0, opaqueVertexCount * FLOATS_PER_VERTEX);
+ ((Buffer) opaqueBuffer).position(0);
+ return opaqueBuffer;
+ }
+
+ public FloatBuffer prepareTransBuffer() {
+ ((Buffer) transBuffer).position(0);
+ transBuffer.put(transStaging, 0, transVertexCount * FLOATS_PER_VERTEX);
+ ((Buffer) transBuffer).position(0);
+ return transBuffer;
+ }
+
+ private int resolveVertexGroundMaterial(int plane, int vx, int vz, int hsl, boolean isOverlay) {
+ HdGroundMaterial group = HdGroundMaterial.resolve(plane, 0, hsl, isOverlay);
+ int wX = (procGen != null ? procGen.baseX : 3200) + vx;
+ int wZ = (procGen != null ? procGen.baseZ : 3200) + vz;
+ int mat = group.getMaterialForVertex(plane, wX, wZ);
+ return (mat >= 0) ? mat : HdMaterial.HD_GRASS_1;
+ }
+
+ public void appendSimpleTile(Class43 tile, int plane, int tileX, int tileZ) {
+ if (staticTerrainBuilt) return;
+ appendSimpleTileInternal(tile, plane, tileX, tileZ);
+ }
+
+ private void appendSimpleTileInternal(Class43 tile, int plane, int tileX, int tileZ) {
+ if (tile == null || worldController == null || procGen == null) return;
+ if (tileX < 0 || tileX >= 104 || tileZ < 0 || tileZ >= 104) return;
+ if (terrainVertexCount + 6 > MAX_TERRAIN_VERTICES) return;
+
+ int[][][] heights = worldController.anIntArrayArrayArray440;
+ float x0 = tileX * 128.0f;
+ float x1 = (tileX + 1) * 128.0f;
+ float z0 = tileZ * 128.0f;
+ float z1 = (tileZ + 1) * 128.0f;
+
+ float y00 = heights[plane][tileX][tileZ];
+ float y10 = heights[plane][tileX + 1][tileZ];
+ float y11 = heights[plane][tileX + 1][tileZ + 1];
+ float y01 = heights[plane][tileX][tileZ + 1];
+
+ float[] n00 = procGen.tileNormals[plane][tileX][tileZ];
+ float[] n10 = procGen.tileNormals[plane][tileX + 1][tileZ];
+ float[] n11 = procGen.tileNormals[plane][tileX + 1][tileZ + 1];
+ float[] n01 = procGen.tileNormals[plane][tileX][tileZ + 1];
+
+ int texId = tile.anInt720;
+ boolean isWater = (texId == 1 || texId == 34);
+ int surfType = isWater ? SURF_WATER : SURF_TERRAIN;
+
+ if (isWater) {
+ n00 = n10 = n11 = n01 = WATER_NORMAL;
+ }
+
+ int m00, m10, m11, m01;
+ if (texId >= 0) {
+ m00 = m10 = m11 = m01 = texId;
+ } else if (procGen.tileIsIndoor[plane][tileX][tileZ]) {
+ // Indoor architectural flooring (e.g. Varrock Castle checkered marble/stone floors):
+ // Use uniform smooth honed stone without outdoor Voronoi cobblestone or dirt splatting
+ m00 = m10 = m11 = m01 = HdMaterial.HD_STONE_PAVERS_2;
+ } else {
+ boolean hasOv = tile.isOverlay;
+ if (plane >= 1) {
+ hasOv = true;
+ }
+ m00 = resolveVertexGroundMaterial(plane, tileX, tileZ, tile.anInt716, hasOv);
+ m10 = resolveVertexGroundMaterial(plane, tileX + 1, tileZ, tile.anInt717, hasOv);
+ m11 = resolveVertexGroundMaterial(plane, tileX + 1, tileZ + 1, tile.anInt718, hasOv);
+ m01 = resolveVertexGroundMaterial(plane, tileX, tileZ + 1, tile.anInt719, hasOv);
+ }
+
+ float uvScale = (texId >= 0) ? 128.0f : 192.0f;
+ boolean drawTri1 = (tile.anInt718 != 0xbc614e);
+ boolean drawTri2 = (tile.anInt716 != 0xbc614e);
+ if (!drawTri1 && !drawTri2) return;
+
+ int cSE = isWater ? 0x808080 : resolveGroundRgb(tile.anInt717, texId, m10);
+ int cNW = isWater ? 0x808080 : resolveGroundRgb(tile.anInt719, texId, m01);
+
+ if (drawTri1) {
+ int cNE = isWater ? 0x808080 : resolveGroundRgb(tile.anInt718, texId, m11);
+
+ putTerrainVertex(x1, y11, z1, n11[0], n11[1], n11[2], x1 / uvScale, z1 / uvScale, cNE, 1.0f, m11, m01, m10, 0, surfType);
+ putTerrainVertex(x0, y01, z1, n01[0], n01[1], n01[2], x0 / uvScale, z1 / uvScale, cNW, 1.0f, m11, m01, m10, 1, surfType);
+ putTerrainVertex(x1, y10, z0, n10[0], n10[1], n10[2], x1 / uvScale, z0 / uvScale, cSE, 1.0f, m11, m01, m10, 2, surfType);
+ }
+
+ if (drawTri2) {
+ int cSW = isWater ? 0x808080 : resolveGroundRgb(tile.anInt716, texId, m00);
+
+ putTerrainVertex(x0, y00, z0, n00[0], n00[1], n00[2], x0 / uvScale, z0 / uvScale, cSW, 1.0f, m00, m10, m01, 0, surfType);
+ putTerrainVertex(x1, y10, z0, n10[0], n10[1], n10[2], x1 / uvScale, z0 / uvScale, cSE, 1.0f, m00, m10, m01, 1, surfType);
+ putTerrainVertex(x0, y01, z1, n01[0], n01[1], n01[2], x0 / uvScale, z1 / uvScale, cNW, 1.0f, m00, m10, m01, 2, surfType);
+ }
+ }
+
+ public void appendShapedTile(Class40 tile, int plane, int tileX, int tileZ) {
+ if (staticTerrainBuilt) return;
+ appendShapedTileInternal(tile, plane, tileX, tileZ);
+ }
+
+ private void appendShapedTileInternal(Class40 tile, int plane, int tileX, int tileZ) {
+ if (tile == null || procGen == null) return;
+ if (tileX < 0 || tileX >= 104 || tileZ < 0 || tileZ >= 104) return;
+
+ int faceCount = tile.anIntArray679.length;
+ if (terrainVertexCount + faceCount * 3 > MAX_TERRAIN_VERTICES) return;
+
+ int vertCount = Math.min(16, tile.anIntArray673.length);
+ for (int v = 0; v < vertCount; v++) {
+ vertexTouchesUnderlay[v] = false;
+ vertexTouchesOverlay[v] = false;
+ }
+ int sampleUnderlayHsl = (20 << 10) | (4 << 7) | 40;
+ int sampleOverlayHsl = (8 << 10) | (1 << 7) | 48;
+
+ boolean hasUntexturedOverlay = false;
+ for (int f = 0; f < faceCount; f++) {
+ boolean ov = tile.isOverlayFace != null && tile.isOverlayFace[f];
+ int a = tile.anIntArray679[f];
+ int b = tile.anIntArray680[f];
+ int c = tile.anIntArray681[f];
+ int fTex = (tile.anIntArray682 != null) ? tile.anIntArray682[f] : -1;
+ if (ov) {
+ if (fTex < 0 && tile.anIntArray676[f] != 0xbc614e) {
+ sampleOverlayHsl = tile.anIntArray676[f];
+ hasUntexturedOverlay = true;
+ }
+ if (a < vertCount) vertexTouchesOverlay[a] = true;
+ if (b < vertCount) vertexTouchesOverlay[b] = true;
+ if (c < vertCount) vertexTouchesOverlay[c] = true;
+ } else {
+ if (fTex < 0 && tile.anIntArray676[f] != 0xbc614e) {
+ sampleUnderlayHsl = tile.anIntArray676[f];
+ }
+ if (a < vertCount) vertexTouchesUnderlay[a] = true;
+ if (b < vertCount) vertexTouchesUnderlay[b] = true;
+ if (c < vertCount) vertexTouchesUnderlay[c] = true;
+ }
+ }
+
+ boolean isIndoorTile = procGen.tileIsIndoor[plane][tileX][tileZ];
+ int uMat = isIndoorTile ? HdMaterial.HD_STONE_PAVERS_2 : resolveVertexGroundMaterial(plane, tileX, tileZ, sampleUnderlayHsl, false);
+ int oMat = hasUntexturedOverlay
+ ? (isIndoorTile ? HdMaterial.HD_STONE_PAVERS_2 : resolveVertexGroundMaterial(plane, tileX, tileZ, sampleOverlayHsl, true))
+ : HdMaterial.NONE;
+
+ float[] nSW = procGen.tileNormals[plane][tileX][tileZ];
+ float[] nSE = procGen.tileNormals[plane][tileX + 1][tileZ];
+ float[] nNE = procGen.tileNormals[plane][tileX + 1][tileZ + 1];
+ float[] nNW = procGen.tileNormals[plane][tileX][tileZ + 1];
+
+ float baseTileX = tileX * 128.0f;
+ float baseTileZ = tileZ * 128.0f;
+
+ boolean isBridgeTile = plane >= 1
+ || (worldController != null
+ && worldController.groundArray[0][tileX][tileZ] != null
+ && worldController.groundArray[0][tileX][tileZ].aClass30_Sub3_1329 != null);
+
+ for (int f = 0; f < faceCount; f++) {
+ int colA = tile.anIntArray676[f];
+ if (colA == 0xbc614e) continue;
+ int colB = tile.anIntArray677[f];
+ int colC = tile.anIntArray678[f];
+
+ int iA = tile.anIntArray679[f];
+ int iB = tile.anIntArray680[f];
+ int iC = tile.anIntArray681[f];
+
+ float xA = tile.anIntArray673[iA], yA = tile.anIntArray674[iA], zA = tile.anIntArray675[iA];
+ float xB = tile.anIntArray673[iB], yB = tile.anIntArray674[iB], zB = tile.anIntArray675[iB];
+ float xC = tile.anIntArray673[iC], yC = tile.anIntArray674[iC], zC = tile.anIntArray675[iC];
+
+ int texId = (tile.anIntArray682 != null) ? tile.anIntArray682[f] : -1;
+ boolean isWater = (texId == 1 || texId == 34);
+ int surfType = isWater ? SURF_WATER : SURF_TERRAIN;
+
+ boolean isOv = tile.isOverlayFace != null && tile.isOverlayFace[f];
+ boolean isBridgeOrRamp = isBridgeTile && hasUntexturedOverlay && (oMat >= HdMaterial.HD_COBBLESTONE_1 && oMat <= HdMaterial.HD_STONE_PAVERS_2);
+ if (!isOv && isBridgeOrRamp) {
+ int oHue = (sampleOverlayHsl >> 10) & 0x3F;
+ int oSat = (sampleOverlayHsl >> 7) & 0x07;
+ colA = (oHue << 10) | (oSat << 7) | (colA & 0x7F);
+ colB = (oHue << 10) | (oSat << 7) | (colB & 0x7F);
+ colC = (oHue << 10) | (oSat << 7) | (colC & 0x7F);
+ isOv = true;
+ }
+ int faceMat = (texId >= 0) ? texId : (isOv ? oMat : uMat);
+ int mA = faceMat, mB = faceMat, mC = faceMat;
+
+ int rgbA = isWater ? 0x808080 : resolveGroundRgb(colA, texId, mA);
+ int rgbB = isWater ? 0x808080 : resolveGroundRgb(colB, texId, mB);
+ int rgbC = isWater ? 0x808080 : resolveGroundRgb(colC, texId, mC);
+
+ float[] normA, normB, normC;
+ if (isWater) {
+ normA = normB = normC = WATER_NORMAL;
+ } else {
+ normA = interpolateTileNormal((xA - baseTileX) / 128.0f, (zA - baseTileZ) / 128.0f, nSW, nSE, nNE, nNW);
+ normB = interpolateTileNormal((xB - baseTileX) / 128.0f, (zB - baseTileZ) / 128.0f, nSW, nSE, nNE, nNW);
+ normC = interpolateTileNormal((xC - baseTileX) / 128.0f, (zC - baseTileZ) / 128.0f, nSW, nSE, nNE, nNW);
+ }
+
+ float uvScale = (texId >= 0) ? 128.0f : 192.0f;
+ putTerrainVertex(xA, yA, zA, normA[0], normA[1], normA[2], xA / uvScale, zA / uvScale, rgbA, 1.0f, mA, mB, mC, 0, surfType);
+ putTerrainVertex(xB, yB, zB, normB[0], normB[1], normB[2], xB / uvScale, zB / uvScale, rgbB, 1.0f, mA, mB, mC, 1, surfType);
+ putTerrainVertex(xC, yC, zC, normC[0], normC[1], normC[2], xC / uvScale, zC / uvScale, rgbC, 1.0f, mA, mB, mC, 2, surfType);
+ }
+ }
+
+ public void appendModel(Model model, int orientation, int relX, int relY, int relZ, int uid) {
+ if (model == null || model.anInt1630 <= 0) return;
+
+ boolean isStaticScenery = (uid != -1) && !HD317Pipeline.drawingAnimatedObj && (uid == 0 || ((uid >>> 29) & 3) == 2);
+ if (HD317Pipeline.useStaticScenery && staticSceneryBuilt && !buildingStaticScenery && isStaticScenery) {
+ return;
+ }
+ int baseSurfType = HD317Pipeline.drawingWall ? SURF_WALL : (isStaticScenery ? SURF_MODEL : SURF_ACTOR);
+
+ int faceCount = model.anInt1630;
+ float modelWorldX = relX + WorldController.anInt455;
+ float modelWorldY = relY + WorldController.anInt456 - (isStaticScenery ? 0.0f : 3.5f);
+ float modelWorldZ = relZ + WorldController.anInt457;
+
+ int sin = 0;
+ int cos = 65536;
+ if (orientation != 0 && Model.modelIntArray1 != null && Model.modelIntArray2 != null) {
+ sin = Model.modelIntArray1[orientation & 2047];
+ cos = Model.modelIntArray2[orientation & 2047];
+ }
+
+ int plane = Math.max(0, Math.min(3, HD317Pipeline.drawingPlane));
+ int cacheTypeKey = baseSurfType + plane * 8;
+ CachedModel cached = modelCache.get(model);
+ if (cached != null && cached.version == model.hdCacheVersion && cached.surfType == cacheTypeKey) {
+ emitCachedModel(cached, orientation, sin, cos, modelWorldX, modelWorldY, modelWorldZ);
+ return;
+ }
+ if (cached != null) {
+ modelCache.remove(model);
+ cachedModelFloats -= cached.totalFloats;
+ }
+
+ Class33[] normals = model.hdVertexNormals;
+ if (normals == null) {
+ normals = (model.aClass33Array1660 != null) ? model.aClass33Array1660 : model.aClass33Array1425;
+ }
+ int[] palette = Texture.anIntArray1482;
+ if (palette == null) return;
+
+ boolean buildCache = false;
+ int cacheStartOpaque = opaqueVertexCount;
+ int cacheStartTrans = transVertexCount;
+ model.hdCleanFrames++;
+ if (model.hdCleanFrames >= 2
+ && faceCount * 3 * FLOATS_PER_VERTEX <= 200000
+ && opaqueVertexCount + faceCount * 3 <= MAX_OPAQUE_VERTICES
+ && transVertexCount + faceCount * 3 <= MAX_TRANS_VERTICES) {
+ buildCache = true;
+ }
+
+ int effOrientation = buildCache ? 0 : orientation;
+ float effWorldX = buildCache ? 0.0f : modelWorldX;
+ float effWorldY = buildCache ? 0.0f : modelWorldY;
+ float effWorldZ = buildCache ? 0.0f : modelWorldZ;
+
+ for (int f = 0; f < faceCount; f++) {
+ int drawType = (model.anIntArray1637 != null) ? model.anIntArray1637[f] : 0;
+ if (drawType == -1) continue;
+
+ int cA = model.anIntArray1634[f];
+ int cB = model.anIntArray1635[f];
+ int cC = model.anIntArray1636[f];
+ if (cC == -2) continue;
+
+ boolean isTextured = (drawType & 2) != 0;
+ boolean isFlat = (drawType & 1) != 0 || cC == -1;
+
+ float alpha = 1.0f;
+ if (model.anIntArray1639 != null && model.anIntArray1639[f] > 0) {
+ alpha = Math.max(0.05f, (255 - (model.anIntArray1639[f] & 0xFF)) / 255.0f);
+ }
+
+ if (!isTextured && alpha < 0.88f) {
+ int lumA = cA & 0x7F;
+ int satA = (cA >> 7) & 0x07;
+ if (lumA <= 20 && satA <= 1) {
+ continue;
+ }
+ }
+
+ int vA = model.anIntArray1631[f];
+ int vB = model.anIntArray1632[f];
+ int vC = model.anIntArray1633[f];
+
+ int vxA = model.anIntArray1627[vA], vyA = model.anIntArray1628[vA], vzA = model.anIntArray1629[vA];
+ int vxB = model.anIntArray1627[vB], vyB = model.anIntArray1628[vB], vzB = model.anIntArray1629[vB];
+ int vxC = model.anIntArray1627[vC], vyC = model.anIntArray1628[vC], vzC = model.anIntArray1629[vC];
+
+ if (effOrientation != 0) {
+ int t = vzA * sin + vxA * cos >> 16;
+ vzA = vzA * cos - vxA * sin >> 16;
+ vxA = t;
+
+ t = vzB * sin + vxB * cos >> 16;
+ vzB = vzB * cos - vxB * sin >> 16;
+ vxB = t;
+
+ t = vzC * sin + vxC * cos >> 16;
+ vzC = vzC * cos - vxC * sin >> 16;
+ vxC = t;
+ }
+
+ float wxA = vxA + effWorldX, wyA = vyA + effWorldY, wzA = vzA + effWorldZ;
+ float wxB = vxB + effWorldX, wyB = vyB + effWorldY, wzB = vzB + effWorldZ;
+ float wxC = vxC + effWorldX, wyC = vyC + effWorldY, wzC = vzC + effWorldZ;
+
+ boolean isHorizontalFace = (vyA == vyB && vyB == vyC);
+ float nxA, nyA, nzA, nxB, nyB, nzB, nxC, nyC, nzC;
+ if (isHorizontalFace) {
+ // Flat horizontal polygons (rugs, carpets, tabletops) use a pure vertical normal
+ // so perimeter side-skirts never bend the lighting into a curved pillow gradient
+ nxA = nxB = nxC = 0.0f;
+ nyA = nyB = nyC = -1.0f;
+ nzA = nzB = nzC = 0.0f;
+ } else if (!isFlat && normals != null
+ && vA < normals.length && vB < normals.length && vC < normals.length
+ && normals[vA] != null && normals[vB] != null && normals[vC] != null
+ && normals[vA].anInt605 > 0 && normals[vB].anInt605 > 0 && normals[vC].anInt605 > 0) {
+ Class33 nA = normals[vA], nB = normals[vB], nC = normals[vC];
+ if (effOrientation != 0) {
+ nxA = (nA.anInt604 * sin + nA.anInt602 * cos) >> 16;
+ nyA = nA.anInt603;
+ nzA = (nA.anInt604 * cos - nA.anInt602 * sin) >> 16;
+
+ nxB = (nB.anInt604 * sin + nB.anInt602 * cos) >> 16;
+ nyB = nB.anInt603;
+ nzB = (nB.anInt604 * cos - nB.anInt602 * sin) >> 16;
+
+ nxC = (nC.anInt604 * sin + nC.anInt602 * cos) >> 16;
+ nyC = nC.anInt603;
+ nzC = (nC.anInt604 * cos - nC.anInt602 * sin) >> 16;
+ } else {
+ nxA = nA.anInt602; nyA = nA.anInt603; nzA = nA.anInt604;
+ nxB = nB.anInt602; nyB = nB.anInt603; nzB = nB.anInt604;
+ nxC = nC.anInt602; nyC = nC.anInt603; nzC = nC.anInt604;
+ }
+ } else {
+ float e1x = wxB - wxA, e1y = wyB - wyA, e1z = wzB - wzA;
+ float e2x = wxC - wxA, e2y = wyC - wyA, e2z = wzC - wzA;
+ float fnx = e1y * e2z - e1z * e2y;
+ float fny = e1z * e2x - e1x * e2z;
+ float fnz = e1x * e2y - e1y * e2x;
+ nxA = nxB = nxC = fnx;
+ nyA = nyB = nyC = fny;
+ nzA = nzB = nzC = fnz;
+ }
+
+ int matId = HdMaterial.NONE;
+ float uA = 0f, vUvA = 0f, uB = 1f, vUvB = 0f, uC = 0f, vUvC = 1f;
+ int rgbA, rgbB, rgbC;
+ int surfType = baseSurfType;
+
+ if (isTextured && model.anIntArray1640 != null) {
+ matId = model.anIntArray1640[f];
+
+ int tIdx = drawType >> 2;
+ int pIdx = vA, mIdx = vB, nIdx = vC;
+ if (model.anIntArray1643 != null && tIdx >= 0 && tIdx < model.anIntArray1643.length) {
+ pIdx = model.anIntArray1643[tIdx];
+ mIdx = model.anIntArray1644[tIdx];
+ nIdx = model.anIntArray1645[tIdx];
+ }
+
+ float px = model.anIntArray1627[pIdx], py = model.anIntArray1628[pIdx], pz = model.anIntArray1629[pIdx];
+ float mx = model.anIntArray1627[mIdx] - px, my = model.anIntArray1628[mIdx] - py, mz = model.anIntArray1629[mIdx] - pz;
+ float nx = model.anIntArray1627[nIdx] - px, ny = model.anIntArray1628[nIdx] - py, nz = model.anIntArray1629[nIdx] - pz;
+
+ float wx = my * nz - mz * ny;
+ float wy = mz * nx - mx * nz;
+ float wz = mx * ny - my * nx;
+
+ float uPerpX = ny * wz - nz * wy;
+ float uPerpY = nz * wx - nx * wz;
+ float uPerpZ = nx * wy - ny * wx;
+ float uDenom = uPerpX * mx + uPerpY * my + uPerpZ * mz;
+ if (Math.abs(uDenom) < 1e-4f) uDenom = 1.0f;
+
+ float vPerpX = wy * mz - wz * my;
+ float vPerpY = wz * mx - wx * mz;
+ float vPerpZ = wx * my - wy * mx;
+ float vDenom = vPerpX * nx + vPerpY * ny + vPerpZ * nz;
+ if (Math.abs(vDenom) < 1e-4f) vDenom = 1.0f;
+
+ float dxA = model.anIntArray1627[vA] - px, dyA = model.anIntArray1628[vA] - py, dzA = model.anIntArray1629[vA] - pz;
+ float dxB = model.anIntArray1627[vB] - px, dyB = model.anIntArray1628[vB] - py, dzB = model.anIntArray1629[vB] - pz;
+ float dxC = model.anIntArray1627[vC] - px, dyC = model.anIntArray1628[vC] - py, dzC = model.anIntArray1629[vC] - pz;
+
+ uA = (uPerpX * dxA + uPerpY * dyA + uPerpZ * dzA) / uDenom;
+ vUvA = (vPerpX * dxA + vPerpY * dyA + vPerpZ * dzA) / vDenom;
+ uB = (uPerpX * dxB + uPerpY * dyB + uPerpZ * dzB) / uDenom;
+ vUvB = (vPerpX * dxB + vPerpY * dyB + vPerpZ * dzB) / vDenom;
+ uC = (uPerpX * dxC + uPerpY * dyC + uPerpZ * dzC) / uDenom;
+ vUvC = (vPerpX * dxC + vPerpY * dyC + vPerpZ * dzC) / vDenom;
+
+ if (matId == 24 || matId == 17 || matId == 1 || matId == 34) {
+ rgbA = 0xFFFFFF;
+ rgbB = 0xFFFFFF;
+ rgbC = 0xFFFFFF;
+ } else {
+ int sA = Math.max(115, Math.min(250, 115 + (127 - (cA & 0x7F)) * 135 / 127));
+ int sB = isFlat ? sA : Math.max(115, Math.min(250, 115 + (127 - (cB & 0x7F)) * 135 / 127));
+ int sC = isFlat ? sA : Math.max(115, Math.min(250, 115 + (127 - (cC & 0x7F)) * 135 / 127));
+ rgbA = (sA << 16) | (sA << 8) | sA;
+ rgbB = (sB << 16) | (sB << 8) | sB;
+ rgbC = (sC << 16) | (sC << 8) | sC;
+ }
+ } else {
+ int unlitHsl = (model.anIntArray1640 != null) ? model.anIntArray1640[f] : cA;
+ rgbA = resolveModelVertexRgb(unlitHsl, cA, palette);
+ rgbB = isFlat ? rgbA : resolveModelVertexRgb(unlitHsl, cB, palette);
+ rgbC = isFlat ? rgbA : resolveModelVertexRgb(unlitHsl, cC, palette);
+ }
+
+ // Encode monotonic face priority (0..11) + face order (f / faceCount) into [0.0, 0.9375]
+ // so stacked coplanar model faces (e.g. rug base -> gold border -> inner rug -> white stars)
+ // always pass the hardware depth test in exact RS2 painter's order!
+ int prio = (model.anIntArray1638 != null) ? (model.anIntArray1638[f] & 0xFF) : model.anInt1641;
+ float faceOrder = (faceCount > 1) ? ((float) f / (float) faceCount) : 0.0f;
+ float faceBias = Math.min(0.9375f, (Math.min(11, Math.max(0, prio)) + faceOrder * 0.95f) / 12.8f);
+
+ boolean isWaterDroplet = (matId == 24 || matId == 17 || matId == 1 || matId == 34);
+ if (alpha >= 0.95f && !isWaterDroplet) {
+ if (opaqueVertexCount + 3 <= MAX_OPAQUE_VERTICES) {
+ putOpaqueVertex(wxA, wyA, wzA, nxA, nyA, nzA, uA, vUvA, rgbA, alpha, matId, matId, matId, 0, surfType, faceBias);
+ putOpaqueVertex(wxB, wyB, wzB, nxB, nyB, nzB, uB, vUvB, rgbB, alpha, matId, matId, matId, 1, surfType, faceBias);
+ putOpaqueVertex(wxC, wyC, wzC, nxC, nyC, nzC, uC, vUvC, rgbC, alpha, matId, matId, matId, 2, surfType, faceBias);
+ }
+ } else {
+ if (transVertexCount + 3 <= MAX_TRANS_VERTICES) {
+ putTransVertex(wxA, wyA, wzA, nxA, nyA, nzA, uA, vUvA, rgbA, alpha, matId, matId, matId, 0, surfType, faceBias);
+ putTransVertex(wxB, wyB, wzB, nxB, nyB, nzB, uB, vUvB, rgbB, alpha, matId, matId, matId, 1, surfType, faceBias);
+ putTransVertex(wxC, wyC, wzC, nxC, nyC, nzC, uC, vUvC, rgbC, alpha, matId, matId, matId, 2, surfType, faceBias);
+ }
+ }
+ }
+
+ if (buildCache) {
+ int oVerts = opaqueVertexCount - cacheStartOpaque;
+ int tVerts = transVertexCount - cacheStartTrans;
+ int totalFloats = (oVerts + tVerts) * FLOATS_PER_VERTEX;
+ if (totalFloats > 0 && totalFloats <= MAX_CACHED_MODEL_FLOATS) {
+ while (cachedModelFloats + totalFloats > MAX_CACHED_MODEL_FLOATS && !modelCache.isEmpty()) {
+ Iterator> it = modelCache.entrySet().iterator();
+ if (!it.hasNext()) break;
+ CachedModel evicted = it.next().getValue();
+ it.remove();
+ cachedModelFloats -= evicted.totalFloats;
+ }
+ CachedModel entry = new CachedModel();
+ entry.opaqueVerts = oVerts;
+ entry.opaque = (oVerts > 0)
+ ? Arrays.copyOfRange(opaqueStaging, cacheStartOpaque * FLOATS_PER_VERTEX, opaqueVertexCount * FLOATS_PER_VERTEX)
+ : null;
+ entry.transVerts = tVerts;
+ entry.trans = (tVerts > 0)
+ ? Arrays.copyOfRange(transStaging, cacheStartTrans * FLOATS_PER_VERTEX, transVertexCount * FLOATS_PER_VERTEX)
+ : null;
+ entry.surfType = cacheTypeKey;
+ entry.version = model.hdCacheVersion;
+ entry.totalFloats = totalFloats;
+ modelCache.put(model, entry);
+ cachedModelFloats += totalFloats;
+
+ opaqueVertexCount = cacheStartOpaque;
+ transVertexCount = cacheStartTrans;
+ emitCachedModel(entry, orientation, sin, cos, modelWorldX, modelWorldY, modelWorldZ);
+ }
+ }
+ }
+
+ private void emitCachedModel(CachedModel cached, int orientation, int sin, int cos,
+ float worldX, float worldY, float worldZ) {
+ int oVerts = cached.opaqueVerts;
+ if (oVerts > 0 && opaqueVertexCount + oVerts <= MAX_OPAQUE_VERTICES) {
+ emitCachedArray(cached.opaque, oVerts, opaqueStaging, opaqueVertexCount, orientation, sin, cos, worldX, worldY, worldZ);
+ opaqueVertexCount += oVerts;
+ }
+ int tVerts = cached.transVerts;
+ if (tVerts > 0 && transVertexCount + tVerts <= MAX_TRANS_VERTICES) {
+ emitCachedArray(cached.trans, tVerts, transStaging, transVertexCount, orientation, sin, cos, worldX, worldY, worldZ);
+ transVertexCount += tVerts;
+ }
+ }
+
+ private static void emitCachedArray(float[] src, int vertCount, float[] dst, int dstVertOffset,
+ int orientation, int sin, int cos,
+ float worldX, float worldY, float worldZ) {
+ int floatCount = vertCount * FLOATS_PER_VERTEX;
+ int dstBase = dstVertOffset * FLOATS_PER_VERTEX;
+ System.arraycopy(src, 0, dst, dstBase, floatCount);
+ int end = dstBase + floatCount;
+ if (orientation == 0) {
+ for (int i = dstBase; i < end; i += FLOATS_PER_VERTEX) {
+ dst[i] += worldX;
+ dst[i + 1] += worldY;
+ dst[i + 2] += worldZ;
+ }
+ } else {
+ float fSin = sin / 65536.0f;
+ float fCos = cos / 65536.0f;
+ for (int i = dstBase; i < end; i += FLOATS_PER_VERTEX) {
+ float lx = dst[i];
+ float lz = dst[i + 2];
+ dst[i] = (lz * fSin + lx * fCos) + worldX;
+ dst[i + 1] += worldY;
+ dst[i + 2] = (lz * fCos - lx * fSin) + worldZ;
+
+ float lnx = dst[i + 3];
+ float lnz = dst[i + 5];
+ dst[i + 3] = lnz * fSin + lnx * fCos;
+ dst[i + 5] = lnz * fCos - lnx * fSin;
+ }
+ }
+ }
+
+ private int resolveGroundRgb(int hsl, int texId, int matId) {
+ if (texId >= 0) {
+ int shade = Math.max(95, Math.min(255, (127 - (hsl & 0x7F)) * 2));
+ return (shade << 16) | (shade << 8) | shade;
+ }
+ int[] palette = Texture.anIntArray1482;
+ if (palette == null || hsl < 0 || hsl >= palette.length) {
+ return 0x808080;
+ }
+
+ int hue = (hsl >> 10) & 0x3F;
+ int sat = (hsl >> 7) & 0x07;
+ int lum = hsl & 0x7F;
+
+ if (lum < 16) {
+ int liftedLum = Math.max(16, 10 + (lum * 6) / 16);
+ int liftedHsl = (hue << 10) | (sat << 7) | liftedLum;
+ if (liftedHsl >= 0 && liftedHsl < palette.length) {
+ return palette[liftedHsl];
+ }
+ }
+
+ return palette[hsl];
+ }
+
+ private int resolveModelVertexRgb(int unlitHsl, int litHsl, int[] palette) {
+ if (litHsl < 0 || litHsl >= palette.length) return 0x808080;
+ if (unlitHsl <= 0 || unlitHsl >= palette.length) {
+ return palette[litHsl];
+ }
+ int hs = unlitHsl & 0xFF80;
+ int baseLum = unlitHsl & 0x7F;
+ int litLum = litHsl & 0x7F;
+ int neutralLum = Math.max(12, Math.min(124, (baseLum * 9 + litLum * 11) / 20));
+ return palette[hs | neutralLum];
+ }
+
+ private final float[] tempInterpNorm = new float[3];
+
+ private float[] interpolateTileNormal(float tx, float tz, float[] n00, float[] n10, float[] n11, float[] n01) {
+ tx = Math.max(0f, Math.min(1f, tx));
+ tz = Math.max(0f, Math.min(1f, tz));
+ float nx = (n00[0] * (1f - tx) + n10[0] * tx) * (1f - tz) + (n01[0] * (1f - tx) + n11[0] * tx) * tz;
+ float ny = (n00[1] * (1f - tx) + n10[1] * tx) * (1f - tz) + (n01[1] * (1f - tx) + n11[1] * tx) * tz;
+ float nz = (n00[2] * (1f - tx) + n10[2] * tx) * (1f - tz) + (n01[2] * (1f - tx) + n11[2] * tx) * tz;
+ float inv = (float) (1.0 / Math.sqrt(nx * nx + ny * ny + nz * nz + 1e-6));
+ tempInterpNorm[0] = nx * inv;
+ tempInterpNorm[1] = ny * inv;
+ tempInterpNorm[2] = nz * inv;
+ return tempInterpNorm;
+ }
+
+ private void putTerrainVertex(float x, float y, float z,
+ float nx, float ny, float nz,
+ float u, float v,
+ int rgb, float alpha,
+ int matA, int matB, int matC,
+ int baryIndex, int surfType) {
+ int base = terrainVertexCount * FLOATS_PER_VERTEX;
+ writeVertexTo(terrainStaging, base, x, y, z, nx, ny, nz, u, v, rgb, alpha, matA, matB, matC, baryIndex, surfType, 0.0f, HD317Pipeline.drawingPlane);
+ terrainVertexCount++;
+ }
+
+ private void putOpaqueVertex(float x, float y, float z,
+ float nx, float ny, float nz,
+ float u, float v,
+ int rgb, float alpha,
+ int matA, int matB, int matC,
+ int baryIndex, int surfType) {
+ putOpaqueVertex(x, y, z, nx, ny, nz, u, v, rgb, alpha, matA, matB, matC, baryIndex, surfType, 0.0f);
+ }
+
+ private void putOpaqueVertex(float x, float y, float z,
+ float nx, float ny, float nz,
+ float u, float v,
+ int rgb, float alpha,
+ int matA, int matB, int matC,
+ int baryIndex, int surfType, float faceBias) {
+ int base = opaqueVertexCount * FLOATS_PER_VERTEX;
+ writeVertexTo(opaqueStaging, base, x, y, z, nx, ny, nz, u, v, rgb, alpha, matA, matB, matC, baryIndex, surfType, faceBias, HD317Pipeline.drawingPlane);
+ opaqueVertexCount++;
+ }
+
+ private void putTransVertex(float x, float y, float z,
+ float nx, float ny, float nz,
+ float u, float v,
+ int rgb, float alpha,
+ int matA, int matB, int matC,
+ int baryIndex, int surfType, float faceBias) {
+ int base = transVertexCount * FLOATS_PER_VERTEX;
+ writeVertexTo(transStaging, base, x, y, z, nx, ny, nz, u, v, rgb, alpha, matA, matB, matC, baryIndex, surfType, faceBias, HD317Pipeline.drawingPlane);
+ transVertexCount++;
+ }
+
+ private static void writeVertexTo(float[] arr, int base,
+ float x, float y, float z,
+ float nx, float ny, float nz,
+ float u, float v,
+ int rgb, float alpha,
+ int matA, int matB, int matC,
+ int baryIndex, int surfType, float faceBias, int plane) {
+ arr[base] = x;
+ arr[base + 1] = y;
+ arr[base + 2] = z;
+
+ arr[base + 3] = nx;
+ arr[base + 4] = ny;
+ arr[base + 5] = nz;
+
+ arr[base + 6] = u;
+ arr[base + 7] = v;
+
+ arr[base + 8] = ((rgb >> 16) & 0xFF) / 255.0f;
+ arr[base + 9] = ((rgb >> 8) & 0xFF) / 255.0f;
+ arr[base + 10] = (rgb & 0xFF) / 255.0f;
+ arr[base + 11] = alpha;
+
+ arr[base + 12] = (float) matA;
+ arr[base + 13] = (float) matB;
+ arr[base + 14] = (float) matC;
+ int p = Math.max(0, Math.min(3, plane));
+ arr[base + 15] = (float) (baryIndex + surfType * 4 + p * 32) + faceBias;
+ }
+}
diff --git a/2006Scape Client/src/main/java/ItemID.java b/2006Scape Client/src/main/java/ItemID.java
new file mode 100644
index 00000000..0490189c
--- /dev/null
+++ b/2006Scape Client/src/main/java/ItemID.java
@@ -0,0 +1,6 @@
+/**
+ * Item ID constants for the 2006Scape Client Plugin & Script API.
+ * Inherits all item constants from StaticItemList.
+ */
+public class ItemID extends StaticItemList {
+}
diff --git a/2006Scape Client/src/main/java/MenuEntry.java b/2006Scape Client/src/main/java/MenuEntry.java
new file mode 100644
index 00000000..4ca930d0
--- /dev/null
+++ b/2006Scape Client/src/main/java/MenuEntry.java
@@ -0,0 +1,165 @@
+import java.util.Objects;
+
+/**
+ * Represents a single right-click or left-click menu entry in the game.
+ */
+public class MenuEntry {
+
+ private String rawText;
+ private int actionId;
+ private int cmd1;
+ private int cmd2;
+ private int cmd3;
+
+ public MenuEntry() {
+ }
+
+ public MenuEntry(String rawText, int actionId, int cmd1, int cmd2, int cmd3) {
+ this.rawText = rawText;
+ this.actionId = actionId;
+ this.cmd1 = cmd1;
+ this.cmd2 = cmd2;
+ this.cmd3 = cmd3;
+ }
+
+ public String getRawText() {
+ return rawText != null ? rawText : "";
+ }
+
+ public void setRawText(String rawText) {
+ this.rawText = rawText;
+ }
+
+ public int getActionId() {
+ return actionId;
+ }
+
+ public void setActionId(int actionId) {
+ this.actionId = actionId;
+ }
+
+ public int getCmd1() {
+ return cmd1;
+ }
+
+ public void setCmd1(int cmd1) {
+ this.cmd1 = cmd1;
+ }
+
+ public int getCmd2() {
+ return cmd2;
+ }
+
+ public void setCmd2(int cmd2) {
+ this.cmd2 = cmd2;
+ }
+
+ public int getCmd3() {
+ return cmd3;
+ }
+
+ public void setCmd3(int cmd3) {
+ this.cmd3 = cmd3;
+ }
+
+ /**
+ * Strips RS color tags like @yel@, @whi@, @gre@, etc.
+ */
+ public static String stripColorTags(String text) {
+ if (text == null) {
+ return "";
+ }
+ StringBuilder sb = new StringBuilder(text.length());
+ boolean inTag = false;
+ for (int i = 0; i < text.length(); i++) {
+ char c = text.charAt(i);
+ if (c == '@' && !inTag) {
+ // Check if closing '@' exists within next 5 chars
+ int closingIndex = text.indexOf('@', i + 1);
+ if (closingIndex > i && closingIndex - i <= 5) {
+ i = closingIndex;
+ continue;
+ }
+ }
+ sb.append(c);
+ }
+ return sb.toString().trim();
+ }
+
+ /**
+ * Returns the verb / action prefix (e.g. "Talk-to", "Attack", "Take", "Bank", "Examine").
+ */
+ public String getAction() {
+ String clean = stripColorTags(rawText);
+ int spaceIndex = clean.indexOf(' ');
+ if (spaceIndex != -1) {
+ return clean.substring(0, spaceIndex).trim();
+ }
+ return clean.trim();
+ }
+
+ /**
+ * Returns the target name without action or color tags (e.g. "Man", "Chicken", "Feather").
+ */
+ public String getTarget() {
+ String clean = stripColorTags(rawText);
+ int spaceIndex = clean.indexOf(' ');
+ if (spaceIndex != -1) {
+ String target = clean.substring(spaceIndex + 1).trim();
+ // If combat level is attached: e.g. "Chicken (level-1)", strip combat level if desired or keep
+ return target;
+ }
+ return "";
+ }
+
+ /**
+ * Case-insensitive match check for action and target patterns.
+ * Empty or null pattern acts as wildcard "*".
+ */
+ public boolean matches(String actionPattern, String targetPattern) {
+ String act = getAction();
+ String tgt = getTarget();
+
+ if (actionPattern != null && !actionPattern.isEmpty() && !actionPattern.equals("*")) {
+ if (!act.equalsIgnoreCase(actionPattern)) {
+ return false;
+ }
+ }
+ if (targetPattern != null && !targetPattern.isEmpty() && !targetPattern.equals("*")) {
+ if (!tgt.toLowerCase().contains(targetPattern.toLowerCase())) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return "MenuEntry{" +
+ "action='" + getAction() + '\'' +
+ ", target='" + getTarget() + '\'' +
+ ", raw='" + rawText + '\'' +
+ ", id=" + actionId +
+ ", cmd1=" + cmd1 +
+ ", cmd2=" + cmd2 +
+ ", cmd3=" + cmd3 +
+ '}';
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof MenuEntry)) return false;
+ MenuEntry menuEntry = (MenuEntry) o;
+ return actionId == menuEntry.actionId &&
+ cmd1 == menuEntry.cmd1 &&
+ cmd2 == menuEntry.cmd2 &&
+ cmd3 == menuEntry.cmd3 &&
+ Objects.equals(rawText, menuEntry.rawText);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(rawText, actionId, cmd1, cmd2, cmd3);
+ }
+}
diff --git a/2006Scape Client/src/main/java/MenuEntrySwapperPlugin.java b/2006Scape Client/src/main/java/MenuEntrySwapperPlugin.java
new file mode 100644
index 00000000..a2666843
--- /dev/null
+++ b/2006Scape Client/src/main/java/MenuEntrySwapperPlugin.java
@@ -0,0 +1,156 @@
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * RuneLite-style Menu Entry Swapper Plugin.
+ * Allows left-click swapping for NPCs, objects, ground items, and custom rules.
+ */
+public class MenuEntrySwapperPlugin extends ClientPlugin {
+
+ private boolean swapBank = true;
+ private boolean swapTrade = true;
+ private boolean swapPickpocket = true;
+ private boolean swapTravel = true;
+ private boolean chatCommands = true;
+ private String customRules = "";
+
+ @Override
+ public String getName() {
+ return "Menu Entry Swapper";
+ }
+
+ @Override
+ public String getDescription() {
+ return "Swaps default left-click actions for Bank, Pickpocket, Trade, and custom rules.";
+ }
+
+ @Override
+ public String getAuthor() {
+ return "2006Scape";
+ }
+
+ @Override
+ public boolean isEnabledByDefault() {
+ return true;
+ }
+
+ @Override
+ public List getConfigItems() {
+ List list = new ArrayList<>();
+ list.add(new PluginConfigItem("swapBank", "Swap Bank", "Promote 'Bank' over 'Talk-to' on bankers", swapBank));
+ list.add(new PluginConfigItem("swapTrade", "Swap Trade", "Promote 'Trade' over 'Talk-to' on shopkeepers", swapTrade));
+ list.add(new PluginConfigItem("swapPickpocket", "Swap Pickpocket", "Promote 'Pickpocket' on NPCs", swapPickpocket));
+ list.add(new PluginConfigItem("swapTravel", "Swap Travel", "Promote 'Travel'/'Pay-fare' on captains", swapTravel));
+ list.add(new PluginConfigItem("customRules", "Custom Rules", "Comma-separated Option:Target pairs (e.g. Bury:Bones)", customRules));
+ list.add(new PluginConfigItem("chatCommands", "Chat Commands", "Allow ::swap / ::swapper in chat", chatCommands));
+ return list;
+ }
+
+ @Override
+ public void onConfigChanged(String key, Object value) {
+ if ("swapBank".equals(key)) swapBank = (Boolean) value;
+ else if ("swapTrade".equals(key)) swapTrade = (Boolean) value;
+ else if ("swapPickpocket".equals(key)) swapPickpocket = (Boolean) value;
+ else if ("swapTravel".equals(key)) swapTravel = (Boolean) value;
+ else if ("chatCommands".equals(key)) chatCommands = (Boolean) value;
+ else if ("customRules".equals(key)) customRules = (String) value;
+ }
+
+ @Override
+ public void onPreMenuRender(List entries) {
+ if (entries == null || entries.size() <= 1) {
+ return;
+ }
+
+ // Apply custom swap rules first
+ if (customRules != null && !customRules.trim().isEmpty()) {
+ String[] rules = customRules.split(",");
+ for (String rule : rules) {
+ String[] parts = rule.trim().split(":");
+ if (parts.length >= 2) {
+ String action = parts[0].trim();
+ String target = parts[1].trim();
+ if (promoteEntry(entries, action, target)) {
+ return;
+ }
+ }
+ }
+ }
+
+ // Built-in Bank swap (Banker, Bank booth, Bank chest)
+ if (swapBank) {
+ if (promoteEntry(entries, "Bank", "*") || promoteEntry(entries, "Open", "Bank")) {
+ return;
+ }
+ }
+
+ // Built-in Pickpocket swap
+ if (swapPickpocket) {
+ if (promoteEntry(entries, "Pickpocket", "*")) {
+ return;
+ }
+ }
+
+ // Built-in Trade swap
+ if (swapTrade) {
+ if (promoteEntry(entries, "Trade", "*")) {
+ return;
+ }
+ }
+
+ // Built-in Travel / Pay-fare swap
+ if (swapTravel) {
+ if (promoteEntry(entries, "Pay-fare", "*") ||
+ promoteEntry(entries, "Travel", "*") ||
+ promoteEntry(entries, "Charter", "*") ||
+ promoteEntry(entries, "Teleport", "*")) {
+ return;
+ }
+ }
+ }
+
+ private boolean promoteEntry(List entries, String action, String target) {
+ int foundIdx = -1;
+ for (int i = 0; i < entries.size(); i++) {
+ MenuEntry e = entries.get(i);
+ if (e.matches(action, target)) {
+ foundIdx = i;
+ break;
+ }
+ }
+ if (foundIdx != -1 && foundIdx != entries.size() - 1) {
+ MenuEntry targetEntry = entries.remove(foundIdx);
+ entries.add(targetEntry); // Top of menu (left-click)
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean onCommand(String command, String[] args) {
+ if ("swap".equalsIgnoreCase(command) || "swapper".equalsIgnoreCase(command)) {
+ if (args.length >= 2 && "add".equalsIgnoreCase(args[0])) {
+ String newRule = args[1].trim();
+ customRules = (customRules != null && !customRules.isEmpty()) ? customRules + "," + newRule : newRule;
+ if (ctx != null) {
+ ctx.sendClientMessage("Added swap rule: " + newRule);
+ }
+ return true;
+ } else if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) {
+ customRules = "";
+ if (ctx != null) {
+ ctx.sendClientMessage("Custom swap rules cleared.");
+ }
+ return true;
+ } else {
+ if (ctx != null) {
+ ctx.sendClientMessage("Menu Swapper Rules: " + customRules);
+ ctx.sendClientMessage("Usage: ::swap add : or ::swap clear");
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+}
diff --git a/2006Scape Client/src/main/java/Model.java b/2006Scape Client/src/main/java/Model.java
index 53d5efe3..fe5880b1 100644
--- a/2006Scape Client/src/main/java/Model.java
+++ b/2006Scape Client/src/main/java/Model.java
@@ -625,6 +625,7 @@ public final class Model extends Animable {
anIntArray1636 = model.anIntArray1636;
anIntArray1637 = model.anIntArray1637;
}
+ hdVertexNormals = model.hdVertexNormals;
anIntArray1627 = model.anIntArray1627;
anIntArray1629 = model.anIntArray1629;
anIntArray1640 = model.anIntArray1640;
@@ -649,6 +650,7 @@ public final class Model extends Animable {
}
public void method464(Model model, boolean flag) {
+ invalidateHdCache();
anInt1626 = model.anInt1626;
anInt1630 = model.anInt1630;
anInt1642 = model.anInt1642;
@@ -698,6 +700,9 @@ public final class Model extends Animable {
anIntArray1643 = model.anIntArray1643;
anIntArray1644 = model.anIntArray1644;
anIntArray1645 = model.anIntArray1645;
+ aClass33Array1660 = model.aClass33Array1660;
+ super.aClass33Array1425 = model.aClass33Array1425;
+ hdVertexNormals = model.hdVertexNormals;
}
private int method465(Model model, int i) {
@@ -859,6 +864,7 @@ public final class Model extends Animable {
}
public void method470(int i) {
+ invalidateHdCache();
if (anIntArrayArray1657 == null) {
return;
}
@@ -881,6 +887,7 @@ public final class Model extends Animable {
}
public void method471(int ai[], int j, int k) {
+ invalidateHdCache();
if (k == -1) {
return;
}
@@ -1070,6 +1077,7 @@ public final class Model extends Animable {
}
public void method473() {
+ invalidateHdCache();
for (int j = 0; j < anInt1626; j++) {
int k = anIntArray1627[j];
anIntArray1627[j] = anIntArray1629[j];
@@ -1079,6 +1087,7 @@ public final class Model extends Animable {
}
public void method474(int i) {
+ invalidateHdCache();
int k = modelIntArray1[i];
int l = modelIntArray2[i];
for (int i1 = 0; i1 < anInt1626; i1++) {
@@ -1089,6 +1098,7 @@ public final class Model extends Animable {
}
public void method475(int i, int j, int l) {
+ invalidateHdCache();
for (int i1 = 0; i1 < anInt1626; i1++) {
anIntArray1627[i1] += i;
anIntArray1628[i1] += j;
@@ -1098,6 +1108,7 @@ public final class Model extends Animable {
}
public void method476(int i, int j) {
+ invalidateHdCache();
for (int k = 0; k < anInt1630; k++) {
if (anIntArray1640[k] == i) {
anIntArray1640[k] = j;
@@ -1107,6 +1118,7 @@ public final class Model extends Animable {
}
public void method477() {
+ invalidateHdCache();
for (int j = 0; j < anInt1626; j++) {
anIntArray1629[j] = -anIntArray1629[j];
}
@@ -1119,6 +1131,7 @@ public final class Model extends Animable {
}
public void method478(int i, int j, int l) {
+ invalidateHdCache();
for (int i1 = 0; i1 < anInt1626; i1++) {
anIntArray1627[i1] = anIntArray1627[i1] * i / 128;
anIntArray1628[i1] = anIntArray1628[i1] * l / 128;
@@ -1128,6 +1141,7 @@ public final class Model extends Animable {
}
public void method479(int i, int j, int k, int l, int i1, boolean flag) {
+ invalidateHdCache();
int j1 = (int) Math.sqrt(k * k + l * l + i1 * i1);
int k1 = j * j1 >> 8;
if (anIntArray1634 == null) {
@@ -1201,6 +1215,7 @@ public final class Model extends Animable {
class33_1.anInt604 = class33.anInt604;
class33_1.anInt605 = class33.anInt605;
}
+ hdVertexNormals = aClass33Array1660;
}
if (flag) {
@@ -1211,6 +1226,7 @@ public final class Model extends Animable {
}
public void method480(int i, int j, int k, int l, int i1) {
+ invalidateHdCache();
for (int j1 = 0; j1 < anInt1630; j1++) {
int k1 = anIntArray1631[j1];
int i2 = anIntArray1632[j1];
@@ -1241,19 +1257,23 @@ public final class Model extends Animable {
}
}
+ if (super.aClass33Array1425 != null) {
+ hdVertexNormals = new Class33[anInt1626];
+ for (int k2 = 0; k2 < anInt1626; k2++) {
+ Class33 src = super.aClass33Array1425[k2];
+ if (src != null) {
+ Class33 dst = hdVertexNormals[k2] = new Class33();
+ dst.anInt602 = src.anInt602;
+ dst.anInt603 = src.anInt603;
+ dst.anInt604 = src.anInt604;
+ dst.anInt605 = src.anInt605;
+ }
+ }
+ }
super.aClass33Array1425 = null;
aClass33Array1660 = null;
anIntArray1655 = null;
anIntArray1656 = null;
- if (anIntArray1637 != null) {
- for (int l1 = 0; l1 < anInt1630; l1++) {
- if ((anIntArray1637[l1] & 2) == 2) {
- return;
- }
- }
-
- }
- anIntArray1640 = null;
}
private static int method481(int i, int j, int k) {
@@ -1335,30 +1355,49 @@ public final class Model extends Animable {
int k2 = k1 * j + j2 * k >> 16;
int l2 = anInt1650 * k >> 16;
int i3 = k2 + l2;
- // Check distance of model to camera for rendering (default 3500)
- int distance = WorldController.drawDistance * 256;
- distance *= 1 + (Game.zoom / 10);
- if (i3 <= 50 || k2 >= distance) {
+ boolean hdActive = ClientSettings.HD_317 && HD317Pipeline.isGpuActive();
+ // Check distance of model to camera for rendering
+ int distance;
+ if (hdActive) {
+ distance = Math.max(4800, (WorldController.effectiveDrawDist + 16) * 128);
+ } else if (ClientSettings.ANDROID) {
+ // In software mode, strictly synchronize model culling distance with ground terrain bounds
+ distance = WorldController.effectiveDrawDist * 128 + 128;
+ } else {
+ distance = WorldController.drawDistance * 256;
+ distance *= 1 + (Game.zoom / 10);
+ }
+ if (i3 <= ((ClientSettings.ANDROID || hdActive) ? 20 : 50) || k2 >= distance) {
return;
}
+
+ int boundX = DrawingArea.centerY;
+ int boundY = DrawingArea.anInt1387;
+ if (hdActive) {
+ int w = DrawingArea.width > 0 ? DrawingArea.width : 1024;
+ int h = DrawingArea.height > 0 ? DrawingArea.height : 768;
+ int minDim = Math.max(1, Math.min(w, h));
+ boundX = (w * 360) / minDim + 180;
+ boundY = (h * 450) / minDim + 180;
+ }
int j3 = l1 * l + j1 * i1 >> 16;
int k3 = j3 - anInt1650 << 9;
- if (k3 / i3 >= DrawingArea.centerY) {
+ if (k3 / i3 >= boundX) {
return;
}
int l3 = j3 + anInt1650 << 9;
- if (l3 / i3 <= -DrawingArea.centerY) {
+ if (l3 / i3 <= -boundX) {
return;
}
int i4 = k1 * k - j2 * j >> 16;
int j4 = anInt1650 * j >> 16;
int k4 = i4 + j4 << 9;
- if (k4 / i3 <= -DrawingArea.anInt1387) {
+ if (k4 / i3 <= -boundY) {
return;
}
int l4 = j4 + (super.modelHeight * k >> 16);
int i5 = i4 - l4 << 9;
- if (i5 / i3 >= DrawingArea.anInt1387) {
+ if (i5 / i3 >= boundY) {
return;
}
int j5 = l2 + (super.modelHeight * j >> 16);
@@ -1396,6 +1435,10 @@ public final class Model extends Animable {
}
}
}
+ if (hdActive && !flag1) {
+ HD317Pipeline.drawModel(this, i, j, k, l, i1, j1, k1, l1, i2);
+ return;
+ }
int l5 = Texture.textureInt1;
int j6 = Texture.textureInt2;
int l6 = 0;
@@ -1437,6 +1480,28 @@ public final class Model extends Animable {
}
}
+ if (hdActive) {
+ if (flag1) {
+ for (int k7 = 0; k7 < anInt1630; k7++) {
+ if (anIntArray1637 == null || anIntArray1637[k7] != -1) {
+ int vA = anIntArray1631[k7];
+ int vB = anIntArray1632[k7];
+ int vC = anIntArray1633[k7];
+ int xA = anIntArray1665[vA];
+ int xB = anIntArray1665[vB];
+ int xC = anIntArray1665[vC];
+ if ((!flag || (xA != -5000 && xB != -5000 && xC != -5000))
+ && method486(anInt1685, anInt1686, anIntArray1666[vA], anIntArray1666[vB], anIntArray1666[vC], xA, xB, xC)) {
+ anIntArray1688[anInt1687++] = i2;
+ break;
+ }
+ }
+ }
+ }
+ HD317Pipeline.drawModel(this, i, j, k, l, i1, j1, k1, l1, i2);
+ return;
+ }
+
try {
method483(flag, flag1, i2);
} catch (Exception _ex) {
@@ -1829,18 +1894,18 @@ public final class Model extends Animable {
public int anIntArray1631[];
public int anIntArray1632[];
public int anIntArray1633[];
- private int[] anIntArray1634;
- private int[] anIntArray1635;
- private int[] anIntArray1636;
+ public int[] anIntArray1634;
+ public int[] anIntArray1635;
+ public int[] anIntArray1636;
public int anIntArray1637[];
- private int[] anIntArray1638;
- private int[] anIntArray1639;
+ public int[] anIntArray1638;
+ public int[] anIntArray1639;
public int anIntArray1640[];
- private int anInt1641;
- private int anInt1642;
- private int[] anIntArray1643;
- private int[] anIntArray1644;
- private int[] anIntArray1645;
+ public int anInt1641;
+ public int anInt1642;
+ public int[] anIntArray1643;
+ public int[] anIntArray1644;
+ public int[] anIntArray1645;
public int anInt1646;
public int anInt1647;
public int anInt1648;
@@ -1855,7 +1920,15 @@ public final class Model extends Animable {
public int anIntArrayArray1657[][];
public int anIntArrayArray1658[][];
public boolean aBoolean1659;
- Class33 aClass33Array1660[];
+ public Class33 aClass33Array1660[];
+ public Class33 hdVertexNormals[];
+ public int hdCacheVersion = 0;
+ public int hdCleanFrames = 0;
+
+ public void invalidateHdCache() {
+ hdCacheVersion++;
+ hdCleanFrames = 0;
+ }
private static Class21[] aClass21Array1661;
private static OnDemandFetcherParent aOnDemandFetcherParent_1662;
private static boolean[] aBooleanArray1663 = new boolean[4096];
diff --git a/2006Scape Client/src/main/java/ModernLayout.java b/2006Scape Client/src/main/java/ModernLayout.java
new file mode 100644
index 00000000..54f195bf
--- /dev/null
+++ b/2006Scape Client/src/main/java/ModernLayout.java
@@ -0,0 +1,201 @@
+/**
+ * ModernLayout
+ *
+ * Coordinates and hit-testing for the modern resizable layout.
+ * Pure Java: no java.awt or android.* imports, allowing 100% shared code
+ * between Desktop and Android.
+ */
+public final class ModernLayout {
+
+ public static final int TARGET_DEFAULT = 0;
+ public static final int TARGET_VIEWPORT = 1;
+ public static final int TARGET_TAB = 2;
+ public static final int TARGET_CHAT = 3;
+ public static final int TARGET_MINIMAP = 4;
+
+ public static int windowWidth = 765;
+ public static int windowHeight = 503;
+ public static boolean inGame = false;
+
+ private ModernLayout() {}
+
+ public static void updateWindowSize(int w, int h) {
+ if (w < 765) w = 765;
+ if (h < 503) h = 503;
+ windowWidth = w;
+ windowHeight = h;
+ }
+
+ public static int hit(int x, int y) {
+ if (!ClientSettings.isModernLayout() || !inGame) {
+ return TARGET_DEFAULT;
+ }
+ int w = windowWidth;
+ int h = windowHeight;
+
+ // Minimap: top right (from w - 249 to w, y from 0 to 168)
+ if (x >= w - 249 && y <= 168) {
+ int localX = x - (w - 249);
+ int localY = y;
+ if (isInsideMinimap(localX, localY)) {
+ return TARGET_MINIMAP;
+ }
+ }
+
+ // Tab block: bottom right (from w - 249 to w, y from h - 343 to h)
+ if (x >= w - 249 && y >= h - 343) {
+ int localX = x - (w - 249);
+ int localY = y - (h - 343);
+ if (isInsideTabArea(localX, localY)) {
+ return TARGET_TAB;
+ }
+ }
+
+ // Chatbox: bottom left (from 0 to 519, y from h - 165 to h)
+ if (x <= 519 && y >= h - 165) {
+ return TARGET_CHAT;
+ }
+
+ return TARGET_VIEWPORT;
+ }
+
+ // Symmetrical corner inset profile for dy = 0..33 from top (sy=0) or bottom (sy=334) of the 234x335 stone ring
+ private static final int[] TAB_CORNER_DX = {
+ 234, // dy = 0 (outermost 1px row is transparent)
+ 28, 26, 24, 22, 20, 19, 17,
+ 14, 13, 11, 10, 9, 8, 8,
+ 7, 7, 7, 7, 6, 6, 6,
+ 5, 5, 5, 5, 4, 4, 3,
+ 3, 3, 3, 2, 2
+ };
+
+ public static boolean isInsideTabArea(int localX, int localY) {
+ int sx = localX - 15;
+ int sy = localY - 8;
+ if (sx <= 0 || sx >= 233 || sy <= 0 || sy >= 334) {
+ return false;
+ }
+ int dy = Math.min(sy, 334 - sy);
+ int dx = (dy < TAB_CORNER_DX.length) ? TAB_CORNER_DX[dy] : 1;
+ return sx >= dx && sx <= (233 - dx);
+ }
+
+ public static boolean isInsideMinimap(int localX, int localY) {
+ // 1. Compass circular area (centered at (16, 16), radius 16)
+ int cDx = localX - 16;
+ int cDy = localY - 16;
+ if (cDx * cDx + cDy * cDy <= 16 * 16) {
+ return true;
+ }
+
+ // 2. Minimap elliptical walking area (centered at (132, 84), Rx=76, Ry=78)
+ float mDx = (localX - 132) / 76f;
+ float mDy = (localY - 84) / 78f;
+ return (mDx * mDx + mDy * mDy) <= 1.0f;
+ }
+
+ /**
+ * Computes aspect-ratio-preserved scaled bounds { originX, originY, scaledW, scaledH }
+ * for a 765x503 canvas (login/title screen or welcome screen) inside window (w, h),
+ * matching the Android client's welcomeScale behavior.
+ */
+ public static int[] getScaledScreenBounds(int w, int h) {
+ float scale = Math.min((float) w / 765f, (float) h / 503f);
+ int scaledW = Math.round(765 * scale);
+ int scaledH = Math.round(503 * scale);
+ int originX = Math.max(0, (w - scaledW) / 2);
+ int originY = Math.max(0, (h - scaledH) / 2);
+ return new int[] { originX, originY, scaledW, scaledH };
+ }
+
+ /**
+ * Maps window coordinates (x, y) to fixed-layout game coordinates (used by input processing).
+ */
+ public static int[] toGameCoords(int area, int x, int y) {
+ if (!ClientSettings.isModernLayout()) {
+ return new int[] { x, y };
+ }
+ int w = windowWidth;
+ int h = windowHeight;
+
+ if (!inGame) {
+ int[] b = getScaledScreenBounds(w, h);
+ int gx = ((x - b[0]) * 765) / Math.max(1, b[2]);
+ int gy = ((y - b[1]) * 503) / Math.max(1, b[3]);
+ return new int[] { gx, gy };
+ }
+
+ switch (area) {
+ case TARGET_MINIMAP:
+ return new int[] { x - (w - 765), y };
+ case TARGET_TAB:
+ return new int[] { x - (w - 765), y - (h - 503) };
+ case TARGET_CHAT:
+ return new int[] { x, y - (h - 503) };
+ case TARGET_VIEWPORT:
+ default:
+ return new int[] { x, y };
+ }
+ }
+
+ /**
+ * Maps classic fixed coordinates (fixedX, fixedY) of a UI element/producer to window coordinates.
+ * Returns null if the element should be hidden/skipped in modern layout (e.g. fixed outer border frames).
+ */
+ public static int[] toWindow(int fixedX, int fixedY, int width, int height) {
+ if (!ClientSettings.isModernLayout()) {
+ return new int[] { fixedX, fixedY };
+ }
+ int w = windowWidth;
+ int h = windowHeight;
+
+ if (!inGame || (width == 765 && height == 503 && fixedX == 0 && fixedY == 0)) {
+ int[] b = getScaledScreenBounds(w, h);
+ int x0 = b[0] + (fixedX * b[2]) / 765;
+ int y0 = b[1] + (fixedY * b[3]) / 503;
+ int x1 = b[0] + ((fixedX + width) * b[2]) / 765;
+ int y1 = b[1] + ((fixedY + height) * b[3]) / 503;
+ return new int[] { x0, y0, x1 - x0, y1 - y0 };
+ }
+
+ // 3D Viewport: (4, 4) in fixed mode -> (0, 0) edge-to-edge in modern mode
+ if (fixedX == 4 && fixedY == 4) {
+ return new int[] { 0, 0 };
+ }
+
+ // Minimap and top-right stone border pieces:
+ // Handled cleanly via modern minimap composite in desktop overlays; suppress raw legacy pieces
+ if (fixedX >= 516 && fixedY < 160) {
+ return null;
+ }
+
+ // Chatbox outer stone borders and raw producers:
+ // backVmidIP2_2 top border (fixedX = 0, fixedY = 338)
+ // backLeftIP2 left border (fixedX = 0, fixedY = 357)
+ // backVmidIP3 right border (fixedX = 496, fixedY = 357)
+ // Parchment 1166 (fixedX = 17, fixedY = 357)
+ // Buttons 1123 (fixedX = 0, fixedY = 453)
+ // All handled cleanly via modern chat composite in DesktopHooks.drawModernChat
+ if (fixedX == 0 && fixedY == 338) {
+ return null;
+ }
+ if ((fixedX == 0 || fixedX == 496 || fixedX == 17) && fixedY == 357) {
+ return null;
+ }
+ if (fixedX == 0 && fixedY == 453) {
+ return null;
+ }
+
+ // Tab block elements:
+ // top bar 1125 (516, 160), left pillar backVmidIP2 (516, 205),
+ // tab body 1163 (553, 205), right pillar backRightIP2 (743, 205),
+ // bottom bar 1124 (496, 466)
+ // All handled cleanly via unified modern tab composite in DesktopHooks.drawModernTab
+ if (fixedX >= 496 && fixedY >= 160) {
+ return null;
+ }
+
+ // Fixed outer frame borders that should not be drawn in modern layout
+ return null;
+ }
+}
diff --git a/2006Scape Client/src/main/java/NpcID.java b/2006Scape Client/src/main/java/NpcID.java
new file mode 100644
index 00000000..824af39e
--- /dev/null
+++ b/2006Scape Client/src/main/java/NpcID.java
@@ -0,0 +1,6 @@
+/**
+ * NPC ID constants for the 2006Scape Client Plugin & Script API.
+ * Inherits all NPC constants from StaticNpcList.
+ */
+public class NpcID extends StaticNpcList {
+}
diff --git a/2006Scape Client/src/main/java/ObjectID.java b/2006Scape Client/src/main/java/ObjectID.java
new file mode 100644
index 00000000..9b475512
--- /dev/null
+++ b/2006Scape Client/src/main/java/ObjectID.java
@@ -0,0 +1,6 @@
+/**
+ * Object ID constants for the 2006Scape Client Plugin & Script API.
+ * Inherits all scene object constants from StaticObjectList.
+ */
+public class ObjectID extends StaticObjectList {
+}
diff --git a/2006Scape Client/src/main/java/ObjectManager.java b/2006Scape Client/src/main/java/ObjectManager.java
index 25895efa..255b17d0 100644
--- a/2006Scape Client/src/main/java/ObjectManager.java
+++ b/2006Scape Client/src/main/java/ObjectManager.java
@@ -2,7 +2,7 @@
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
-final class ObjectManager {
+public final class ObjectManager {
public ObjectManager(byte abyte0[][][], int ai[][][]) {
anInt145 = 99;
@@ -146,7 +146,10 @@ final class ObjectManager {
k15 -= anIntArray127[k18];
k16 -= anIntArray128[k18];
}
- if (k17 >= 1 && k17 < anInt147 - 1 && ((!hideBuggyVarrockSwordShopSnow && !hideRoofs && !lowMem) || (aByteArrayArrayArray149[0][l6][k17] & 2) != 0 || (aByteArrayArrayArray149[l][l6][k17] & 0x10) == 0 && method182(k17, l, l6) == anInt131)) {
+ boolean roofGate = ClientSettings.ANDROID
+ ? (!hideRoofs && !lowMem)
+ : (!hideBuggyVarrockSwordShopSnow && !hideRoofs && !lowMem);
+ if (k17 >= 1 && k17 < anInt147 - 1 && (roofGate || (aByteArrayArrayArray149[0][l6][k17] & 2) != 0 || (aByteArrayArrayArray149[l][l6][k17] & 0x10) == 0 && method182(k17, l, l6) == anInt131)) {
if (l < anInt145) {
anInt145 = l;
}
@@ -1337,23 +1340,23 @@ final class ObjectManager {
private final int[] anIntArray126;
private final int[] anIntArray127;
private final int[] anIntArray128;
- private final int[][][] anIntArrayArrayArray129;
- private final byte[][][] aByteArrayArrayArray130;
+ public final int[][][] anIntArrayArrayArray129;
+ public final byte[][][] aByteArrayArrayArray130;
static int anInt131;
private static int anInt133 = (int) (Math.random() * 33D) - 16;
- private final byte[][][] aByteArrayArrayArray134;
- private final int[][][] anIntArrayArrayArray135;
- private final byte[][][] aByteArrayArrayArray136;
+ public final byte[][][] aByteArrayArrayArray134;
+ public final int[][][] anIntArrayArrayArray135;
+ public final byte[][][] aByteArrayArrayArray136;
private static final int anIntArray137[] = {1, 0, -1, 0};
- private final int[][] anIntArrayArray139;
+ public final int[][] anIntArrayArray139;
private static final int anIntArray140[] = {16, 32, 64, 128};
- private final byte[][][] aByteArrayArrayArray142;
+ public final byte[][][] aByteArrayArrayArray142;
private static final int anIntArray144[] = {0, -1, 0, 1};
static int anInt145 = 99;
private final int anInt146;
private final int anInt147;
- private final byte[][][] aByteArrayArrayArray148;
- private final byte[][][] aByteArrayArrayArray149;
+ public final byte[][][] aByteArrayArrayArray148;
+ public final byte[][][] aByteArrayArrayArray149;
static boolean lowMem = true;
static boolean hideRoofs = ClientSettings.HIDE_ROOFS;
diff --git a/2006Scape Client/src/main/java/PluginConfigItem.java b/2006Scape Client/src/main/java/PluginConfigItem.java
new file mode 100644
index 00000000..bbe9be6f
--- /dev/null
+++ b/2006Scape Client/src/main/java/PluginConfigItem.java
@@ -0,0 +1,102 @@
+import java.util.Arrays;
+
+/**
+ * Defines a metadata item for configuring a plugin or script.
+ */
+public class PluginConfigItem {
+
+ public enum Type {
+ BOOLEAN,
+ INTEGER,
+ STRING,
+ CHOICE
+ }
+
+ private final String key;
+ private final String label;
+ private final String description;
+ private final Type type;
+ private final Object defaultValue;
+ private final String[] choices;
+ private final int minValue;
+ private final int maxValue;
+ private String visibleWhen;
+
+ public PluginConfigItem(String key, String label, String description, boolean defaultValue) {
+ this(key, label, description, Type.BOOLEAN, defaultValue, null, 0, 0);
+ }
+
+ public PluginConfigItem(String key, String label, String description, int defaultValue, int minValue, int maxValue) {
+ this(key, label, description, Type.INTEGER, defaultValue, null, minValue, maxValue);
+ }
+
+ public PluginConfigItem(String key, String label, String description, String defaultValue) {
+ this(key, label, description, Type.STRING, defaultValue, null, 0, 0);
+ }
+
+ public PluginConfigItem(String key, String label, String description, String defaultValue, String[] choices) {
+ this(key, label, description, Type.CHOICE, defaultValue, choices, 0, 0);
+ }
+
+ public PluginConfigItem(String key, String label, String description, Type type, Object defaultValue, String[] choices, int minValue, int maxValue) {
+ this.key = key;
+ this.label = label;
+ this.description = description;
+ this.type = type;
+ this.defaultValue = defaultValue;
+ this.choices = choices;
+ this.minValue = minValue;
+ this.maxValue = maxValue;
+ }
+
+ public String getKey() {
+ return key;
+ }
+
+ public String getLabel() {
+ return label;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public Type getType() {
+ return type;
+ }
+
+ public Object getDefaultValue() {
+ return defaultValue;
+ }
+
+ public String[] getChoices() {
+ return choices != null ? choices.clone() : new String[0];
+ }
+
+ public int getMinValue() {
+ return minValue;
+ }
+
+ public int getMaxValue() {
+ return maxValue;
+ }
+
+ public PluginConfigItem setVisibleWhen(String key) {
+ this.visibleWhen = key;
+ return this;
+ }
+
+ public String getVisibleWhen() {
+ return visibleWhen;
+ }
+
+ @Override
+ public String toString() {
+ return "PluginConfigItem{" +
+ "key='" + key + '\'' +
+ ", label='" + label + '\'' +
+ ", type=" + type +
+ ", default=" + defaultValue +
+ '}';
+ }
+}
diff --git a/2006Scape Client/src/main/java/PluginContext.java b/2006Scape Client/src/main/java/PluginContext.java
new file mode 100644
index 00000000..596395a2
--- /dev/null
+++ b/2006Scape Client/src/main/java/PluginContext.java
@@ -0,0 +1,2891 @@
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.function.Predicate;
+
+/**
+ * High-level game API facade for plugins and scripts.
+ */
+public class PluginContext {
+
+ private final Game game;
+
+ public PluginContext(Game game) {
+ this.game = game;
+ }
+
+ public Game getGame() {
+ return game;
+ }
+
+ // =========================================================================
+ // Player State Queries
+ // =========================================================================
+
+ public boolean isLoggedIn() {
+ return game != null && game.loggedIn && game.myPlayer != null;
+ }
+
+ public int getPlane() {
+ return game.plane;
+ }
+
+ public int getBaseX() {
+ return game.baseX;
+ }
+
+ public int getBaseY() {
+ return game.baseY;
+ }
+
+ public int getPlayerX() {
+ return game.myPlayer != null ? (game.myPlayer.x >> 7) + game.baseX : 0;
+ }
+
+ public int getPlayerY() {
+ return game.myPlayer != null ? (game.myPlayer.y >> 7) + game.baseY : 0;
+ }
+
+ public int getPlayerLocalX() {
+ return game.myPlayer != null ? (game.myPlayer.x >> 7) : 0;
+ }
+
+ public int getPlayerLocalY() {
+ return game.myPlayer != null ? (game.myPlayer.y >> 7) : 0;
+ }
+
+ public String getPlayerName() {
+ return game.myPlayer != null ? game.myPlayer.name : "";
+ }
+
+ public int getPlayerAnim() {
+ return game.myPlayer != null ? game.myPlayer.anim : -1;
+ }
+
+ public int getPlayerCombatLevel() {
+ return game.myPlayer != null ? game.myPlayer.combatLevel : 3;
+ }
+
+ public int getPlayerInteractingIndex() {
+ return game.myPlayer != null ? game.myPlayer.interactingEntity : -1;
+ }
+
+ public boolean isPlayerMoving() {
+ return game.myPlayer != null && (game.myPlayer.anInt1517 != -1 && game.myPlayer.anInt1517 != game.myPlayer.anInt1511);
+ }
+
+ public boolean isPlayerInCombat() {
+ if (game.myPlayer == null) return false;
+ NpcWrapper interactingNpc = getPlayerInteractingNpc();
+ if (interactingNpc != null && !interactingNpc.isDead() && interactingNpc.combatLevel > 0) {
+ return true;
+ }
+ NpcWrapper attacker = getNpcAttackingPlayer();
+ if (attacker != null && !attacker.isDead()) {
+ return true;
+ }
+ return false;
+ }
+
+ public NpcWrapper getPlayerInteractingNpc() {
+ if (game.myPlayer == null) return null;
+ int idx = game.myPlayer.interactingEntity;
+ if (idx >= 0 && idx < 32768 && idx < game.npcArray.length) {
+ NPC npc = game.npcArray[idx];
+ if (npc != null && npc.desc != null && npc.isVisible()) {
+ return new NpcWrapper(idx, npc, game.baseX, game.baseY, getPlayerX(), getPlayerY(), game.unknownInt10, game.myPlayerIndex);
+ }
+ }
+ return null;
+ }
+
+ public NpcWrapper getNpcAttackingPlayer() {
+ if (game.myPlayer == null) return null;
+ for (int i = 0; i < game.npcCount; i++) {
+ int idx = game.npcIndices[i];
+ NPC npc = game.npcArray[idx];
+ if (npc != null && npc.desc != null && npc.isVisible()) {
+ NpcWrapper wrapper = new NpcWrapper(idx, npc, game.baseX, game.baseY, getPlayerX(), getPlayerY(), game.unknownInt10, game.myPlayerIndex);
+ if (wrapper.isAttackingPlayer && !wrapper.isDead()) {
+ return wrapper;
+ }
+ }
+ }
+ return null;
+ }
+
+ public boolean isPlayerIdle() {
+ if (game.myPlayer == null) return false;
+ return game.myPlayer.anim == -1 && !isPlayerMoving() && !isPlayerInCombat();
+ }
+
+ public int getSkillLevel(int skillId) {
+ if (skillId >= 0 && skillId < game.currentExp.length) {
+ return game.currentStats[skillId];
+ }
+ return 1;
+ }
+
+ public int getSkillMaxLevel(int skillId) {
+ if (skillId >= 0 && skillId < game.maxStats.length) {
+ return game.maxStats[skillId];
+ }
+ return 1;
+ }
+
+ public int getSkillXp(int skillId) {
+ if (skillId >= 0 && skillId < game.currentExp.length) {
+ return game.currentExp[skillId];
+ }
+ return 0;
+ }
+
+ public int getEnergy() {
+ return game.energy;
+ }
+
+ public int getPlayerHp() {
+ return isLoggedIn() ? getSkillLevel(SkillID.HITPOINTS) : 0;
+ }
+
+ public int getPlayerMaxHp() {
+ return isLoggedIn() ? getSkillMaxLevel(SkillID.HITPOINTS) : 1;
+ }
+
+ public int getPlayerHpPercent() {
+ if (!isLoggedIn()) return 100;
+ int max = getPlayerMaxHp();
+ if (max <= 0) return 100;
+ return Math.max(0, Math.min(100, (getPlayerHp() * 100) / max));
+ }
+
+ public InventoryItemWrapper findFood() {
+ if (!isLoggedIn()) return null;
+ InventoryItemWrapper edible = inventory().hasAction("Eat").first();
+ if (edible != null) return edible;
+ return inventory()
+ .named("meat", "shrimp", "trout", "salmon", "tuna", "lobster",
+ "swordfish", "shark", "monkfish", "bread", "cake", "pie",
+ "stew", "anchovies", "sardine", "herring", "pike", "bass", "karambwan")
+ .first();
+ }
+
+ public boolean eatAnyFood() {
+ InventoryItemWrapper food = findFood();
+ return food != null && interactInventoryItem(food.slot, "Eat");
+ }
+
+ public boolean emergencyTeleport(Spell teleportSpell, int minHpPercent) {
+ if (!isLoggedIn() || teleportSpell == null) return false;
+ if (getPlayerHpPercent() <= minHpPercent) {
+ return castSpell(teleportSpell);
+ }
+ return false;
+ }
+
+ public int distanceTo(int worldX, int worldY) {
+ int dx = getPlayerX() - worldX;
+ int dy = getPlayerY() - worldY;
+ return (int) Math.sqrt(dx * dx + dy * dy);
+ }
+
+ public boolean isRunEnabled() {
+ return game.variousSettings != null && 173 < game.variousSettings.length && game.variousSettings[173] == 1;
+ }
+
+ public boolean setRunEnabled(boolean enabled) {
+ if (!isLoggedIn()) return false;
+ if (isRunEnabled() == enabled) return true;
+ if (enabled && getEnergy() <= 0) return false;
+ invokeMenuAction("Toggle Run", 315, 0, 0, 19136);
+ return true;
+ }
+
+ public boolean ensureRunEnabled(int minEnergy) {
+ if (!isRunEnabled() && getEnergy() >= minEnergy) {
+ return setRunEnabled(true);
+ }
+ return false;
+ }
+
+ public boolean isInArea(int minX, int minY, int maxX, int maxY) {
+ int px = getPlayerX();
+ int py = getPlayerY();
+ return px >= minX && px <= maxX && py >= minY && py <= maxY;
+ }
+
+ public boolean isInArea(WorldArea area) {
+ return area != null && area.contains(getPlayerX(), getPlayerY(), getPlane());
+ }
+
+ public boolean isAt(int worldX, int worldY, int radius) {
+ return distanceTo(worldX, worldY) <= Math.max(0, radius);
+ }
+
+ public static final class WorldArea {
+ public final int minX;
+ public final int minY;
+ public final int maxX;
+ public final int maxY;
+ public final int plane;
+
+ public WorldArea(int x1, int y1, int x2, int y2) {
+ this(x1, y1, x2, y2, 0);
+ }
+
+ public WorldArea(int x1, int y1, int x2, int y2, int plane) {
+ this.minX = Math.min(x1, x2);
+ this.minY = Math.min(y1, y2);
+ this.maxX = Math.max(x1, x2);
+ this.maxY = Math.max(y1, y2);
+ this.plane = plane;
+ }
+
+ public boolean contains(int worldX, int worldY) {
+ return worldX >= minX && worldX <= maxX && worldY >= minY && worldY <= maxY;
+ }
+
+ public boolean contains(int worldX, int worldY, int worldPlane) {
+ return plane == worldPlane && contains(worldX, worldY);
+ }
+
+ public int centerX() {
+ return (minX + maxX) / 2;
+ }
+
+ public int centerY() {
+ return (minY + maxY) / 2;
+ }
+ }
+
+ // =========================================================================
+ // Entity Wrappers
+ // =========================================================================
+
+ public static class NpcWrapper {
+ public final int index;
+ public final int id;
+ public final String name;
+ public final int combatLevel;
+ public final int worldX;
+ public final int worldY;
+ public final int localX;
+ public final int localY;
+ public final int anim;
+ public final int interactingEntity;
+ public final int currentHealth;
+ public final int maxHealth;
+ public final String[] actions;
+ public final boolean isAttackingPlayer;
+ private final int playerDist;
+
+ public NpcWrapper(int index, NPC npc, int baseX, int baseY, int px, int py, int myPlayerId, int myPlayerIdx) {
+ this.index = index;
+ this.id = npc.desc != null ? (int) npc.desc.type : -1;
+ this.name = npc.desc != null && npc.desc.name != null ? MenuEntry.stripColorTags(npc.desc.name) : "";
+ this.combatLevel = npc.desc != null ? npc.desc.combatLevel : 0;
+ this.localX = npc.x >> 7;
+ this.localY = npc.y >> 7;
+ this.worldX = localX + baseX;
+ this.worldY = localY + baseY;
+ this.anim = npc.anim;
+ this.interactingEntity = npc.interactingEntity;
+ this.currentHealth = npc.currentHealth;
+ this.maxHealth = npc.maxHealth;
+ this.actions = npc.desc != null && npc.desc.actions != null ? npc.desc.actions.clone() : new String[0];
+ int dx = worldX - px;
+ int dy = worldY - py;
+ this.playerDist = (int) Math.sqrt(dx * dx + dy * dy);
+
+ int target = (interactingEntity >= 32768) ? (interactingEntity - 32768) : interactingEntity;
+ this.isAttackingPlayer = (interactingEntity != -1) && (target == myPlayerId || target == myPlayerIdx);
+ }
+
+ public int getDistance() {
+ return playerDist;
+ }
+
+ public boolean isUnderAttack() {
+ return interactingEntity != -1;
+ }
+
+ public boolean isUnderAttackByOther() {
+ return interactingEntity != -1 && !isAttackingPlayer;
+ }
+
+ public boolean isDead() {
+ if (maxHealth > 0 && currentHealth <= 0) return true;
+ if (anim == 5389 || anim == 57 || anim == 58) return true; // Chicken, Rooster, and Cow death emotes
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return name + " (lvl-" + combatLevel + ") @ (" + worldX + ", " + worldY + ") dist=" + playerDist;
+ }
+ }
+
+ public static class PlayerWrapper {
+ public final int index;
+ public final String name;
+ public final int combatLevel;
+ public final int worldX;
+ public final int worldY;
+ public final int localX;
+ public final int localY;
+ public final int anim;
+ public final int interactingEntity;
+ public final int currentHealth;
+ public final int maxHealth;
+ public final int skullIcon;
+ public final int headIcon;
+ public final int team;
+ public final boolean isLocalPlayer;
+ private final int playerDist;
+
+ public PlayerWrapper(int index, Player p, int baseX, int baseY, int px, int py, boolean isLocalPlayer) {
+ this.index = index;
+ this.name = p.name != null ? MenuEntry.stripColorTags(p.name) : "";
+ this.combatLevel = p.combatLevel;
+ this.localX = (p.smallX != null && p.smallX.length > 0) ? p.smallX[0] : 0;
+ this.localY = (p.smallY != null && p.smallY.length > 0) ? p.smallY[0] : 0;
+ this.worldX = this.localX + baseX;
+ this.worldY = this.localY + baseY;
+ this.anim = p.anim;
+ this.interactingEntity = p.interactingEntity;
+ this.currentHealth = p.currentHealth;
+ this.maxHealth = p.maxHealth;
+ this.skullIcon = p.skullIcon;
+ this.headIcon = p.headIcon;
+ this.team = p.team;
+ this.isLocalPlayer = isLocalPlayer;
+ this.playerDist = Math.max(Math.abs(px - worldX), Math.abs(py - worldY));
+ }
+
+ public int getDistance() {
+ return playerDist;
+ }
+
+ public boolean isInCombat() {
+ return interactingEntity != -1;
+ }
+
+ @Override
+ public String toString() {
+ return name + " (lvl-" + combatLevel + ") @ (" + worldX + ", " + worldY + ") dist=" + playerDist;
+ }
+ }
+
+ public static class GroundItemWrapper {
+ public final int id;
+ public final String name;
+ public final int amount;
+ public final int value;
+ public final long totalValue;
+ public final int worldX;
+ public final int worldY;
+ public final int localX;
+ public final int localY;
+ public final int plane;
+ private final int playerDist;
+
+ public GroundItemWrapper(Item item, int lx, int ly, int plane, int baseX, int baseY, int px, int py) {
+ this(item.ID, item.amount, lx + baseX, ly + baseY, plane, baseX, baseY, px, py);
+ }
+
+ public GroundItemWrapper(int itemId, int amount, int worldX, int worldY, int plane, int baseX, int baseY, int px, int py) {
+ this.id = itemId;
+ ItemDef def = null;
+ try {
+ def = ItemDef.forID(itemId);
+ } catch (Throwable ignored) {}
+ this.name = def != null && def.name != null ? MenuEntry.stripColorTags(def.name) : "Item " + itemId;
+ this.amount = amount;
+ this.value = def != null ? Math.max(1, def.value) : 1;
+ this.totalValue = (long) this.value * Math.max(1, amount);
+ this.worldX = worldX;
+ this.worldY = worldY;
+ this.localX = worldX - baseX;
+ this.localY = worldY - baseY;
+ this.plane = plane;
+ int dx = worldX - px;
+ int dy = worldY - py;
+ this.playerDist = (int) Math.sqrt(dx * dx + dy * dy);
+ }
+
+ public int getDistance() {
+ return playerDist;
+ }
+
+ @Override
+ public String toString() {
+ return name + " x" + amount + " @ (" + worldX + ", " + worldY + ") dist=" + playerDist;
+ }
+ }
+
+ public static class SceneObjectWrapper {
+ public final int uid;
+ public final int id;
+ public final String name;
+ public final int worldX;
+ public final int worldY;
+ public final int localX;
+ public final int localY;
+ public final int plane;
+ public final int category; // 1: Wall/Door, 2: WallDeco, 3: GroundDeco, 5: Interactive
+ public final String[] actions;
+ private final int playerDist;
+
+ public SceneObjectWrapper(int uid, int lx, int ly, int plane, int category, int baseX, int baseY, int px, int py) {
+ this.uid = uid;
+ this.id = uid >> 14 & 0x7fff;
+ int anchorLx = uid & 0x7f;
+ int anchorLy = (uid >> 7) & 0x7f;
+ this.localX = anchorLx;
+ this.localY = anchorLy;
+ this.worldX = anchorLx + baseX;
+ this.worldY = anchorLy + baseY;
+ this.plane = plane;
+ this.category = category;
+
+ ObjectDef def = null;
+ try {
+ def = ObjectDef.forID(this.id);
+ if (def != null && def.childrenIDs != null) {
+ ObjectDef morphed = def.method580();
+ if (morphed != null) {
+ def = morphed;
+ }
+ }
+ } catch (Throwable ignored) {}
+ this.name = def != null && def.name != null ? MenuEntry.stripColorTags(def.name) : "Object " + this.id;
+ this.actions = def != null && def.actions != null ? def.actions.clone() : new String[0];
+
+ int dx = worldX - px;
+ int dy = worldY - py;
+ this.playerDist = (int) Math.sqrt(dx * dx + dy * dy);
+ }
+
+ public int getDistance() {
+ return playerDist;
+ }
+
+ @Override
+ public String toString() {
+ return name + " [id=" + id + "] @ (" + worldX + ", " + worldY + ") dist=" + playerDist;
+ }
+ }
+
+ public static class InventoryItemWrapper {
+ public final int slot;
+ public final int id;
+ public final String name;
+ public final int amount;
+ public final String[] actions;
+
+ public InventoryItemWrapper(int slot, int rawId, int amount) {
+ this.slot = slot;
+ this.id = rawId - 1;
+ this.amount = amount;
+ ItemDef def = null;
+ try {
+ def = ItemDef.forID(this.id);
+ } catch (Throwable ignored) {}
+ this.name = def != null && def.name != null ? MenuEntry.stripColorTags(def.name) : "";
+ this.actions = def != null && def.actions != null ? def.actions.clone() : new String[0];
+ }
+
+ public InventoryItemWrapper(int slot, int id, String name, int amount, String[] actions) {
+ this.slot = slot;
+ this.id = id;
+ this.name = name != null ? name : "";
+ this.amount = amount;
+ this.actions = actions != null ? actions.clone() : new String[0];
+ }
+
+ @Override
+ public String toString() {
+ return name + " [slot=" + slot + ", amount=" + amount + "]";
+ }
+ }
+
+ // =========================================================================
+ // Entity Finders
+ // =========================================================================
+
+ public List getNpcs() {
+ if (!isLoggedIn()) return Collections.emptyList();
+ List list = new ArrayList<>();
+ int px = getPlayerX();
+ int py = getPlayerY();
+ for (int i = 0; i < game.npcCount; i++) {
+ int idx = game.npcIndices[i];
+ NPC npc = game.npcArray[idx];
+ if (npc != null && npc.isVisible()) {
+ list.add(new NpcWrapper(idx, npc, game.baseX, game.baseY, px, py, game.unknownInt10, game.myPlayerIndex));
+ }
+ }
+ list.sort(Comparator.comparingInt(NpcWrapper::getDistance));
+ return list;
+ }
+
+ public NpcWrapper getNpcByIndex(int index) {
+ if (!isLoggedIn() || index < 0 || index >= game.npcArray.length) return null;
+ NPC npc = game.npcArray[index];
+ if (npc == null || npc.desc == null || !npc.isVisible()) return null;
+ return new NpcWrapper(index, npc, game.baseX, game.baseY, getPlayerX(), getPlayerY(), game.unknownInt10, game.myPlayerIndex);
+ }
+
+ public NpcWrapper findNearestNpc(String... names) {
+ List npcs = getNpcs();
+ for (NpcWrapper npc : npcs) {
+ for (String n : names) {
+ if (npc.name.equalsIgnoreCase(n) || npc.name.toLowerCase().contains(n.toLowerCase())) {
+ return npc;
+ }
+ }
+ }
+ return null;
+ }
+
+ public NpcWrapper findNearestNpcById(int... ids) {
+ List npcs = getNpcs();
+ for (NpcWrapper npc : npcs) {
+ for (int id : ids) {
+ if (npc.id == id) {
+ return npc;
+ }
+ }
+ }
+ return null;
+ }
+
+ public NpcWrapper findNearestAttackableNpc(String... names) {
+ List npcs = getNpcs();
+ for (NpcWrapper npc : npcs) {
+ if (npc.isDead()) continue;
+ // Skip NPCs in combat with someone else
+ if (npc.isUnderAttackByOther()) {
+ continue;
+ }
+ for (String n : names) {
+ if (npc.name.equalsIgnoreCase(n) || npc.name.toLowerCase().contains(n.toLowerCase())) {
+ return npc;
+ }
+ }
+ }
+ return null;
+ }
+
+ public List getGroundItems() {
+ if (!isLoggedIn()) return Collections.emptyList();
+ List list = new ArrayList<>();
+ int p = game.plane;
+ int px = getPlayerX();
+ int py = getPlayerY();
+
+ for (int x = 0; x < 104; x++) {
+ for (int y = 0; y < 104; y++) {
+ NodeList nodeList = game.groundArray[p][x][y];
+ if (nodeList != null) {
+ for (Item item = (Item) nodeList.getFirst(); item != null; item = (Item) nodeList.getNext()) {
+ list.add(new GroundItemWrapper(item, x, y, p, game.baseX, game.baseY, px, py));
+ }
+ }
+ }
+ }
+ list.sort(Comparator.comparingInt(GroundItemWrapper::getDistance));
+ return list;
+ }
+
+ public GroundItemWrapper findNearestGroundItem(String... names) {
+ List items = getGroundItems();
+ for (GroundItemWrapper item : items) {
+ for (String n : names) {
+ if (item.name.equalsIgnoreCase(n) || item.name.toLowerCase().contains(n.toLowerCase())) {
+ return item;
+ }
+ }
+ }
+ return null;
+ }
+
+ public GroundItemWrapper findNearestGroundItemById(int... ids) {
+ List items = getGroundItems();
+ for (GroundItemWrapper item : items) {
+ for (int id : ids) {
+ if (item.id == id) {
+ return item;
+ }
+ }
+ }
+ return null;
+ }
+
+ public List getSceneObjects(int radius) {
+ if (!isLoggedIn() || game.worldController == null) return Collections.emptyList();
+ List list = new ArrayList<>();
+ int p = game.plane;
+ int plx = getPlayerLocalX();
+ int ply = getPlayerLocalY();
+ int px = getPlayerX();
+ int py = getPlayerY();
+
+ int minX = Math.max(0, plx - radius);
+ int maxX = Math.min(103, plx + radius);
+ int minY = Math.max(0, ply - radius);
+ int maxY = Math.min(103, ply + radius);
+
+ Ground[][][] grounds = game.worldController.groundArray;
+ if (grounds == null) return Collections.emptyList();
+ java.util.Set seenUids = new java.util.HashSet<>();
+
+ for (int x = minX; x <= maxX; x++) {
+ for (int y = minY; y <= maxY; y++) {
+ Ground g = grounds[p][x][y];
+ if (g == null) continue;
+
+ // Wall / Doors
+ if (g.obj1 != null && g.obj1.uid > 0 && seenUids.add(g.obj1.uid)) {
+ list.add(new SceneObjectWrapper(g.obj1.uid, x, y, p, 1, game.baseX, game.baseY, px, py));
+ }
+ // Wall Decor
+ if (g.obj2 != null && g.obj2.uid > 0 && seenUids.add(g.obj2.uid)) {
+ list.add(new SceneObjectWrapper(g.obj2.uid, x, y, p, 2, game.baseX, game.baseY, px, py));
+ }
+ // Ground Decor
+ if (g.obj3 != null && g.obj3.uid > 0 && seenUids.add(g.obj3.uid)) {
+ list.add(new SceneObjectWrapper(g.obj3.uid, x, y, p, 3, game.baseX, game.baseY, px, py));
+ }
+ // Interactive Scene Objects (obj5Array)
+ for (int o = 0; o < g.anInt1317; o++) {
+ Object5 obj5 = g.obj5Array[o];
+ if (obj5 != null && obj5.uid > 0 && seenUids.add(obj5.uid)) {
+ list.add(new SceneObjectWrapper(obj5.uid, x, y, p, 5, game.baseX, game.baseY, px, py));
+ }
+ }
+ }
+ }
+ list.sort(Comparator.comparingInt(SceneObjectWrapper::getDistance));
+ return list;
+ }
+
+ public SceneObjectWrapper findNearestObject(String... names) {
+ List objs = getSceneObjects(25);
+ for (SceneObjectWrapper obj : objs) {
+ for (String n : names) {
+ if (obj.name.equalsIgnoreCase(n) || obj.name.toLowerCase().contains(n.toLowerCase())) {
+ return obj;
+ }
+ }
+ }
+ return null;
+ }
+
+ public SceneObjectWrapper findNearestObjectWithAction(String action, String... names) {
+ if (action == null) return null;
+ List objs = getSceneObjects(25);
+ for (SceneObjectWrapper obj : objs) {
+ if (!hasAction(obj, action)) continue;
+ for (String n : names) {
+ if (obj.name.equalsIgnoreCase(n) || obj.name.toLowerCase().contains(n.toLowerCase())) {
+ return obj;
+ }
+ }
+ }
+ return null;
+ }
+
+ public boolean hasAction(SceneObjectWrapper obj, String action) {
+ if (obj == null || obj.actions == null || action == null) return false;
+ for (String act : obj.actions) {
+ if (act != null && act.trim().equalsIgnoreCase(action.trim())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean isTollGate(SceneObjectWrapper obj) {
+ if (obj == null || obj.actions == null) return false;
+ for (String act : obj.actions) {
+ if (act != null && act.toLowerCase().contains("pay-toll")) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public static boolean isOpenGateOrDoor(SceneObjectWrapper obj) {
+ if (obj == null) return false;
+ int id = obj.id;
+ // Known open gate IDs in Revision 377 / 2006Scape GateHandler
+ if (id == StaticObjectList.GATE_1552 || id == StaticObjectList.GATE_1556 || id == StaticObjectList.GATE_1560
+ || id == StaticObjectList.GATE_1561 || id == StaticObjectList.GATE_7051 || id == StaticObjectList.GATE_7052
+ || id == StaticObjectList.GATE_12988 || id == StaticObjectList.GATE_12989 || id == StaticObjectList.GATE_3727
+ || id == StaticObjectList.GATE_3728 || id == StaticObjectList.GATE_8812 || id == StaticObjectList.GATE_8813) {
+ return true;
+ }
+ if (obj.actions != null) {
+ for (String act : obj.actions) {
+ if (act != null && "Close".equalsIgnoreCase(act.trim())) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Checks if any gate within maxDistance is currently open.
+ */
+ public boolean isAnyGateOpenNearby(int maxDistance) {
+ List objs = getSceneObjects(maxDistance);
+ for (SceneObjectWrapper obj : objs) {
+ if (obj.name != null && obj.name.toLowerCase().contains("gate") && isOpenGateOrDoor(obj)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Checks if any gate or door within maxDistance is currently open.
+ */
+ public boolean isAnyGateOrDoorOpenNearby(int maxDistance) {
+ List objs = getSceneObjects(maxDistance);
+ for (SceneObjectWrapper obj : objs) {
+ if (obj.name != null && (obj.name.toLowerCase().contains("gate") || obj.name.toLowerCase().contains("door")) && isOpenGateOrDoor(obj)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public SceneObjectWrapper findNearestObjectById(int... ids) {
+ List objs = getSceneObjects(25);
+ for (SceneObjectWrapper obj : objs) {
+ for (int id : ids) {
+ if (obj.id == id) {
+ return obj;
+ }
+ }
+ }
+ return null;
+ }
+
+ // =========================================================================
+ // Collision, Line-of-Sight & Reachability API
+ // =========================================================================
+
+ public static final int MASK_BLOCK_NORTH = 0x1280120;
+ public static final int MASK_BLOCK_EAST = 0x1280180;
+ public static final int MASK_BLOCK_SOUTH = 0x1280102;
+ public static final int MASK_BLOCK_WEST = 0x1280108;
+
+ public static final int MASK_BLOCK_NORTH_WEST = 0x1280138;
+ public static final int MASK_BLOCK_NORTH_EAST = 0x12801e0;
+ public static final int MASK_BLOCK_SOUTH_WEST = 0x128010e;
+ public static final int MASK_BLOCK_SOUTH_EAST = 0x1280183;
+
+ public int getClipping(int worldX, int worldY) {
+ if (!isLoggedIn() || game == null || game.aClass11Array1230 == null) return 0xffffff;
+ int p = game.plane;
+ if (p < 0 || p >= game.aClass11Array1230.length || game.aClass11Array1230[p] == null) return 0xffffff;
+ int lx = worldX - game.baseX;
+ int ly = worldY - game.baseY;
+ if (lx < 0 || lx >= 104 || ly < 0 || ly >= 104) return 0xffffff;
+ int[][] flags = game.aClass11Array1230[p].anIntArrayArray294;
+ if (flags == null) return 0xffffff;
+ return flags[lx][ly];
+ }
+
+ public boolean isTileWalkable(int worldX, int worldY) {
+ int clip = getClipping(worldX, worldY);
+ return (clip & 0x1280100) == 0;
+ }
+
+ public boolean canStep(int fromX, int fromY, int toX, int toY) {
+ int dx = toX - fromX;
+ int dy = toY - fromY;
+ if (dx == 0 && dy == 0) return true;
+ if (Math.abs(dx) > 1 || Math.abs(dy) > 1) return false;
+
+ int fromClip = getClipping(fromX, fromY);
+ int toClip = getClipping(toX, toY);
+
+ // Destination tile must not be solid blocked
+ if ((toClip & 0x1280100) != 0) {
+ return false;
+ }
+
+ if (dx == 0 && dy == 1) { // North
+ return (fromClip & 2) == 0 && (toClip & MASK_BLOCK_NORTH) == 0;
+ } else if (dx == 0 && dy == -1) { // South
+ return (fromClip & 0x20) == 0 && (toClip & MASK_BLOCK_SOUTH) == 0;
+ } else if (dx == 1 && dy == 0) { // East
+ return (fromClip & 8) == 0 && (toClip & MASK_BLOCK_EAST) == 0;
+ } else if (dx == -1 && dy == 0) { // West
+ return (fromClip & 0x80) == 0 && (toClip & MASK_BLOCK_WEST) == 0;
+ } else if (dx == 1 && dy == 1) { // North-East
+ return canStep(fromX, fromY, fromX + 1, fromY)
+ && canStep(fromX, fromY, fromX, fromY + 1)
+ && (toClip & MASK_BLOCK_NORTH_EAST) == 0;
+ } else if (dx == -1 && dy == 1) { // North-West
+ return canStep(fromX, fromY, fromX - 1, fromY)
+ && canStep(fromX, fromY, fromX, fromY + 1)
+ && (toClip & MASK_BLOCK_NORTH_WEST) == 0;
+ } else if (dx == 1 && dy == -1) { // South-East
+ return canStep(fromX, fromY, fromX + 1, fromY)
+ && canStep(fromX, fromY, fromX, fromY - 1)
+ && (toClip & MASK_BLOCK_SOUTH_EAST) == 0;
+ } else if (dx == -1 && dy == -1) { // South-West
+ return canStep(fromX, fromY, fromX - 1, fromY)
+ && canStep(fromX, fromY, fromX, fromY - 1)
+ && (toClip & MASK_BLOCK_SOUTH_WEST) == 0;
+ }
+ return false;
+ }
+
+ public boolean canMeleeReach(int px, int py, int npcX, int npcY, int npcSize) {
+ if (px >= npcX && px <= npcX + npcSize - 1 && py >= npcY && py <= npcY + npcSize - 1) {
+ return false; // Standing on top of NPC
+ }
+ int pClip = getClipping(px, py);
+ int nClip = getClipping(npcX, npcY);
+
+ // West
+ if (px == npcX - 1 && py >= npcY && py <= npcY + npcSize - 1) {
+ return (pClip & 8) == 0 && (nClip & 0x80) == 0;
+ }
+ // East
+ if (px == npcX + npcSize && py >= npcY && py <= npcY + npcSize - 1) {
+ return (pClip & 0x80) == 0 && (nClip & 8) == 0;
+ }
+ // South
+ if (py == npcY - 1 && px >= npcX && px <= npcX + npcSize - 1) {
+ return (pClip & 2) == 0 && (nClip & 0x20) == 0;
+ }
+ // North
+ if (py == npcY + npcSize && px >= npcX && px <= npcX + npcSize - 1) {
+ return (pClip & 0x20) == 0 && (nClip & 2) == 0;
+ }
+ return false;
+ }
+
+ public boolean hasLineOfSight(int startX, int startY, int endX, int endY) {
+ if (startX == endX && startY == endY) return true;
+ int dx = Math.abs(endX - startX);
+ int dy = Math.abs(endY - startY);
+ int sx = startX < endX ? 1 : -1;
+ int sy = startY < endY ? 1 : -1;
+ int err = dx - dy;
+
+ int curX = startX;
+ int curY = startY;
+
+ while (curX != endX || curY != endY) {
+ int e2 = 2 * err;
+ int nextX = curX;
+ int nextY = curY;
+
+ if (e2 > -dy) {
+ err -= dy;
+ nextX += sx;
+ }
+ if (e2 < dx) {
+ err += dx;
+ nextY += sy;
+ }
+
+ if (!canStep(curX, curY, nextX, nextY)) {
+ if (nextX == endX && nextY == endY) {
+ return true;
+ }
+ return false;
+ }
+ curX = nextX;
+ curY = nextY;
+ }
+ return true;
+ }
+
+ public boolean hasLineOfSight(NpcWrapper npc) {
+ if (npc == null || !isLoggedIn()) return false;
+ return hasLineOfSight(getPlayerX(), getPlayerY(), npc.worldX, npc.worldY);
+ }
+
+ public boolean hasLineOfSight(GroundItemWrapper item) {
+ if (item == null || !isLoggedIn()) return false;
+ return hasLineOfSight(getPlayerX(), getPlayerY(), item.worldX, item.worldY);
+ }
+
+ public boolean canReach(int targetWorldX, int targetWorldY, int maxDistance, boolean isNpc, int npcSize) {
+ if (!isLoggedIn()) return false;
+ int px = getPlayerX();
+ int py = getPlayerY();
+ if (px == targetWorldX && py == targetWorldY) return true;
+ int dist = distanceTo(targetWorldX, targetWorldY);
+ if (dist > maxDistance) return false;
+
+ if (isNpc && dist <= 1) {
+ if (canMeleeReach(px, py, targetWorldX, targetWorldY, npcSize)) {
+ return true;
+ }
+ } else if (!isNpc && dist <= 1 && canStep(px, py, targetWorldX, targetWorldY)) {
+ return true;
+ }
+
+ int startLx = getPlayerLocalX();
+ int startLy = getPlayerLocalY();
+ int targetLx = targetWorldX - game.baseX;
+ int targetLy = targetWorldY - game.baseY;
+
+ if (startLx < 0 || startLx >= 104 || startLy < 0 || startLy >= 104) return false;
+ if (targetLx < 0 || targetLx >= 104 || targetLy < 0 || targetLy >= 104) return false;
+
+ int rad = Math.min(52, maxDistance);
+ int minX = Math.max(0, startLx - rad);
+ int maxX = Math.min(103, startLx + rad);
+ int minY = Math.max(0, startLy - rad);
+ int maxY = Math.min(103, startLy + rad);
+
+ boolean[][] visited = new boolean[104][104];
+ int[] queueX = new int[104 * 104];
+ int[] queueY = new int[104 * 104];
+ int head = 0;
+ int tail = 0;
+
+ queueX[tail] = startLx;
+ queueY[tail] = startLy;
+ tail = (tail + 1) % queueX.length;
+ visited[startLx][startLy] = true;
+
+ int iterations = 0;
+ int[][] directions = {
+ {0, 1}, {0, -1}, {1, 0}, {-1, 0},
+ {1, 1}, {-1, 1}, {1, -1}, {-1, -1}
+ };
+
+ int maxIterations = Math.max(6000, (rad * 2 + 1) * (rad * 2 + 1));
+ while (head != tail && iterations++ < maxIterations) {
+ int cx = queueX[head];
+ int cy = queueY[head];
+ head = (head + 1) % queueX.length;
+
+ int cWorldX = cx + game.baseX;
+ int cWorldY = cy + game.baseY;
+
+ if (isNpc) {
+ if (canMeleeReach(cWorldX, cWorldY, targetWorldX, targetWorldY, npcSize)) {
+ return true;
+ }
+ } else {
+ if (cx == targetLx && cy == targetLy) {
+ return true;
+ }
+ }
+
+ for (int[] d : directions) {
+ int nx = cx + d[0];
+ int ny = cy + d[1];
+ if (nx < minX || nx > maxX || ny < minY || ny > maxY) continue;
+ if (visited[nx][ny]) continue;
+
+ if (canStep(cWorldX, cWorldY, nx + game.baseX, ny + game.baseY)) {
+ visited[nx][ny] = true;
+ queueX[tail] = nx;
+ queueY[tail] = ny;
+ tail = (tail + 1) % queueX.length;
+ if (tail == head) {
+ break;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ public boolean canReach(int targetWorldX, int targetWorldY, int maxDistance, boolean isNpc) {
+ return canReach(targetWorldX, targetWorldY, maxDistance, isNpc, 1);
+ }
+
+ public boolean canReach(int targetWorldX, int targetWorldY) {
+ return canReach(targetWorldX, targetWorldY, 20, false, 1);
+ }
+
+ public boolean canReach(NpcWrapper npc) {
+ if (npc == null || !isLoggedIn()) return false;
+ return canReach(npc.worldX, npc.worldY, 20, true, 1);
+ }
+
+ public boolean canReach(GroundItemWrapper item) {
+ if (item == null || !isLoggedIn()) return false;
+ return canReach(item.worldX, item.worldY, 20, false, 1);
+ }
+
+ public boolean canReach(SceneObjectWrapper obj) {
+ if (obj == null || !isLoggedIn()) return false;
+ return canReach(obj.worldX, obj.worldY, 20, true, 1);
+ }
+
+ /**
+ * Generates a human-like Gaussian random delay between minMs and maxMs.
+ */
+ public int randomDelay(int minMs, int maxMs) {
+ if (minMs >= maxMs) return minMs;
+ double r = (Math.random() + Math.random() + Math.random()) / 3.0;
+ return (int) (minMs + r * (maxMs - minMs));
+ }
+
+ // =========================================================================
+ // Inventory Queries
+ // =========================================================================
+
+ public List getInventoryItems() {
+ if (!isLoggedIn()) return Collections.emptyList();
+ // Inventory interface ID in 317 is typically 3214
+ RSInterface invInterface = RSInterface.interfaceCache[3214];
+ if (invInterface == null || invInterface.inv == null) {
+ return Collections.emptyList();
+ }
+ List list = new ArrayList<>();
+ for (int i = 0; i < invInterface.inv.length && i < 28; i++) {
+ if (invInterface.inv[i] > 0) {
+ int amount = (invInterface.invStackSizes != null && i < invInterface.invStackSizes.length)
+ ? invInterface.invStackSizes[i] : 1;
+ list.add(new InventoryItemWrapper(i, invInterface.inv[i], amount));
+ }
+ }
+ return list;
+ }
+
+ public int getInventoryCount() {
+ return getInventoryItems().size();
+ }
+
+ public int getEmptySlots() {
+ return 28 - getInventoryCount();
+ }
+
+ public boolean isInventoryFull() {
+ return getInventoryCount() >= 28;
+ }
+
+ public boolean hasInventoryItem(int id) {
+ for (InventoryItemWrapper item : getInventoryItems()) {
+ if (item.id == id) return true;
+ }
+ return false;
+ }
+
+ public boolean hasInventoryItem(String name) {
+ for (InventoryItemWrapper item : getInventoryItems()) {
+ if (item.name.equalsIgnoreCase(name) || item.name.toLowerCase().contains(name.toLowerCase())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public int getInventoryItemCount(int id) {
+ int count = 0;
+ for (InventoryItemWrapper item : getInventoryItems()) {
+ if (item.id == id) {
+ count += item.amount;
+ }
+ }
+ return count;
+ }
+
+ // =========================================================================
+ // Actions & Interaction Dispatch
+ // =========================================================================
+
+ /**
+ * Walks to a target world coordinate safely via client pathfinder.
+ */
+ public boolean walkTo(int worldX, int worldY) {
+ if (!isLoggedIn()) return false;
+ int destLx = worldX - game.baseX;
+ int destLy = worldY - game.baseY;
+ if (destLx < 0 || destLx >= 104 || destLy < 0 || destLy >= 104) {
+ return false;
+ }
+ if (!suppressWalkToPathUpdate) {
+ List preview = findPath(worldX, worldY, 20, true, false);
+ if (preview.isEmpty()) {
+ lastComputedPath = Collections.singletonList(new int[] { worldX, worldY });
+ }
+ }
+ int myLx = getPlayerLocalX();
+ int myLy = getPlayerLocalY();
+ boolean ok = game.doWalkTo(0, 0, 0, 0, myLy, 0, 0, destLy, myLx, true, destLx);
+ ScriptLogger.logActiveAction("walkTo(" + worldX + ", " + worldY + ") -> " + ok);
+ return ok;
+ }
+
+ /**
+ * Interacts with an NPC using a specified action (e.g. "Attack", "Talk-to", "Pickpocket").
+ */
+ public boolean interactNpc(NpcWrapper npc, String action) {
+ if (npc == null || !isLoggedIn()) return false;
+ int actionId;
+ if ("Attack".equalsIgnoreCase(action)) {
+ actionId = 412; // Hardcoded in 317 Game.java for Attack NPC (packet 72)
+ } else if ("Examine".equalsIgnoreCase(action)) {
+ actionId = 1025;
+ } else {
+ int optIndex = -1;
+ for (int i = 0; i < npc.actions.length; i++) {
+ if (npc.actions[i] != null && npc.actions[i].equalsIgnoreCase(action)) {
+ optIndex = i;
+ break;
+ }
+ }
+ if (optIndex == -1) {
+ return false;
+ }
+ switch (optIndex) {
+ case 0: actionId = 20; break; // First click / Talk-to (packet 155)
+ case 1: actionId = 225; break; // Second click (packet 17)
+ case 2: actionId = 965; break; // Third click (packet 21)
+ case 3: actionId = 478; break; // Fourth click (packet 18)
+ default: actionId = 20; break;
+ }
+ }
+ invokeMenuAction(action + " " + npc.name, actionId, npc.index, npc.localX, npc.localY);
+ return true;
+ }
+
+ /**
+ * Loots a ground item.
+ */
+ public boolean takeGroundItem(GroundItemWrapper item) {
+ if (item == null || !isLoggedIn()) return false;
+ invokeMenuAction("Take " + item.name, 234, item.id, item.localX, item.localY);
+ return true;
+ }
+
+ /**
+ * Interacts with a scene object (e.g. "Open" door, "Climb-up" ladder, "Bank" booth).
+ */
+ public boolean interactObject(SceneObjectWrapper obj, String action) {
+ if (obj == null || !isLoggedIn() || action == null) return false;
+ int optIndex = -1;
+ for (int i = 0; i < obj.actions.length; i++) {
+ if (obj.actions[i] != null && obj.actions[i].equalsIgnoreCase(action)) {
+ optIndex = i;
+ break;
+ }
+ }
+ if (optIndex == -1) {
+ return false;
+ }
+ int actionId;
+ switch (optIndex) {
+ case 0: actionId = 502; break;
+ case 1: actionId = 900; break;
+ case 2: actionId = 113; break;
+ case 3: actionId = 872; break;
+ case 4: actionId = 1062; break;
+ default: actionId = 502; break;
+ }
+ invokeMenuAction(action + " " + obj.name, actionId, obj.uid, obj.uid & 0x7f, (obj.uid >> 7) & 0x7f);
+ return true;
+ }
+
+ /**
+ * Interacts with an inventory item (e.g. "Bury", "Eat", "Drop").
+ */
+ public boolean interactInventoryItem(int slot, String action) {
+ if (!isLoggedIn() || slot < 0 || slot >= 28) return false;
+ RSInterface invInterface = RSInterface.interfaceCache[3214];
+ if (invInterface == null || invInterface.inv == null || slot >= invInterface.inv.length) return false;
+ int rawId = invInterface.inv[slot];
+ if (rawId <= 0) return false;
+ int itemId = rawId - 1;
+
+ if (action.equalsIgnoreCase("Drop")) {
+ invokeMenuAction("Drop", 847, itemId, slot, 3214);
+ return true;
+ } else if (action.equalsIgnoreCase("Bury") || action.equalsIgnoreCase("Eat") || action.equalsIgnoreCase("Wear") || action.equalsIgnoreCase("Wield")) {
+ invokeMenuAction(action, 74, itemId, slot, 3214);
+ return true;
+ } else {
+ invokeMenuAction(action, 493, itemId, slot, 3214);
+ return true;
+ }
+ }
+
+ public boolean dropInventoryItem(int slot) {
+ return interactInventoryItem(slot, "Drop");
+ }
+
+ public boolean buryInventoryItem(int slot) {
+ return interactInventoryItem(slot, "Bury");
+ }
+
+ /**
+ * Uses one inventory item on another inventory item (e.g. tinderbox on logs, chisel on gem).
+ */
+ public boolean useItemOnItem(int slotA, int slotB) {
+ if (!isLoggedIn() || slotA < 0 || slotA >= 28 || slotB < 0 || slotB >= 28 || slotA == slotB) {
+ return false;
+ }
+ RSInterface invInterface = RSInterface.interfaceCache[3214];
+ if (invInterface == null || invInterface.inv == null) return false;
+ int rawA = invInterface.inv[slotA];
+ int rawB = invInterface.inv[slotB];
+ if (rawA <= 0 || rawB <= 0) return false;
+ invokeMenuAction("Use", 447, rawA - 1, slotA, 3214);
+ invokeMenuAction("Use", 870, rawB - 1, slotB, 3214);
+ return true;
+ }
+
+ /**
+ * Uses an inventory item on a scene object (e.g. raw food on range/fire, ore on furnace, bones on altar).
+ */
+ public boolean useItemOnObject(int slot, SceneObjectWrapper obj) {
+ if (!isLoggedIn() || obj == null || slot < 0 || slot >= 28) return false;
+ RSInterface invInterface = RSInterface.interfaceCache[3214];
+ if (invInterface == null || invInterface.inv == null) return false;
+ int rawId = invInterface.inv[slot];
+ if (rawId <= 0) return false;
+ invokeMenuAction("Use", 447, rawId - 1, slot, 3214);
+ invokeMenuAction("Use", 62, obj.uid, obj.localX, obj.localY);
+ return true;
+ }
+
+ // =========================================================================
+ // Equipment, Combat Style, Special Attack, Prayer & Magic API
+ // =========================================================================
+
+ public static final int EQUIPMENT_INTERFACE_ID = 1688;
+
+ public List getEquipment() {
+ if (!isLoggedIn()) return Collections.emptyList();
+ RSInterface equip = RSInterface.interfaceCache[EQUIPMENT_INTERFACE_ID];
+ if (equip == null || equip.inv == null) {
+ return Collections.emptyList();
+ }
+ List list = new ArrayList<>();
+ for (int i = 0; i < equip.inv.length; i++) {
+ if (equip.inv[i] > 0) {
+ int amount = (equip.invStackSizes != null && i < equip.invStackSizes.length)
+ ? equip.invStackSizes[i] : 1;
+ list.add(new InventoryItemWrapper(i, equip.inv[i], amount));
+ }
+ }
+ return list;
+ }
+
+ public boolean isWearing(int id) {
+ for (InventoryItemWrapper item : getEquipment()) {
+ if (item.id == id) return true;
+ }
+ return false;
+ }
+
+ public boolean isWearing(String... names) {
+ for (InventoryItemWrapper item : getEquipment()) {
+ if (matchesName(item.name, names)) return true;
+ }
+ return false;
+ }
+
+ public boolean equipItem(int invSlot) {
+ return interactInventoryItem(invSlot, "Wear")
+ || interactInventoryItem(invSlot, "Wield")
+ || interactInventoryItem(invSlot, "Equip");
+ }
+
+ public boolean unequipItem(int equipSlot) {
+ if (!isLoggedIn() || equipSlot < 0) return false;
+ RSInterface equip = RSInterface.interfaceCache[EQUIPMENT_INTERFACE_ID];
+ if (equip == null || equip.inv == null || equipSlot >= equip.inv.length) return false;
+ int rawId = equip.inv[equipSlot];
+ if (rawId <= 0) return false;
+ invokeMenuAction("Remove", 632, rawId - 1, equipSlot, EQUIPMENT_INTERFACE_ID);
+ return true;
+ }
+
+ public int getAttackStyle() {
+ return (game.variousSettings != null && 43 < game.variousSettings.length)
+ ? game.variousSettings[43] : -1;
+ }
+
+ private void collectWidgetsByType(RSInterface parent, int widgetType, List out) {
+ if (parent == null || parent.children == null) return;
+ for (int childId : parent.children) {
+ if (childId < 0 || childId >= RSInterface.interfaceCache.length) continue;
+ RSInterface child = RSInterface.interfaceCache[childId];
+ if (child == null) continue;
+ if (child.type == widgetType) {
+ out.add(child);
+ }
+ if (child.children != null) {
+ collectWidgetsByType(child, widgetType, out);
+ }
+ }
+ }
+
+ private RSInterface findSpecialBarTextWidget() {
+ if (!isLoggedIn()) return null;
+ int tabId = (game.tabInterfaceIDs != null && game.tabInterfaceIDs.length > 0) ? game.tabInterfaceIDs[0] : -1;
+ if (tabId <= 0 || tabId >= RSInterface.interfaceCache.length) return null;
+ RSInterface tabRoot = RSInterface.interfaceCache[tabId];
+ List labels = new ArrayList<>();
+ collectWidgetsByType(tabRoot, 4, labels);
+ for (RSInterface lbl : labels) {
+ if (lbl.disabledText == null) continue;
+ String txt = MenuEntry.stripColorTags(lbl.disabledText).toLowerCase();
+ if (txt.contains("special") || txt.contains("s p")) {
+ return lbl;
+ }
+ }
+ return null;
+ }
+
+ /** Returns special attack energy from 0 to 100. */
+ public int getSpecialEnergy() {
+ if (game.variousSettings != null && 300 < game.variousSettings.length && game.variousSettings[300] > 0) {
+ return Math.max(0, Math.min(100, game.variousSettings[300] / 10));
+ }
+ RSInterface bar = findSpecialBarTextWidget();
+ if (bar != null) {
+ int filled = 0;
+ for (int i = 1; i <= 10; i++) {
+ int segId = bar.id - i;
+ if (segId >= 0 && segId < RSInterface.interfaceCache.length
+ && RSInterface.interfaceCache[segId] != null
+ && RSInterface.interfaceCache[segId].anInt263 != 0) {
+ filled++;
+ }
+ }
+ return filled * 10;
+ }
+ return 0;
+ }
+
+ public boolean isSpecialAttackActive() {
+ if (game.variousSettings != null && 301 < game.variousSettings.length && game.variousSettings[301] == 1) {
+ return true;
+ }
+ RSInterface bar = findSpecialBarTextWidget();
+ return bar != null && bar.disabledText != null && bar.disabledText.contains("@yel@");
+ }
+
+ public boolean toggleSpecialAttack() {
+ if (!isLoggedIn()) return false;
+ int tabId = (game.tabInterfaceIDs != null && game.tabInterfaceIDs.length > 0) ? game.tabInterfaceIDs[0] : -1;
+ if (tabId > 0 && tabId < RSInterface.interfaceCache.length) {
+ RSInterface tabRoot = RSInterface.interfaceCache[tabId];
+ int[] specButtonIds = {7462, 7487, 7537, 7562, 7587, 7612, 7637, 7662, 7687, 7712, 7737, 7812, 8481, 12311};
+ for (int id : specButtonIds) {
+ if (id < RSInterface.interfaceCache.length && RSInterface.interfaceCache[id] != null && containsChildId(tabRoot, id)) {
+ invokeMenuAction("Use Special Attack", 315, 0, 0, id);
+ return true;
+ }
+ }
+ List buttons = new ArrayList<>();
+ collectDialogChildren(tabRoot, 1, buttons);
+ collectDialogChildren(tabRoot, 5, buttons);
+ for (RSInterface btn : buttons) {
+ String tip = btn.tooltip != null ? MenuEntry.stripColorTags(btn.tooltip).toLowerCase() : "";
+ String txt = btn.disabledText != null ? MenuEntry.stripColorTags(btn.disabledText).toLowerCase() : "";
+ String enTxt = btn.enabledText != null ? MenuEntry.stripColorTags(btn.enabledText).toLowerCase() : "";
+ if (tip.contains("special") || txt.contains("special") || enTxt.contains("special") || hasAction(btn.actions, "Use")) {
+ invokeMenuAction("Use Special Attack", 315, 0, 0, btn.id);
+ return true;
+ }
+ }
+ }
+ ScriptLogger.logActiveAction("toggleSpecialAttack() -> false (tabId=" + tabId + ", energy=" + getSpecialEnergy() + ", active=" + isSpecialAttackActive() + ")");
+ return false;
+ }
+
+ private boolean containsChildId(RSInterface parent, int targetId) {
+ if (parent == null || parent.children == null) return false;
+ for (int childId : parent.children) {
+ if (childId == targetId) return true;
+ if (childId >= 0 && childId < RSInterface.interfaceCache.length
+ && containsChildId(RSInterface.interfaceCache[childId], targetId)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public boolean setSpecialAttack(boolean active) {
+ if (!isLoggedIn()) return false;
+ if (isSpecialAttackActive() == active) return true;
+ return toggleSpecialAttack();
+ }
+
+ public boolean setAttackStyle(int styleIndex) {
+ if (!isLoggedIn() || styleIndex < 0 || styleIndex > 3) return false;
+ int tabId = (game.tabInterfaceIDs != null && game.tabInterfaceIDs.length > 0) ? game.tabInterfaceIDs[0] : -1;
+ if (tabId <= 0 || tabId >= RSInterface.interfaceCache.length) return false;
+ List buttons = new ArrayList<>();
+ collectDialogChildren(RSInterface.interfaceCache[tabId], 1, buttons);
+ List styleButtons = new ArrayList<>();
+ for (RSInterface btn : buttons) {
+ String tip = btn.tooltip != null ? MenuEntry.stripColorTags(btn.tooltip).toLowerCase() : "";
+ if (tip.contains("special") || tip.contains("retaliate") || tip.contains("autocast")) continue;
+ styleButtons.add(btn);
+ }
+ if (styleIndex < styleButtons.size()) {
+ invokeMenuAction("Select", 315, 0, 0, styleButtons.get(styleIndex).id);
+ return true;
+ }
+ return false;
+ }
+
+ public enum Prayer {
+ THICK_SKIN(5609, 83),
+ BURST_OF_STRENGTH(5610, 84),
+ CLARITY_OF_THOUGHT(5611, 85),
+ SHARP_EYE(18000, 601),
+ MYSTIC_WILL(18002, 602),
+ ROCK_SKIN(5612, 86),
+ SUPERHUMAN_STRENGTH(5613, 87),
+ IMPROVED_REFLEXES(5614, 88),
+ RAPID_RESTORE(5615, 89),
+ RAPID_HEAL(5616, 90),
+ PROTECT_ITEM(5617, 91),
+ HAWK_EYE(18004, 603),
+ MYSTIC_LORE(18006, 604),
+ STEEL_SKIN(5618, 92),
+ ULTIMATE_STRENGTH(5619, 93),
+ INCREDIBLE_REFLEXES(5620, 94),
+ PROTECT_FROM_MAGIC(5621, 95),
+ PROTECT_FROM_MISSILES(5622, 96),
+ PROTECT_FROM_MELEE(5623, 97),
+ EAGLE_EYE(18008, 605),
+ MYSTIC_MIGHT(18010, 606),
+ RETRIBUTION(683, 98),
+ REDEMPTION(684, 99),
+ SMITE(685, 100),
+ CHIVALRY(18012, 607),
+ PIETY(18014, 608);
+
+ public final int widgetId;
+ public final int varpId;
+
+ Prayer(int widgetId, int varpId) {
+ this.widgetId = widgetId;
+ this.varpId = varpId;
+ }
+ }
+
+ public boolean isPrayerActive(Prayer prayer) {
+ if (prayer == null || game.variousSettings == null || prayer.varpId >= game.variousSettings.length) {
+ return false;
+ }
+ return game.variousSettings[prayer.varpId] == 1;
+ }
+
+ public boolean togglePrayer(Prayer prayer) {
+ if (prayer == null || !isLoggedIn()) return false;
+ invokeMenuAction("Activate", 315, 0, 0, prayer.widgetId);
+ return true;
+ }
+
+ public boolean setPrayer(Prayer prayer, boolean active) {
+ if (prayer == null || !isLoggedIn()) return false;
+ if (isPrayerActive(prayer) == active) return true;
+ return togglePrayer(prayer);
+ }
+
+ public enum Spell {
+ WIND_STRIKE(1152),
+ CONFUSE(1153),
+ WATER_STRIKE(1154),
+ EARTH_STRIKE(1156),
+ WEAKEN(1157),
+ FIRE_STRIKE(1158),
+ BONES_TO_BANANAS(1159),
+ WIND_BOLT(1160),
+ CURSE(1161),
+ LOW_LEVEL_ALCHEMY(1162),
+ WATER_BOLT(1163),
+ VARROCK_TELEPORT(1164),
+ EARTH_BOLT(1166),
+ LUMBRIDGE_TELEPORT(1167),
+ TELEKINETIC_GRAB(1168),
+ FIRE_BOLT(1169),
+ FALADOR_TELEPORT(1170),
+ CRUMBLE_UNDEAD(1171),
+ WIND_BLAST(1172),
+ SUPERHEAT_ITEM(1173),
+ CAMELOT_TELEPORT(1174),
+ WATER_BLAST(1175),
+ EARTH_BLAST(1177),
+ HIGH_LEVEL_ALCHEMY(1178),
+ FIRE_BLAST(1181),
+ WIND_WAVE(1183),
+ WATER_WAVE(1185),
+ EARTH_WAVE(1188),
+ FIRE_WAVE(1189),
+ IBAN_BLAST(1539),
+ ARDOUGNE_TELEPORT(1540),
+ WATCHTOWER_TELEPORT(1541),
+ BIND(1572),
+ SNARE(1582),
+ ENTANGLE(1592),
+ TROLLHEIM_TELEPORT(7455),
+ MAGIC_DART(12037),
+ APE_ATOLL_TELEPORT(18470);
+
+ public final int widgetId;
+
+ Spell(int widgetId) {
+ this.widgetId = widgetId;
+ }
+ }
+
+ public boolean castSpell(int spellWidgetId) {
+ return clickWidget(spellWidgetId);
+ }
+
+ public boolean castSpell(Spell spell) {
+ return spell != null && castSpell(spell.widgetId);
+ }
+
+ public boolean castSpellOnNpc(int spellWidgetId, NpcWrapper npc) {
+ if (!isLoggedIn() || npc == null || spellWidgetId < 0 || spellWidgetId >= RSInterface.interfaceCache.length) {
+ return false;
+ }
+ if (RSInterface.interfaceCache[spellWidgetId] == null) return false;
+ invokeMenuAction("Cast", 626, 0, 0, spellWidgetId);
+ invokeMenuAction("Cast", 413, npc.index, 0, 0);
+ return true;
+ }
+
+ public boolean castSpellOnNpc(Spell spell, NpcWrapper npc) {
+ return spell != null && castSpellOnNpc(spell.widgetId, npc);
+ }
+
+ public boolean castSpellOnItem(int spellWidgetId, int invSlot) {
+ if (!isLoggedIn() || invSlot < 0 || invSlot >= 28 || spellWidgetId < 0 || spellWidgetId >= RSInterface.interfaceCache.length) {
+ return false;
+ }
+ if (RSInterface.interfaceCache[spellWidgetId] == null) return false;
+ RSInterface invInterface = RSInterface.interfaceCache[3214];
+ if (invInterface == null || invInterface.inv == null) return false;
+ int rawId = invInterface.inv[invSlot];
+ if (rawId <= 0) return false;
+ invokeMenuAction("Cast", 626, 0, 0, spellWidgetId);
+ invokeMenuAction("Cast", 543, rawId - 1, invSlot, 3214);
+ return true;
+ }
+
+ public boolean castSpellOnItem(Spell spell, int invSlot) {
+ return spell != null && castSpellOnItem(spell.widgetId, invSlot);
+ }
+
+ /**
+ * Executes an authentic client menu action.
+ */
+ public void invokeMenuAction(String name, int actionId, int cmd1, int cmd2, int cmd3) {
+ if (!isLoggedIn()) return;
+ // Inject into the next available menu action slot or temporary row
+ int slot = game.menuActionRow;
+ if (slot >= 490) {
+ slot = 490;
+ }
+ game.menuActionName[slot] = name;
+ game.menuActionID[slot] = actionId;
+ game.menuActionCmd1[slot] = cmd1;
+ game.menuActionCmd2[slot] = cmd2;
+ game.menuActionCmd3[slot] = cmd3;
+ game.menuActionRow = slot + 1;
+ game.doAction(slot);
+ ScriptLogger.logActiveAction("menuAction('" + name + "', id=" + actionId + ", cmd1=" + cmd1 + ", cmd2=" + cmd2 + ", cmd3=" + cmd3 + ")");
+ }
+
+ // =========================================================================
+ // Menu Manipulation (For Swappers & Hooks)
+ // =========================================================================
+
+ public List getMenuEntries() {
+ int count = game.menuActionRow;
+ if (count <= 0) return new ArrayList<>();
+ List entries = new ArrayList<>(count);
+ for (int i = 0; i < count; i++) {
+ entries.add(new MenuEntry(
+ game.menuActionName[i],
+ game.menuActionID[i],
+ game.menuActionCmd1[i],
+ game.menuActionCmd2[i],
+ game.menuActionCmd3[i]
+ ));
+ }
+ return entries;
+ }
+
+ public void setMenuEntries(List entries) {
+ if (entries == null) return;
+ int count = Math.min(entries.size(), 495);
+ for (int i = 0; i < count; i++) {
+ MenuEntry e = entries.get(i);
+ game.menuActionName[i] = e.getRawText();
+ game.menuActionID[i] = e.getActionId();
+ game.menuActionCmd1[i] = e.getCmd1();
+ game.menuActionCmd2[i] = e.getCmd2();
+ game.menuActionCmd3[i] = e.getCmd3();
+ }
+ game.menuActionRow = count;
+ }
+
+ /**
+ * Moves a menu entry matching action and target pattern to the top (left-click position).
+ */
+ public boolean promoteMenuEntry(String actionPattern, String targetPattern) {
+ List entries = getMenuEntries();
+ if (entries.size() <= 1) return false;
+
+ int foundIdx = -1;
+ for (int i = 0; i < entries.size(); i++) {
+ MenuEntry e = entries.get(i);
+ if (e.matches(actionPattern, targetPattern)) {
+ foundIdx = i;
+ break;
+ }
+ }
+ if (foundIdx != -1 && foundIdx != entries.size() - 1) {
+ MenuEntry target = entries.remove(foundIdx);
+ entries.add(target); // Add to end (top priority)
+ setMenuEntries(entries);
+ return true;
+ }
+ return false;
+ }
+
+ // =========================================================================
+ // Utilities & Configuration
+ // =========================================================================
+
+ public void sendClientMessage(String msg) {
+ if (game != null && msg != null) {
+ game.pushMessage(msg, 0, "");
+ }
+ }
+
+ public void switchTab(int tabId) {
+ if (game != null) {
+ game.switchTab(tabId);
+ }
+ }
+
+ public int getOpenInterfaceId() {
+ return game.openInterfaceID;
+ }
+
+ public void closeInterfaces() {
+ if (game != null) {
+ game.closeOpenInterfaces();
+ }
+ }
+
+ // =========================================================================
+ // Fluent Entity & Inventory Query API
+ // =========================================================================
+
+ private static boolean matchesName(String actual, String... names) {
+ if (actual == null || names == null || names.length == 0) return false;
+ String lowerActual = actual.toLowerCase();
+ for (String n : names) {
+ if (n != null && (actual.equalsIgnoreCase(n) || lowerActual.contains(n.toLowerCase()))) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean matchesId(int actual, int... ids) {
+ if (ids == null) return false;
+ for (int id : ids) {
+ if (actual == id) return true;
+ }
+ return false;
+ }
+
+ public static boolean hasAction(String[] actions, String action) {
+ if (actions == null || action == null) return false;
+ String trimmed = action.trim();
+ for (String act : actions) {
+ if (act != null && act.trim().equalsIgnoreCase(trimmed)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Generic chainable query builder backed by a pre-sorted or raw entity list.
+ */
+ public static class Query> {
+ protected final List source;
+ protected Predicate predicate = item -> true;
+
+ public Query(List source) {
+ this.source = source != null ? source : Collections.emptyList();
+ }
+
+ @SuppressWarnings("unchecked")
+ protected final Q self() {
+ return (Q) this;
+ }
+
+ public Q filter(Predicate extra) {
+ if (extra != null) {
+ this.predicate = this.predicate.and(extra);
+ }
+ return self();
+ }
+
+ public List all() {
+ List results = new ArrayList<>();
+ for (T item : source) {
+ if (item != null && predicate.test(item)) {
+ results.add(item);
+ }
+ }
+ return results;
+ }
+
+ public T first() {
+ for (T item : source) {
+ if (item != null && predicate.test(item)) {
+ return item;
+ }
+ }
+ return null;
+ }
+
+ public T nearest() {
+ return first();
+ }
+
+ public int count() {
+ int c = 0;
+ for (T item : source) {
+ if (item != null && predicate.test(item)) {
+ c++;
+ }
+ }
+ return c;
+ }
+
+ public boolean exists() {
+ return first() != null;
+ }
+ }
+
+ public final class NpcQuery extends Query {
+ private NpcQuery(List source) {
+ super(source);
+ }
+
+ public NpcQuery named(String... names) {
+ return filter(npc -> matchesName(npc.name, names));
+ }
+
+ public NpcQuery id(int... ids) {
+ return filter(npc -> matchesId(npc.id, ids));
+ }
+
+ public NpcQuery within(int maxDistance) {
+ return filter(npc -> npc.getDistance() <= maxDistance);
+ }
+
+ public NpcQuery alive() {
+ return filter(npc -> !npc.isDead());
+ }
+
+ public NpcQuery attackable() {
+ return filter(npc -> !npc.isDead() && !npc.isUnderAttackByOther());
+ }
+
+ public NpcQuery hasAction(String action) {
+ return filter(npc -> PluginContext.hasAction(npc.actions, action));
+ }
+
+ public NpcQuery reachable() {
+ return filter(PluginContext.this::canReach);
+ }
+
+ public NpcQuery hasLineOfSight() {
+ return filter(PluginContext.this::hasLineOfSight);
+ }
+ }
+
+ public final class GroundItemQuery extends Query {
+ private GroundItemQuery(List source) {
+ super(source);
+ }
+
+ public GroundItemQuery named(String... names) {
+ return filter(item -> matchesName(item.name, names));
+ }
+
+ public GroundItemQuery id(int... ids) {
+ return filter(item -> matchesId(item.id, ids));
+ }
+
+ public GroundItemQuery within(int maxDistance) {
+ return filter(item -> item.getDistance() <= maxDistance);
+ }
+
+ public GroundItemQuery minValue(long minTotalValue) {
+ return filter(item -> item.totalValue >= minTotalValue);
+ }
+
+ public GroundItemQuery reachable() {
+ return filter(PluginContext.this::canReach);
+ }
+
+ public GroundItemQuery hasLineOfSight() {
+ return filter(PluginContext.this::hasLineOfSight);
+ }
+ }
+
+ public final class ObjectQuery extends Query {
+ private ObjectQuery(List source) {
+ super(source);
+ }
+
+ public ObjectQuery named(String... names) {
+ return filter(obj -> matchesName(obj.name, names));
+ }
+
+ public ObjectQuery id(int... ids) {
+ return filter(obj -> matchesId(obj.id, ids));
+ }
+
+ public ObjectQuery within(int maxDistance) {
+ return filter(obj -> obj.getDistance() <= maxDistance);
+ }
+
+ public ObjectQuery hasAction(String action) {
+ return filter(obj -> PluginContext.hasAction(obj.actions, action));
+ }
+
+ public ObjectQuery reachable() {
+ return filter(PluginContext.this::canReach);
+ }
+ }
+
+ public final class InventoryQuery extends Query {
+ private InventoryQuery(List source) {
+ super(source);
+ }
+
+ public InventoryQuery named(String... names) {
+ return filter(item -> matchesName(item.name, names));
+ }
+
+ public InventoryQuery id(int... ids) {
+ return filter(item -> matchesId(item.id, ids));
+ }
+
+ public InventoryQuery hasAction(String action) {
+ return filter(item -> PluginContext.hasAction(item.actions, action));
+ }
+ }
+
+ public NpcQuery npcs() {
+ return new NpcQuery(getNpcs());
+ }
+
+ public NpcQuery queryNpcs(List source) {
+ return new NpcQuery(source);
+ }
+
+ public GroundItemQuery groundItems() {
+ return new GroundItemQuery(getGroundItems());
+ }
+
+ public GroundItemQuery queryGroundItems(List source) {
+ return new GroundItemQuery(source);
+ }
+
+ public ObjectQuery objects() {
+ return new ObjectQuery(getSceneObjects(25));
+ }
+
+ public ObjectQuery objects(int radius) {
+ return new ObjectQuery(getSceneObjects(radius));
+ }
+
+ public ObjectQuery queryObjects(List source) {
+ return new ObjectQuery(source);
+ }
+
+ public InventoryQuery inventory() {
+ return new InventoryQuery(getInventoryItems());
+ }
+
+ public InventoryQuery queryInventory(List source) {
+ return new InventoryQuery(source);
+ }
+
+ public List getPlayers() {
+ return getPlayers(false);
+ }
+
+ public List getPlayers(boolean includeSelf) {
+ if (!isLoggedIn()) return Collections.emptyList();
+ List list = new ArrayList<>();
+ int baseX = game.baseX;
+ int baseY = game.baseY;
+ int px = getPlayerX();
+ int py = getPlayerY();
+ int count = Math.min(game.playerCount, game.playerIndices != null ? game.playerIndices.length : 0);
+ for (int i = 0; i < count; i++) {
+ int idx = game.playerIndices[i];
+ if (idx < 0 || game.playerArray == null || idx >= game.playerArray.length) continue;
+ Player p = game.playerArray[idx];
+ if (p == null) continue;
+ boolean isSelf = (idx == game.myPlayerIndex || p == game.myPlayer);
+ if (!includeSelf && isSelf) continue;
+ list.add(new PlayerWrapper(idx, p, baseX, baseY, px, py, isSelf));
+ }
+ list.sort(Comparator.comparingInt(PlayerWrapper::getDistance));
+ return list;
+ }
+
+ public final class PlayerQuery extends Query {
+ private PlayerQuery(List source) {
+ super(source);
+ }
+
+ public PlayerQuery named(String... names) {
+ return filter(p -> matchesName(p.name, names));
+ }
+
+ public PlayerQuery within(int maxDistance) {
+ return filter(p -> p.getDistance() <= maxDistance);
+ }
+
+ public PlayerQuery combatLevel(int minLevel, int maxLevel) {
+ return filter(p -> p.combatLevel >= minLevel && p.combatLevel <= maxLevel);
+ }
+
+ public PlayerQuery skulled() {
+ return filter(p -> p.skullIcon >= 0);
+ }
+
+ public PlayerQuery reachable() {
+ return filter(p -> canReach(p.worldX, p.worldY, 20, true));
+ }
+
+ public PlayerQuery hasLineOfSight() {
+ return filter(p -> PluginContext.this.hasLineOfSight(getPlayerX(), getPlayerY(), p.worldX, p.worldY));
+ }
+ }
+
+ public PlayerQuery players() {
+ return new PlayerQuery(getPlayers(false));
+ }
+
+ public PlayerQuery queryPlayers(List source) {
+ return new PlayerQuery(source);
+ }
+
+ public boolean isPlayerNearby(int maxDistance) {
+ return players().within(maxDistance).exists();
+ }
+
+ // =========================================================================
+ // Dialogue & Widget API
+ // =========================================================================
+
+ public int getActiveDialogId() {
+ if (!isLoggedIn()) return -1;
+ if (game.backDialogID != -1) return game.backDialogID;
+ return game.dialogID;
+ }
+
+ public boolean isDialogueOpen() {
+ return getActiveDialogId() != -1;
+ }
+
+ private void collectDialogChildren(RSInterface parent, int actionType, List out) {
+ if (parent == null || parent.children == null) return;
+ for (int childId : parent.children) {
+ if (childId < 0 || childId >= RSInterface.interfaceCache.length) continue;
+ RSInterface child = RSInterface.interfaceCache[childId];
+ if (child == null) continue;
+ if (child.atActionType == actionType) {
+ out.add(child);
+ }
+ if (child.children != null) {
+ collectDialogChildren(child, actionType, out);
+ }
+ }
+ }
+
+ private List getActiveDialogChildren(int actionType) {
+ int id = getActiveDialogId();
+ if (id < 0 || id >= RSInterface.interfaceCache.length) return Collections.emptyList();
+ List list = new ArrayList<>();
+ collectDialogChildren(RSInterface.interfaceCache[id], actionType, list);
+ return list;
+ }
+
+ public boolean canContinueDialogue() {
+ boolean res = !getActiveDialogChildren(6).isEmpty();
+ if (res) {
+ System.out.println("[PC] canContinueDialogue=true backDialogID=" + game.backDialogID + " dialogID=" + game.dialogID);
+ }
+ return res;
+ }
+
+ public boolean continueDialogue() {
+ if (!isLoggedIn() || game.aBoolean1149) return false;
+ List continues = getActiveDialogChildren(6);
+ if (continues.isEmpty()) return false;
+ invokeMenuAction("Continue", 679, 0, 0, continues.get(0).id);
+ return true;
+ }
+
+ public int getDialogueOptionCount() {
+ return getActiveDialogChildren(1).size();
+ }
+
+ public List getDialogueOptions() {
+ List options = getActiveDialogChildren(1);
+ List texts = new ArrayList<>(options.size());
+ for (RSInterface opt : options) {
+ texts.add(opt.disabledText != null ? MenuEntry.stripColorTags(opt.disabledText) : "");
+ }
+ return texts;
+ }
+
+ public boolean selectDialogueOption(int optionIndex) {
+ if (!isLoggedIn() || optionIndex < 0) return false;
+ List options = getActiveDialogChildren(1);
+ if (optionIndex >= options.size()) return false;
+ invokeMenuAction("Select", 315, 0, 0, options.get(optionIndex).id);
+ return true;
+ }
+
+ public boolean selectDialogueOption(String text) {
+ if (!isLoggedIn() || text == null || text.isEmpty()) return false;
+ String needle = text.toLowerCase();
+ List options = getActiveDialogChildren(1);
+ for (RSInterface opt : options) {
+ String optText = opt.disabledText != null ? MenuEntry.stripColorTags(opt.disabledText).toLowerCase() : "";
+ if (optText.contains(needle)) {
+ invokeMenuAction("Select", 315, 0, 0, opt.id);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public String getWidgetText(int widgetId) {
+ if (widgetId < 0 || widgetId >= RSInterface.interfaceCache.length) return "";
+ RSInterface widget = RSInterface.interfaceCache[widgetId];
+ return (widget != null && widget.disabledText != null) ? widget.disabledText : "";
+ }
+
+ public int getWidgetColor(int widgetId) {
+ if (widgetId < 0 || widgetId >= RSInterface.interfaceCache.length) return 0;
+ RSInterface widget = RSInterface.interfaceCache[widgetId];
+ return widget != null ? widget.textColor : 0;
+ }
+
+ public int getVarp(int varpId) {
+ if (game == null || game.variousSettings == null || varpId < 0 || varpId >= game.variousSettings.length) {
+ return 0;
+ }
+ return game.variousSettings[varpId];
+ }
+
+ public boolean clickWidget(int widgetId) {
+ if (!isLoggedIn() || widgetId < 0 || widgetId >= RSInterface.interfaceCache.length) return false;
+ if (RSInterface.interfaceCache[widgetId] == null) return false;
+ invokeMenuAction("Click", 315, 0, 0, widgetId);
+ return true;
+ }
+
+ // =========================================================================
+ // Banking & Container API
+ // =========================================================================
+
+ public static final int BANK_INTERFACE_ID = 5292;
+ public static final int BANK_INVENTORY_ID = 5064;
+ public static final int BANK_ITEMS_ID = 5382;
+
+ public boolean isBankOpen() {
+ return isLoggedIn() && game.openInterfaceID == BANK_INTERFACE_ID;
+ }
+
+ public boolean closeBank() {
+ if (!isBankOpen()) return false;
+ closeInterfaces();
+ return true;
+ }
+
+ public boolean openNearestBank() {
+ if (!isLoggedIn()) return false;
+ if (isBankOpen()) return true;
+ SceneObjectWrapper booth = objects(20)
+ .named("Bank booth", "Bank chest")
+ .filter(o -> hasAction(o, "Bank") || hasAction(o, "Use-quickly"))
+ .reachable()
+ .nearest();
+ if (booth == null) {
+ booth = objects(10)
+ .named("Bank booth", "Bank chest")
+ .filter(o -> hasAction(o, "Bank") || hasAction(o, "Use-quickly"))
+ .nearest();
+ }
+ if (booth != null) {
+ String act = hasAction(booth, "Bank") ? "Bank" : "Use-quickly";
+ return interactObject(booth, act);
+ }
+ NpcWrapper banker = npcs()
+ .named("Banker")
+ .hasAction("Bank")
+ .within(20)
+ .reachable()
+ .nearest();
+ return banker != null && interactNpc(banker, "Bank");
+ }
+
+ public List getBankItems() {
+ if (!isLoggedIn()) return Collections.emptyList();
+ RSInterface bankInterface = RSInterface.interfaceCache[BANK_ITEMS_ID];
+ if (bankInterface == null || bankInterface.inv == null) {
+ return Collections.emptyList();
+ }
+ List list = new ArrayList<>();
+ for (int i = 0; i < bankInterface.inv.length; i++) {
+ if (bankInterface.inv[i] > 0) {
+ int amt = (bankInterface.invStackSizes != null && i < bankInterface.invStackSizes.length)
+ ? bankInterface.invStackSizes[i] : 1;
+ list.add(new InventoryItemWrapper(i, bankInterface.inv[i], amt));
+ }
+ }
+ return list;
+ }
+
+ public boolean hasBankItem(int id) {
+ return getBankItemCount(id) > 0;
+ }
+
+ public int getBankItemCount(int id) {
+ int total = 0;
+ for (InventoryItemWrapper item : getBankItems()) {
+ if (item.id == id) {
+ total += Math.max(1, item.amount);
+ }
+ }
+ return total;
+ }
+
+ private boolean interactContainerItem(int containerId, int itemId, int amount, boolean isWithdraw) {
+ if (!isBankOpen() || containerId < 0 || containerId >= RSInterface.interfaceCache.length) return false;
+ RSInterface container = RSInterface.interfaceCache[containerId];
+ if (container == null || container.inv == null) return false;
+
+ int slot = -1;
+ int slotAmount = 0;
+ for (int i = 0; i < container.inv.length; i++) {
+ if (container.inv[i] - 1 == itemId) {
+ slot = i;
+ slotAmount = (container.invStackSizes != null && i < container.invStackSizes.length)
+ ? container.invStackSizes[i] : 1;
+ break;
+ }
+ }
+ if (slot == -1) return false;
+
+ if (amount <= 0 || amount >= Integer.MAX_VALUE || (amount != 1 && amount != 5 && amount != 10 && amount >= slotAmount)) {
+ invokeMenuAction(isWithdraw ? "Withdraw" : "Deposit", 431, itemId, slot, containerId);
+ return true;
+ }
+ if (amount == 1) {
+ invokeMenuAction(isWithdraw ? "Withdraw" : "Deposit", 632, itemId, slot, containerId);
+ return true;
+ }
+ if (amount == 5) {
+ invokeMenuAction(isWithdraw ? "Withdraw" : "Deposit", 78, itemId, slot, containerId);
+ return true;
+ }
+ if (amount == 10) {
+ invokeMenuAction(isWithdraw ? "Withdraw" : "Deposit", 867, itemId, slot, containerId);
+ return true;
+ }
+
+ // Exact custom amount (< slotAmount, not 1/5/10): use Withdraw-X / Deposit-X (action 53 -> packet 208)
+ if (isEnterAmountOpen()) {
+ return submitAmount(amount);
+ }
+ invokeMenuAction(isWithdraw ? "Withdraw X" : "Deposit X", 53, itemId, slot, containerId);
+ return true;
+ }
+
+ public boolean isEnterAmountOpen() {
+ return isLoggedIn() && game.inputDialogState == 1;
+ }
+
+ public boolean submitAmount(int amount) {
+ if (!isLoggedIn() || amount <= 0) return false;
+ game.stream.createFrame(208);
+ game.stream.writeDWord(amount);
+ game.inputDialogState = 0;
+ game.inputTaken = true;
+ if (ClientSettings.ANDROID) {
+ AndroidHooks.hideKeyboard();
+ }
+ return true;
+ }
+
+ public boolean setWithdrawAsNote(boolean noted) {
+ if (!isBankOpen()) return false;
+ invokeMenuAction(noted ? "Note" : "Item", 315, 0, 0, noted ? 5386 : 5387);
+ return true;
+ }
+
+ public boolean depositItem(int id, int amount) {
+ return interactContainerItem(BANK_INVENTORY_ID, id, amount, false);
+ }
+
+ public boolean depositAll() {
+ return depositAllExcept(new int[0]);
+ }
+
+ public boolean depositAllExcept(int... keepIds) {
+ if (!isBankOpen()) return false;
+ List deposited = new ArrayList<>();
+ boolean any = false;
+ for (InventoryItemWrapper item : getInventoryItems()) {
+ if (matchesId(item.id, keepIds) || deposited.contains(item.id)) continue;
+ if (depositItem(item.id, Integer.MAX_VALUE)) {
+ deposited.add(item.id);
+ any = true;
+ }
+ }
+ return any;
+ }
+
+ public boolean depositAllExcept(String... keepNames) {
+ if (!isBankOpen()) return false;
+ List deposited = new ArrayList<>();
+ boolean any = false;
+ for (InventoryItemWrapper item : getInventoryItems()) {
+ if (matchesName(item.name, keepNames) || deposited.contains(item.id)) continue;
+ if (depositItem(item.id, Integer.MAX_VALUE)) {
+ deposited.add(item.id);
+ any = true;
+ }
+ }
+ return any;
+ }
+
+ public boolean withdrawItem(int id, int amount) {
+ return interactContainerItem(BANK_ITEMS_ID, id, amount, true);
+ }
+
+ // =========================================================================
+ // Shop & Make-X Skilling API
+ // =========================================================================
+
+ public static final int SHOP_INTERFACE_ID = 3824;
+ public static final int SHOP_INVENTORY_ID = 3823;
+ public static final int SHOP_ITEMS_ID = 3900;
+
+ public boolean isShopOpen() {
+ return isLoggedIn() && game.openInterfaceID == SHOP_INTERFACE_ID;
+ }
+
+ public boolean closeShop() {
+ if (!isShopOpen()) return false;
+ closeInterfaces();
+ return true;
+ }
+
+ public List getShopItems() {
+ if (!isLoggedIn()) return Collections.emptyList();
+ RSInterface shopInterface = RSInterface.interfaceCache[SHOP_ITEMS_ID];
+ if (shopInterface == null || shopInterface.inv == null) {
+ return Collections.emptyList();
+ }
+ List list = new ArrayList<>();
+ for (int i = 0; i < shopInterface.inv.length; i++) {
+ if (shopInterface.inv[i] > 0) {
+ int amt = (shopInterface.invStackSizes != null && i < shopInterface.invStackSizes.length)
+ ? shopInterface.invStackSizes[i] : 1;
+ list.add(new InventoryItemWrapper(i, shopInterface.inv[i], amt));
+ }
+ }
+ return list;
+ }
+
+ public int getShopItemCount(int id) {
+ int total = 0;
+ for (InventoryItemWrapper item : getShopItems()) {
+ if (item.id == id) {
+ total += Math.max(0, item.amount);
+ }
+ }
+ return total;
+ }
+
+ private boolean interactShopContainer(int containerId, int itemId, int amount, boolean isBuy) {
+ if (!isShopOpen() || containerId < 0 || containerId >= RSInterface.interfaceCache.length) return false;
+ RSInterface container = RSInterface.interfaceCache[containerId];
+ if (container == null || container.inv == null) return false;
+
+ int slot = -1;
+ for (int i = 0; i < container.inv.length; i++) {
+ if (container.inv[i] - 1 == itemId) {
+ slot = i;
+ break;
+ }
+ }
+ if (slot == -1) return false;
+
+ String label = isBuy ? "Buy" : "Sell";
+ if (amount == 1) {
+ invokeMenuAction(label + " 1", 78, itemId, slot, containerId);
+ return true;
+ }
+ if (amount == 10) {
+ invokeMenuAction(label + " 10", 867, itemId, slot, containerId);
+ return true;
+ }
+ if (isEnterAmountOpen()) {
+ return submitAmount(amount);
+ }
+ invokeMenuAction(label + " X", 431, itemId, slot, containerId);
+ return true;
+ }
+
+ public boolean buyItem(int id, int amount) {
+ return interactShopContainer(SHOP_ITEMS_ID, id, amount, true);
+ }
+
+ public boolean sellItem(int id, int amount) {
+ return interactShopContainer(SHOP_INVENTORY_ID, id, amount, false);
+ }
+
+ /**
+ * Selects a quantity on the standard cooking Make-1/5/10/All dialogue (13720..13717).
+ */
+ public boolean makeCookingAmount(int amount) {
+ if (!isLoggedIn()) return false;
+ if (amount == 1) return clickWidget(13720);
+ if (amount == 5) return clickWidget(13719);
+ if (amount == 10) return clickWidget(13718);
+ return clickWidget(13717);
+ }
+
+ /**
+ * Clicks a skilling/dialogue child button whose text or tooltip contains the given text.
+ */
+ public boolean clickMakeOption(String text) {
+ if (!isLoggedIn() || text == null || text.isEmpty()) return false;
+ String needle = text.toLowerCase();
+ int[] parents = {getActiveDialogId(), game.openInterfaceID};
+ for (int parentId : parents) {
+ if (parentId < 0 || parentId >= RSInterface.interfaceCache.length) continue;
+ List children = new ArrayList<>();
+ collectDialogChildren(RSInterface.interfaceCache[parentId], 1, children);
+ collectDialogChildren(RSInterface.interfaceCache[parentId], 4, children);
+ collectDialogChildren(RSInterface.interfaceCache[parentId], 5, children);
+ for (RSInterface child : children) {
+ String label = child.disabledText != null ? MenuEntry.stripColorTags(child.disabledText).toLowerCase() : "";
+ String tip = child.tooltip != null ? MenuEntry.stripColorTags(child.tooltip).toLowerCase() : "";
+ if (label.contains(needle) || tip.contains(needle)) {
+ invokeMenuAction("Make", 315, 0, 0, child.id);
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ // =========================================================================
+ // Long-Distance Waypoint Path Walking
+ // =========================================================================
+
+ private int[][] lastWalkPathWaypoints;
+ private int lastWalkPathIndex;
+
+ /**
+ * Walks along a sequence of world-coordinate waypoints ({x, y}).
+ * @return true if a walk step was issued, false if already within arrivalRadius of the final waypoint.
+ */
+ public boolean walkPath(int arrivalRadius, int[]... waypoints) {
+ if (!isLoggedIn() || waypoints == null || waypoints.length == 0) return false;
+ int[] last = waypoints[waypoints.length - 1];
+ if (last == null || last.length < 2) return false;
+ if (distanceTo(last[0], last[1]) <= Math.max(0, arrivalRadius)) {
+ lastWalkPathWaypoints = null;
+ lastWalkPathIndex = 0;
+ return false;
+ }
+
+ if (waypoints != lastWalkPathWaypoints) {
+ lastWalkPathWaypoints = waypoints;
+ lastWalkPathIndex = 0;
+ } else if (lastWalkPathIndex >= waypoints.length
+ || waypoints[lastWalkPathIndex] == null
+ || waypoints[lastWalkPathIndex].length < 2
+ || distanceTo(waypoints[lastWalkPathIndex][0], waypoints[lastWalkPathIndex][1]) > 24) {
+ lastWalkPathIndex = 0;
+ }
+
+ // Find closest waypoint at or after lastWalkPathIndex so we never walk backwards
+ int closestIdx = lastWalkPathIndex;
+ int closestDist = Integer.MAX_VALUE;
+ for (int i = lastWalkPathIndex; i < waypoints.length; i++) {
+ int[] wp = waypoints[i];
+ if (wp == null || wp.length < 2) continue;
+ int dist = distanceTo(wp[0], wp[1]);
+ if (dist < closestDist) {
+ closestDist = dist;
+ closestIdx = i;
+ }
+ }
+
+ // Advance past closestIdx if we are already close to it
+ int minIdx = (closestDist <= 3 && closestIdx + 1 < waypoints.length) ? (closestIdx + 1) : closestIdx;
+ lastWalkPathIndex = Math.max(lastWalkPathIndex, minIdx);
+
+ // Pick the furthest reachable waypoint ahead within local pathing range (16 tiles)
+ for (int i = waypoints.length - 1; i >= lastWalkPathIndex; i--) {
+ int[] wp = waypoints[i];
+ if (wp == null || wp.length < 2) continue;
+ int dist = distanceTo(wp[0], wp[1]);
+ if (dist <= 16 && dist > 1 && canReach(wp[0], wp[1], 18, false)) {
+ updateWalkPathOverlay(waypoints, i);
+ suppressWalkToPathUpdate = true;
+ try {
+ return walkTo(wp[0], wp[1]);
+ } finally {
+ suppressWalkToPathUpdate = false;
+ }
+ }
+ }
+
+ // Fallback: pick furthest forward waypoint within 16 tiles, or next waypoint ahead
+ for (int i = waypoints.length - 1; i >= lastWalkPathIndex; i--) {
+ int[] wp = waypoints[i];
+ if (wp == null || wp.length < 2) continue;
+ int dist = distanceTo(wp[0], wp[1]);
+ if (dist <= 16 && dist > 1) {
+ updateWalkPathOverlay(waypoints, i);
+ suppressWalkToPathUpdate = true;
+ try {
+ return walkTo(wp[0], wp[1]);
+ } finally {
+ suppressWalkToPathUpdate = false;
+ }
+ }
+ }
+
+ int[] nextWp = waypoints[lastWalkPathIndex];
+ return nextWp != null && nextWp.length >= 2 && walkToSmart(nextWp[0], nextWp[1]);
+ }
+
+ private void updateWalkPathOverlay(int[][] waypoints, int startIdx) {
+ List path = new ArrayList<>();
+ if (startIdx >= 0 && startIdx < waypoints.length && waypoints[startIdx] != null && waypoints[startIdx].length >= 2) {
+ List local = findPath(waypoints[startIdx][0], waypoints[startIdx][1], 18, true, false);
+ path.addAll(local);
+ }
+ for (int i = Math.max(0, startIdx + (path.isEmpty() ? 0 : 1)); i < waypoints.length; i++) {
+ int[] wp = waypoints[i];
+ if (wp != null && wp.length >= 2) {
+ path.add(new int[] { wp[0], wp[1] });
+ }
+ }
+ lastComputedPath = path.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(path);
+ }
+
+ public WorldArea createArea(int x1, int y1, int x2, int y2) {
+ return new WorldArea(x1, y1, x2, y2);
+ }
+
+ public boolean walkPathCoords(int arrivalRadius, int... coords) {
+ if (coords == null || coords.length < 2) return false;
+ int count = coords.length / 2;
+ int[][] waypoints = new int[count][2];
+ for (int i = 0; i < count; i++) {
+ waypoints[i][0] = coords[i * 2];
+ waypoints[i][1] = coords[i * 2 + 1];
+ }
+ return walkPath(arrivalRadius, waypoints);
+ }
+
+ public boolean walkPath(int[]... waypoints) {
+ return walkPath(2, waypoints);
+ }
+
+ /**
+ * Computes a collision-aware BFS path of world {x, y} tiles from the player to the target.
+ */
+ public List findPath(int targetWorldX, int targetWorldY, int maxSearchRadius) {
+ return findPath(targetWorldX, targetWorldY, maxSearchRadius, false, false);
+ }
+
+ /**
+ * Computes a collision-aware BFS path, optionally returning the closest reachable partial path
+ * when the target is outside the search radius or blocked by an obstacle.
+ */
+ public List findPath(int targetWorldX, int targetWorldY, int maxSearchRadius, boolean allowPartial) {
+ return findPath(targetWorldX, targetWorldY, maxSearchRadius, allowPartial, false);
+ }
+
+ /**
+ * Computes a collision-aware BFS path, optionally allowing cardinal steps through closed doors/gates.
+ */
+ public List findPath(int targetWorldX, int targetWorldY, int maxSearchRadius, boolean allowPartial, boolean passThroughDoors) {
+ if (!isLoggedIn()) return Collections.emptyList();
+ int startLx = getPlayerLocalX();
+ int startLy = getPlayerLocalY();
+ int targetLx = targetWorldX - game.baseX;
+ int targetLy = targetWorldY - game.baseY;
+ if (startLx < 0 || startLx >= 104 || startLy < 0 || startLy >= 104) return Collections.emptyList();
+ if (!allowPartial && (targetLx < 0 || targetLx >= 104 || targetLy < 0 || targetLy >= 104)) {
+ return Collections.emptyList();
+ }
+ if (startLx == targetLx && startLy == targetLy) return Collections.emptyList();
+
+ int rad = Math.max(5, Math.min(55, maxSearchRadius));
+ int minX = Math.max(0, startLx - rad);
+ int maxX = Math.min(103, startLx + rad);
+ int minY = Math.max(0, startLy - rad);
+ int maxY = Math.min(103, startLy + rad);
+ if (!allowPartial && (targetLx < minX || targetLx > maxX || targetLy < minY || targetLy > maxY)) {
+ return Collections.emptyList();
+ }
+
+ boolean[][] doorTile = null;
+ if (passThroughDoors) {
+ doorTile = new boolean[104][104];
+ for (SceneObjectWrapper obj : getSceneObjects(55)) {
+ if (obj.name == null) continue;
+ String lower = obj.name.toLowerCase();
+ if (!lower.contains("door") && !lower.contains("gate")) continue;
+ if (!hasAction(obj, "Open") || isTollGate(obj)) continue;
+ int lx = obj.worldX - game.baseX;
+ int ly = obj.worldY - game.baseY;
+ if (lx >= 0 && lx < 104 && ly >= 0 && ly < 104) {
+ doorTile[lx][ly] = true;
+ }
+ }
+ }
+
+ boolean[][] visited = new boolean[104][104];
+ int[][] parentX = new int[104][104];
+ int[][] parentY = new int[104][104];
+ for (int x = minX; x <= maxX; x++) {
+ for (int y = minY; y <= maxY; y++) {
+ parentX[x][y] = -1;
+ parentY[x][y] = -1;
+ }
+ }
+
+ int[] queueX = new int[104 * 104];
+ int[] queueY = new int[104 * 104];
+ int head = 0;
+ int tail = 0;
+ queueX[tail] = startLx;
+ queueY[tail] = startLy;
+ tail++;
+ visited[startLx][startLy] = true;
+
+ int[][] directions = {
+ {0, 1}, {0, -1}, {1, 0}, {-1, 0},
+ {1, 1}, {-1, 1}, {1, -1}, {-1, -1}
+ };
+
+ boolean found = false;
+ int bestX = startLx;
+ int bestY = startLy;
+ long bestDistSq = (long) (startLx - targetLx) * (startLx - targetLx)
+ + (long) (startLy - targetLy) * (startLy - targetLy);
+ int iterations = 0;
+ while (head != tail && iterations++ < 104 * 104) {
+ int cx = queueX[head];
+ int cy = queueY[head];
+ head = (head + 1) % queueX.length;
+
+ if (cx == targetLx && cy == targetLy) {
+ found = true;
+ bestX = cx;
+ bestY = cy;
+ break;
+ }
+
+ long distSq = (long) (cx - targetLx) * (cx - targetLx)
+ + (long) (cy - targetLy) * (cy - targetLy);
+ if (distSq < bestDistSq) {
+ bestDistSq = distSq;
+ bestX = cx;
+ bestY = cy;
+ }
+
+ int cWorldX = cx + game.baseX;
+ int cWorldY = cy + game.baseY;
+ for (int[] d : directions) {
+ int nx = cx + d[0];
+ int ny = cy + d[1];
+ if (nx < minX || nx > maxX || ny < minY || ny > maxY || visited[nx][ny]) continue;
+ boolean stepOk = canStep(cWorldX, cWorldY, nx + game.baseX, ny + game.baseY);
+ if (!stepOk && doorTile != null && (d[0] == 0 || d[1] == 0)) {
+ if (doorTile[cx][cy] || doorTile[nx][ny]) {
+ stepOk = true;
+ }
+ }
+ if (stepOk) {
+ visited[nx][ny] = true;
+ parentX[nx][ny] = cx;
+ parentY[nx][ny] = cy;
+ queueX[tail] = nx;
+ queueY[tail] = ny;
+ tail = (tail + 1) % queueX.length;
+ if (tail == head) break;
+ }
+ }
+ }
+
+ if (!found && (!allowPartial || (bestX == startLx && bestY == startLy))) {
+ return Collections.emptyList();
+ }
+
+ List reversed = new ArrayList<>();
+ int curX = found ? targetLx : bestX;
+ int curY = found ? targetLy : bestY;
+ while (curX != startLx || curY != startLy) {
+ reversed.add(new int[]{curX + game.baseX, curY + game.baseY});
+ int px = parentX[curX][curY];
+ int py = parentY[curX][curY];
+ if (px == -1 || py == -1) break;
+ curX = px;
+ curY = py;
+ }
+ Collections.reverse(reversed);
+ lastComputedPath = Collections.unmodifiableList(reversed);
+ return reversed;
+ }
+
+ private volatile List lastComputedPath = Collections.emptyList();
+ private boolean suppressWalkToPathUpdate = false;
+ private long lastAutoDoorTime = 0;
+ private int committedGoalX = -1;
+ private int committedGoalY = -1;
+ private int committedTargetX = -1;
+ private int committedTargetY = -1;
+ private long committedGoalTimeMs = 0;
+ private int committedLastPlayerX = -1;
+ private int committedLastPlayerY = -1;
+ private List activeWebRoute = Collections.emptyList();
+ private int activeWebRouteIndex = 0;
+ private int activeWebTargetX = -1;
+ private int activeWebTargetY = -1;
+
+ public List getLastComputedPath() {
+ return lastComputedPath;
+ }
+
+ /**
+ * Walks toward a destination using local collision-aware BFS to route around obstacles,
+ * stepping in 14-tile chunks when the destination is far away or outside the local region.
+ */
+ public boolean walkToSmart(int targetWorldX, int targetWorldY) {
+ return walkToSmartInternal(targetWorldX, targetWorldY, false);
+ }
+
+ private boolean isDoorReachable(SceneObjectWrapper door, int maxDistance) {
+ if (door == null) return false;
+ if (distanceTo(door.worldX, door.worldY) <= 1) return true;
+ if (canReach(door)) return true;
+ int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
+ for (int[] d : dirs) {
+ if (canReach(door.worldX + d[0], door.worldY + d[1], maxDistance + 2, false)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Opens the nearest reachable closed non-toll door or gate within maxDistance.
+ */
+ public boolean openNearestClosedDoor(int maxDistance) {
+ if (!isLoggedIn()) return false;
+ int searchDist = Math.max(4, maxDistance);
+ SceneObjectWrapper door = objects(searchDist)
+ .named("Door", "Gate", "Large door", "Wooden door")
+ .hasAction("Open")
+ .filter(o -> !isOpenGateOrDoor(o) && !isTollGate(o))
+ .filter(o -> isDoorReachable(o, searchDist))
+ .nearest();
+ if (door != null) {
+ lastAutoDoorTime = System.currentTimeMillis();
+ return interactObject(door, "Open");
+ }
+ return false;
+ }
+
+ /**
+ * Walks toward a destination using BFS, automatically opening closed doors/gates if blocked.
+ */
+ public boolean walkToSmartOrOpenDoors(int targetWorldX, int targetWorldY) {
+ return walkToSmartInternal(targetWorldX, targetWorldY, true);
+ }
+
+ private boolean walkToSmartInternal(int targetWorldX, int targetWorldY, boolean openDoors) {
+ if (!isLoggedIn()) return false;
+ int dist = distanceTo(targetWorldX, targetWorldY);
+ if (dist <= 16 && canReach(targetWorldX, targetWorldY, 18, false)) {
+ committedGoalX = -1;
+ activeWebRoute = Collections.emptyList();
+ return walkTo(targetWorldX, targetWorldY);
+ }
+
+ // For long-distance or cross-river routes, follow a sticky F2P road/bridge route monotonically
+ int effectiveTargetX = targetWorldX;
+ int effectiveTargetY = targetWorldY;
+ if ((dist > 35 && !canReach(targetWorldX, targetWorldY, 38, false))
+ || findPath(targetWorldX, targetWorldY, 50, false, openDoors).isEmpty()) {
+ if (activeWebRoute.isEmpty() || activeWebTargetX != targetWorldX || activeWebTargetY != targetWorldY) {
+ activeWebRoute = WorldWebWalker.findRoute(this, getPlayerX(), getPlayerY(), targetWorldX, targetWorldY);
+ activeWebRouteIndex = 0;
+ activeWebTargetX = targetWorldX;
+ activeWebTargetY = targetWorldY;
+ }
+ if (!activeWebRoute.isEmpty()) {
+ int curX = getPlayerX();
+ int curY = getPlayerY();
+ while (activeWebRouteIndex < activeWebRoute.size()) {
+ int[] wp = activeWebRoute.get(activeWebRouteIndex);
+ int wpDist = distanceTo(wp[0], wp[1]);
+ if (wpDist <= 8) {
+ activeWebRouteIndex++;
+ continue;
+ }
+ if (activeWebRouteIndex + 1 < activeWebRoute.size() && wpDist < 25
+ && canReach(wp[0], wp[1], 25, false)) {
+ int[] next = activeWebRoute.get(activeWebRouteIndex + 1);
+ long dot = (long) (curX - wp[0]) * (next[0] - wp[0])
+ + (long) (curY - wp[1]) * (next[1] - wp[1]);
+ if (dot > 0) {
+ activeWebRouteIndex++;
+ continue;
+ }
+ }
+ break;
+ }
+ if (activeWebRouteIndex < activeWebRoute.size()) {
+ effectiveTargetX = activeWebRoute.get(activeWebRouteIndex)[0];
+ effectiveTargetY = activeWebRoute.get(activeWebRouteIndex)[1];
+ }
+ }
+ } else {
+ activeWebRoute = Collections.emptyList();
+ }
+
+ // Hysteresis: keep walking toward committed partial goal while making progress to avoid oscillation
+ long now = System.currentTimeMillis();
+ int px = getPlayerX();
+ int py = getPlayerY();
+ if (committedGoalX != -1
+ && committedTargetX == targetWorldX && committedTargetY == targetWorldY
+ && (now - committedGoalTimeMs) < 4500
+ && distanceTo(committedGoalX, committedGoalY) > 3
+ && (px != committedLastPlayerX || py != committedLastPlayerY)) {
+ committedLastPlayerX = px;
+ committedLastPlayerY = py;
+ if (isPlayerMoving()) {
+ return true;
+ }
+ return walkTo(committedGoalX, committedGoalY);
+ }
+
+ // Local/partial BFS up to 50 tiles
+ List path = findPath(effectiveTargetX, effectiveTargetY, 50, true, openDoors);
+ if (!path.isEmpty()) {
+ int[] end = path.get(path.size() - 1);
+ boolean reachedEndOfPartial = (end[0] != effectiveTargetX || end[1] != effectiveTargetY)
+ && distanceTo(end[0], end[1]) <= 2;
+ if (reachedEndOfPartial) {
+ if (openDoors && (now - lastAutoDoorTime) > 2500) {
+ if (openNearestClosedDoor(8)) {
+ return true;
+ }
+ }
+ if (distanceTo(effectiveTargetX, effectiveTargetY) <= 16
+ && canReach(effectiveTargetX, effectiveTargetY, 18, false)) {
+ committedGoalX = -1;
+ return walkTo(effectiveTargetX, effectiveTargetY);
+ }
+ }
+ int[] best = path.get(0);
+ for (int[] step : path) {
+ if (distanceTo(step[0], step[1]) <= 14) {
+ best = step;
+ } else {
+ break;
+ }
+ }
+ boolean sameGoal = best[0] == committedGoalX && best[1] == committedGoalY
+ && (px != committedLastPlayerX || py != committedLastPlayerY);
+ committedGoalX = best[0];
+ committedGoalY = best[1];
+ committedTargetX = targetWorldX;
+ committedTargetY = targetWorldY;
+ committedGoalTimeMs = now;
+ committedLastPlayerX = px;
+ committedLastPlayerY = py;
+ if (sameGoal && isPlayerMoving()) {
+ return true;
+ }
+ return walkTo(best[0], best[1]);
+ }
+
+ if (openDoors && (now - lastAutoDoorTime) > 2500) {
+ if (openNearestClosedDoor(dist <= 25 ? 12 : 6)) {
+ return true;
+ }
+ }
+ return walkTo(effectiveTargetX, effectiveTargetY);
+ }
+
+ public boolean climb(String action) {
+ if (!isLoggedIn() || action == null || action.isEmpty()) return false;
+ SceneObjectWrapper obj = objects(15)
+ .hasAction(action)
+ .reachable()
+ .nearest();
+ return obj != null && interactObject(obj, action);
+ }
+
+ public boolean climbUp() {
+ return climb("Climb-up");
+ }
+
+ public boolean climbDown() {
+ return climb("Climb-down");
+ }
+
+ public boolean navigateToPlane(int targetPlane) {
+ if (!isLoggedIn()) return false;
+ int cur = getPlane();
+ if (cur < targetPlane) return climbUp();
+ if (cur > targetPlane) return climbDown();
+ return false;
+ }
+}
diff --git a/2006Scape Client/src/main/java/PluginGraphics.java b/2006Scape Client/src/main/java/PluginGraphics.java
new file mode 100644
index 00000000..d6417509
--- /dev/null
+++ b/2006Scape Client/src/main/java/PluginGraphics.java
@@ -0,0 +1,253 @@
+/**
+ * 2D & 3D projected overlay rendering utilities for plugins and scripts.
+ * Renders directly into the current DrawingArea buffer.
+ */
+public class PluginGraphics {
+
+ private final Game game;
+
+ public PluginGraphics(Game game) {
+ this.game = game;
+ }
+
+ public int getViewportWidth() {
+ return DrawingArea.width;
+ }
+
+ public int getViewportHeight() {
+ return DrawingArea.height;
+ }
+
+ public void fillRect(int x, int y, int w, int h, int rgb, int alpha) {
+ if (alpha >= 255) {
+ DrawingArea.fillArea(h, y, rgb, w, x);
+ } else if (alpha > 0) {
+ DrawingArea.fillArea(rgb, y, w, h, alpha, x);
+ }
+ }
+
+ public void drawRect(int x, int y, int w, int h, int rgb) {
+ DrawingArea.fillPixels(y, h, rgb, x, w);
+ }
+
+ public void drawHorizontalLine(int x, int y, int length, int rgb) {
+ DrawingArea.drawHorizontalLine(y, rgb, length, x);
+ }
+
+ public void drawVerticalLine(int x, int y, int length, int rgb) {
+ DrawingArea.drawVerticalLine(y, rgb, length, x);
+ }
+
+ /**
+ * Draws a RuneLite-style RS translucent panel with border and optional header.
+ */
+ public void drawPanel(int x, int y, int w, int h, String title) {
+ // Dark translucent background
+ fillRect(x, y, w, h, 0x121212, 190);
+ // Outer dark stone border
+ drawRect(x, y, w, h, 0x5a5243);
+ drawRect(x + 1, y + 1, w - 2, h - 2, 0x2b271f);
+
+ if (title != null && !title.isEmpty()) {
+ fillRect(x + 2, y + 2, w - 4, 18, 0x2b271f, 220);
+ drawHorizontalLine(x + 1, y + 20, w - 2, 0x5a5243);
+ if (game.aTextDrawingArea_1271 != null) {
+ game.aTextDrawingArea_1271.textLeft(RSColors.WHITE_DARKER, title, y + 15, x + 6);
+ }
+ }
+ }
+
+ public void drawString(String text, int x, int y, int rgb, boolean shadow) {
+ if (text == null || text.isEmpty() || game == null) return;
+ TextDrawingArea font = game.aTextDrawingArea_1270 != null ? game.aTextDrawingArea_1270 : game.aTextDrawingArea_1271;
+ if (font != null) {
+ if (shadow) {
+ font.textLeftShadow(true, x, rgb, text, y);
+ } else {
+ font.textLeft(rgb, text, y, x);
+ }
+ }
+ }
+
+ public void drawStringBold(String text, int x, int y, int rgb, boolean shadow) {
+ if (text == null || text.isEmpty() || game == null) return;
+ TextDrawingArea font = game.aTextDrawingArea_1271 != null ? game.aTextDrawingArea_1271 : game.aTextDrawingArea_1270;
+ if (font != null) {
+ if (shadow) {
+ font.textLeftShadow(true, x, rgb, text, y);
+ } else {
+ font.textLeft(rgb, text, y, x);
+ }
+ }
+ }
+
+ public void drawCenteredString(String text, int x, int y, int rgb) {
+ drawCenteredString(text, x, y, rgb, 255);
+ }
+
+ public void drawCenteredString(String text, int x, int y, int rgb, int alpha) {
+ if (text == null || text.isEmpty() || game == null || alpha <= 0) return;
+ TextDrawingArea font = game.aTextDrawingArea_1270 != null ? game.aTextDrawingArea_1270 : game.aTextDrawingArea_1271;
+ if (font != null) {
+ if (alpha >= 255) {
+ font.textCenter(rgb, text, y, x);
+ } else {
+ font.textCenterAlpha(rgb, text, y, x, alpha, false);
+ }
+ }
+ }
+
+ public void drawRightString(String text, int rightX, int y, int rgb) {
+ if (text == null || text.isEmpty() || game == null) return;
+ TextDrawingArea font = game.aTextDrawingArea_1270 != null ? game.aTextDrawingArea_1270 : game.aTextDrawingArea_1271;
+ if (font != null) {
+ font.textRight(rgb, text, y, rightX);
+ }
+ }
+
+ public int getTextWidth(String text) {
+ if (text == null || text.isEmpty()) return 0;
+ if (game == null) return text.length() * 6;
+ TextDrawingArea font = game.aTextDrawingArea_1270 != null ? game.aTextDrawingArea_1270 : game.aTextDrawingArea_1271;
+ return font != null ? font.getTextWidth(text) : text.length() * 6;
+ }
+
+ public int getTextWidthBold(String text) {
+ if (text == null || text.isEmpty()) return 0;
+ if (game == null) return text.length() * 7;
+ TextDrawingArea font = game.aTextDrawingArea_1271 != null ? game.aTextDrawingArea_1271 : game.aTextDrawingArea_1270;
+ return font != null ? font.getTextWidth(text) : text.length() * 7;
+ }
+
+ public void drawStringTruncated(String text, int x, int y, int maxWidth, int rgb, boolean shadow) {
+ if (text == null || text.isEmpty() || maxWidth <= 0) return;
+ if (getTextWidth(text) <= maxWidth) {
+ drawString(text, x, y, rgb, shadow);
+ return;
+ }
+ String ellipsis = "...";
+ int ellipsisW = getTextWidth(ellipsis);
+ if (maxWidth <= ellipsisW) return;
+ int targetW = maxWidth - ellipsisW;
+
+ int len = text.length();
+ while (len > 0 && getTextWidth(text.substring(0, len)) > targetW) {
+ len--;
+ }
+ if (len > 0) {
+ drawString(text.substring(0, len).trim() + ellipsis, x, y, rgb, shadow);
+ }
+ }
+
+ public void drawStringBoldTruncated(String text, int x, int y, int maxWidth, int rgb, boolean shadow) {
+ if (text == null || text.isEmpty() || maxWidth <= 0) return;
+ if (getTextWidthBold(text) <= maxWidth) {
+ drawStringBold(text, x, y, rgb, shadow);
+ return;
+ }
+ String ellipsis = "...";
+ int ellipsisW = getTextWidthBold(ellipsis);
+ if (maxWidth <= ellipsisW) return;
+ int targetW = maxWidth - ellipsisW;
+
+ int len = text.length();
+ while (len > 0 && getTextWidthBold(text.substring(0, len)) > targetW) {
+ len--;
+ }
+ if (len > 0) {
+ drawStringBold(text.substring(0, len).trim() + ellipsis, x, y, rgb, shadow);
+ }
+ }
+
+ /**
+ * Projects world coordinate to screen (viewport) coordinate.
+ * @return int[] {screenX, screenY} or null if not on screen.
+ */
+ public int[] worldToScreen(int worldX, int worldY, int heightOffset) {
+ int localX = worldX - game.baseX;
+ int localY = worldY - game.baseY;
+ if (localX < 0 || localX >= 104 || localY < 0 || localY >= 104) {
+ return null;
+ }
+ int sceneX = localX * 128 + 64;
+ int sceneY = localY * 128 + 64;
+ game.calcEntityScreenPos(sceneX, heightOffset, sceneY);
+ if (game.spriteDrawX < 0 || game.spriteDrawY < 0) {
+ return null;
+ }
+ return new int[]{game.spriteDrawX, game.spriteDrawY};
+ }
+
+ /**
+ * Draws a tile highlight marker and label in the 3D world.
+ */
+ public void drawTileOverlay(int worldX, int worldY, int rgb, String label) {
+ int[] center = worldToScreen(worldX, worldY, 0);
+ if (center == null) return;
+
+ // Draw cross/diamond at tile center
+ int cx = center[0];
+ int cy = center[1];
+ drawHorizontalLine(cx - 5, cy, 11, rgb);
+ drawVerticalLine(cx, cy - 5, 11, rgb);
+
+ if (label != null && !label.isEmpty()) {
+ int w = getTextWidth(label);
+ fillRect(cx - (w / 2) - 3, cy - 16, w + 6, 12, 0x000000, 160);
+ drawCenteredString(label, cx, cy - 7, rgb);
+ }
+ }
+
+ /**
+ * Draws a vertical radiant lootbeam rising from the ground tile into the sky.
+ */
+ public void drawLootbeam(int worldX, int worldY, int rgb) {
+ int[] ground = worldToScreen(worldX, worldY, 0);
+ int[] sky = worldToScreen(worldX, worldY, 160);
+ if (ground == null || sky == null) return;
+
+ int gx = ground[0];
+ int gy = ground[1];
+ int sy = sky[1];
+ if (gy <= sy) return;
+
+ int height = gy - sy;
+ // Outer radiant glow
+ fillRect(gx - 2, sy, 5, height, rgb, 90);
+ // Inner intense beam
+ fillRect(gx - 1, sy, 3, height, rgb, 180);
+ fillRect(gx, sy, 1, height, 0xffffff, 240);
+
+ // Ground target highlight
+ drawHorizontalLine(gx - 6, gy, 13, rgb);
+ drawVerticalLine(gx, gy - 6, 13, rgb);
+ drawHorizontalLine(gx - 3, gy + 1, 7, rgb);
+ }
+
+ /**
+ * Renders a list of world {x, y} path tiles as step markers on screen.
+ */
+ public void drawPathOverlay(java.util.List path, int rgb) {
+ if (path == null || path.isEmpty()) return;
+ for (int i = 0; i < path.size(); i++) {
+ int[] tile = path.get(i);
+ if (tile == null || tile.length < 2) continue;
+ String label = (i == path.size() - 1) ? "Goal" : null;
+ drawTileOverlay(tile[0], tile[1], rgb, label);
+ }
+ }
+
+ /**
+ * Renders the four corners and center label of a WorldArea in the 3D viewport.
+ */
+ public void drawAreaOverlay(PluginContext.WorldArea area, int rgb, String label) {
+ if (area == null) return;
+ drawTileOverlay(area.minX, area.minY, rgb, null);
+ drawTileOverlay(area.maxX, area.minY, rgb, null);
+ drawTileOverlay(area.minX, area.maxY, rgb, null);
+ drawTileOverlay(area.maxX, area.maxY, rgb, null);
+ if (label != null && !label.isEmpty()) {
+ drawTileOverlay(area.centerX(), area.centerY(), rgb, label);
+ }
+ }
+}
diff --git a/2006Scape Client/src/main/java/PluginManager.java b/2006Scape Client/src/main/java/PluginManager.java
new file mode 100644
index 00000000..0eeb83b3
--- /dev/null
+++ b/2006Scape Client/src/main/java/PluginManager.java
@@ -0,0 +1,834 @@
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.*;
+
+/**
+ * Central singleton coordinator for plugins, scripts, configuration, and event dispatch.
+ */
+public class PluginManager {
+
+ private static volatile PluginManager instance;
+ public static final String API_VERSION = "1.0.0";
+
+ private final Game game;
+ private final PluginContext context;
+ private final PluginGraphics graphics;
+ private final File pluginBaseDir;
+ private final Properties configProps = new Properties();
+ private final File configFile;
+
+ private final List plugins = new ArrayList<>();
+ private final List scripts = new ArrayList<>();
+ private final List lastLoadErrors = new ArrayList<>();
+ private ClientScript activeScript = null;
+ private final int[] lastSkillXp = new int[25];
+ private int lastPlayerAnim = Integer.MIN_VALUE;
+ private boolean wasLoggedIn = false;
+ private boolean deathNotified = false;
+
+ private PluginManager(Game game) {
+ this.game = game;
+ this.context = new PluginContext(game);
+ this.graphics = new PluginGraphics(game);
+ Arrays.fill(lastSkillXp, -1);
+
+ String cacheDir = Signlink.findcachedir();
+ this.pluginBaseDir = new File(cacheDir);
+ this.configFile = new File(cacheDir, "plugin_settings.properties");
+
+ loadConfig();
+ registerBuiltIns();
+ loadExternal();
+ }
+
+ public static synchronized PluginManager init(Game game) {
+ if (instance == null) {
+ instance = new PluginManager(game);
+ }
+ return instance;
+ }
+
+ public static PluginManager get() {
+ return instance;
+ }
+
+ public PluginContext getContext() {
+ return context;
+ }
+
+ public PluginGraphics getGraphics() {
+ return graphics;
+ }
+
+ public List getPlugins() {
+ return Collections.unmodifiableList(plugins);
+ }
+
+ public static boolean isScriptsAvailable() {
+ return ClientSettings.SERVER_WORLD == 1;
+ }
+
+ public List getScripts() {
+ if (!isScriptsAvailable()) {
+ return Collections.emptyList();
+ }
+ return Collections.unmodifiableList(scripts);
+ }
+
+ public List getAllRegisteredScripts() {
+ return Collections.unmodifiableList(scripts);
+ }
+
+ public ClientScript getActiveScript() {
+ return activeScript;
+ }
+
+ // =========================================================================
+ // Registration & Loading
+ // =========================================================================
+
+ private void registerBuiltIns() {
+ registerPlugin(new MenuEntrySwapperPlugin());
+ registerPlugin(new GroundItemsOverlayPlugin());
+ registerPlugin(new Hd317Plugin());
+ }
+
+ public synchronized void syncPluginEnabledState(String pluginName, boolean enabled) {
+ for (ClientPlugin p : plugins) {
+ if (p.getName().equalsIgnoreCase(pluginName)) {
+ p.setEnabled(enabled);
+ String key = "plugin." + p.getName().replace(' ', '_') + ".enabled";
+ configProps.setProperty(key, String.valueOf(enabled));
+ saveConfig();
+ break;
+ }
+ }
+ }
+
+ public static boolean isApiCompatible(String minApiVersion) {
+ return SemVer.parse(API_VERSION).compareTo(SemVer.parse(minApiVersion)) >= 0;
+ }
+
+ public synchronized void registerPlugin(ClientPlugin plugin) {
+ if (plugin == null) return;
+ if (!isApiCompatible(plugin.getMinApiVersion())) {
+ String err = plugin.getName() + ": requires API >= " + plugin.getMinApiVersion() + " (current " + API_VERSION + ")";
+ lastLoadErrors.add(err);
+ System.err.println("Skipping plugin " + err);
+ return;
+ }
+ for (int i = 0; i < plugins.size(); i++) {
+ ClientPlugin existing = plugins.get(i);
+ if (existing.getName().equalsIgnoreCase(plugin.getName())) {
+ if (plugin.getSemVer().isNewerThan(existing.getSemVer())) {
+ if (existing.isEnabled()) {
+ try { existing.onStop(); } catch (Throwable ignored) {}
+ existing.setEnabled(false);
+ }
+ plugins.set(i, plugin);
+ break;
+ }
+ return; // Existing version is same or newer
+ }
+ }
+ if (!plugins.contains(plugin)) {
+ plugins.add(plugin);
+ }
+
+ // Load saved enabled state or default
+ String key = "plugin." + plugin.getName().replace(' ', '_') + ".enabled";
+ boolean enabled = Boolean.parseBoolean(configProps.getProperty(key, String.valueOf(plugin.isEnabledByDefault())));
+ plugin.setEnabled(enabled);
+
+ // Load saved config items
+ for (PluginConfigItem item : plugin.getConfigItems()) {
+ String propKey = "config." + plugin.getName().replace(' ', '_') + "." + item.getKey();
+ if (configProps.containsKey(propKey)) {
+ String valStr = configProps.getProperty(propKey);
+ applyConfigValue(plugin, item, valStr);
+ }
+ }
+
+ if (enabled) {
+ try {
+ plugin.onStart(context);
+ } catch (Throwable t) {
+ System.err.println("Error starting plugin " + plugin.getName() + ": " + t.getMessage());
+ }
+ }
+ }
+
+ public synchronized void registerScript(ClientScript script) {
+ if (script == null) return;
+ if (!isApiCompatible(script.getMinApiVersion())) {
+ String err = script.getName() + ": requires API >= " + script.getMinApiVersion() + " (current " + API_VERSION + ")";
+ lastLoadErrors.add(err);
+ System.err.println("Skipping script " + err);
+ return;
+ }
+ for (int i = 0; i < scripts.size(); i++) {
+ ClientScript existing = scripts.get(i);
+ if (existing.getName().equalsIgnoreCase(script.getName())) {
+ if (script.getSemVer().isNewerThan(existing.getSemVer())) {
+ if (activeScript == existing) {
+ stopScript(existing);
+ }
+ scripts.set(i, script);
+ break;
+ }
+ return;
+ }
+ }
+ if (!scripts.contains(script)) {
+ scripts.add(script);
+ }
+
+ // Load saved config items for script
+ for (PluginConfigItem item : script.getConfigItems()) {
+ String propKey = "config." + script.getName().replace(' ', '_') + "." + item.getKey();
+ if (configProps.containsKey(propKey)) {
+ String valStr = configProps.getProperty(propKey);
+ applyScriptConfigValue(script, item, valStr);
+ }
+ }
+ }
+
+ public synchronized List getLastLoadErrors() {
+ return Collections.unmodifiableList(new ArrayList<>(lastLoadErrors));
+ }
+
+ public File getPluginBaseDir() {
+ return pluginBaseDir;
+ }
+
+ public synchronized void loadExternal() {
+ lastLoadErrors.clear();
+ try {
+ ExternalPluginLoader.LoadedContainer container = ExternalPluginLoader.loadExternal(pluginBaseDir);
+ lastLoadErrors.addAll(container.errors);
+ for (ClientPlugin p : container.plugins) {
+ registerPlugin(p);
+ }
+ for (ClientScript s : container.scripts) {
+ registerScript(s);
+ }
+ } catch (Throwable t) {
+ lastLoadErrors.add(t.getMessage() != null ? t.getMessage() : t.getClass().getSimpleName());
+ System.err.println("Error loading external plugins: " + t.getMessage());
+ t.printStackTrace();
+ }
+ }
+
+ public synchronized void reloadExternal() {
+ // Stop active external scripts/plugins first
+ if (activeScript != null) {
+ stopScript(activeScript);
+ }
+
+ Iterator pIter = plugins.iterator();
+ while (pIter.hasNext()) {
+ ClientPlugin p = pIter.next();
+ if (p instanceof ScriptInterpreter.InterpretedPlugin) {
+ if (p.isEnabled()) {
+ try { p.onStop(); } catch (Throwable ignored) {}
+ }
+ pIter.remove();
+ }
+ }
+
+ Iterator sIter = scripts.iterator();
+ while (sIter.hasNext()) {
+ ClientScript s = sIter.next();
+ if (s instanceof ScriptInterpreter.InterpretedScript) {
+ sIter.remove();
+ }
+ }
+
+ loadExternal();
+ if (context != null) {
+ if (lastLoadErrors.isEmpty()) {
+ context.sendClientMessage("External plugins and scripts reloaded successfully.");
+ } else {
+ context.sendClientMessage("Reload finished with " + lastLoadErrors.size() + " error(s): " + lastLoadErrors.get(0));
+ }
+ }
+ }
+
+ // =========================================================================
+ // Control & Toggling
+ // =========================================================================
+
+ public synchronized void togglePlugin(ClientPlugin plugin) {
+ if (plugin == null) return;
+ boolean newState = !plugin.isEnabled();
+ plugin.setEnabled(newState);
+
+ String key = "plugin." + plugin.getName().replace(' ', '_') + ".enabled";
+ configProps.setProperty(key, String.valueOf(newState));
+ saveConfig();
+
+ try {
+ if (newState) {
+ plugin.onStart(context);
+ context.sendClientMessage(plugin.getName() + " enabled.");
+ } else {
+ plugin.onStop();
+ context.sendClientMessage(plugin.getName() + " disabled.");
+ }
+ } catch (Throwable t) {
+ System.err.println("Error toggling plugin " + plugin.getName() + ": " + t.getMessage());
+ t.printStackTrace();
+ }
+ }
+
+ public synchronized void startScript(ClientScript script) {
+ if (script == null) return;
+ if (!isScriptsAvailable()) {
+ if (context != null) {
+ context.sendClientMessage("Automation scripts are only available on World 1.");
+ }
+ return;
+ }
+ if (activeScript != null && activeScript != script) {
+ stopScript(activeScript);
+ }
+ activeScript = script;
+ script.start(context);
+ }
+
+ public synchronized void stopScript(ClientScript script) {
+ if (script == null) return;
+ script.stop();
+ if (activeScript == script) {
+ activeScript = null;
+ }
+ }
+
+ public synchronized void stopAllScripts() {
+ if (activeScript != null) {
+ stopScript(activeScript);
+ }
+ for (ClientScript s : scripts) {
+ if (s.isRunning()) {
+ s.stop();
+ }
+ }
+ }
+
+ public synchronized void onLogout() {
+ if (wasLoggedIn) {
+ wasLoggedIn = false;
+ notifyDisconnect();
+ }
+ stopAllScripts();
+ for (ClientPlugin p : plugins) {
+ if (p.isEnabled()) {
+ try {
+ p.onLogout();
+ } catch (Throwable t) {
+ System.err.println("Plugin " + p.getName() + " onLogout error: " + t.getMessage());
+ }
+ }
+ }
+ }
+
+ public synchronized void pauseResumeScript(ClientScript script) {
+ if (script == null) return;
+ if (script.isPaused()) {
+ script.resume();
+ } else {
+ script.pause();
+ }
+ }
+
+ // =========================================================================
+ // Configuration Persistence
+ // =========================================================================
+
+ private void loadConfig() {
+ String webCfg = DesktopHooks.loadPluginConfig();
+ if (webCfg != null) {
+ parseConfigLines(webCfg);
+ return;
+ }
+ if (!configFile.exists()) return;
+ try (FileInputStream fis = new FileInputStream(configFile);
+ java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(fis, java.nio.charset.StandardCharsets.UTF_8))) {
+ StringBuilder sb = new StringBuilder();
+ String line;
+ while ((line = reader.readLine()) != null) {
+ sb.append(line).append('\n');
+ }
+ parseConfigLines(sb.toString());
+ } catch (IOException e) {
+ System.err.println("Failed to load plugin config: " + e.getMessage());
+ }
+ }
+
+ private void parseConfigLines(String text) {
+ if (text == null || text.isEmpty()) return;
+ for (String line : text.split("\r?\n")) {
+ if (line.isEmpty() || line.charAt(0) == '#' || line.charAt(0) == '!') continue;
+ int eq = line.indexOf('=');
+ if (eq > 0) {
+ String k = line.substring(0, eq).trim();
+ String v = line.substring(eq + 1).replace("\\=", "=").replace("\\n", "\n").replace("\\r", "\r").replace("\\\\", "\\");
+ configProps.setProperty(k, v);
+ }
+ }
+ }
+
+ public synchronized void saveConfig() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("#2006Scape Plugin System Configuration\n");
+ for (String k : configProps.stringPropertyNames()) {
+ String v = configProps.getProperty(k, "").replace("\\", "\\\\").replace("\r", "\\r").replace("\n", "\\n");
+ sb.append(k).append('=').append(v).append('\n');
+ }
+ String serialized = sb.toString();
+ if (DesktopHooks.savePluginConfig(serialized)) {
+ return;
+ }
+ File parent = configFile.getParentFile();
+ if (parent != null && !parent.exists()) {
+ parent.mkdirs();
+ }
+ try (FileOutputStream fos = new FileOutputStream(configFile);
+ java.io.OutputStreamWriter writer = new java.io.OutputStreamWriter(fos, java.nio.charset.StandardCharsets.UTF_8)) {
+ writer.write(serialized);
+ } catch (IOException e) {
+ System.err.println("Failed to save plugin config: " + e.getMessage());
+ }
+ }
+
+ public synchronized void setPluginConfig(ClientPlugin plugin, String key, Object value) {
+ String propKey = "config." + plugin.getName().replace(' ', '_') + "." + key;
+ configProps.setProperty(propKey, String.valueOf(value));
+ plugin.onConfigChanged(key, value);
+ saveConfig();
+ }
+
+ public synchronized void setScriptConfig(ClientScript script, String key, Object value) {
+ String propKey = "config." + script.getName().replace(' ', '_') + "." + key;
+ configProps.setProperty(propKey, String.valueOf(value));
+ script.onConfigChanged(key, value);
+ saveConfig();
+ }
+
+ public synchronized Object getConfigValue(Object target, PluginConfigItem item) {
+ if (target == null || item == null) return null;
+ String name = (target instanceof ClientPlugin) ? ((ClientPlugin) target).getName()
+ : (target instanceof ClientScript) ? ((ClientScript) target).getName() : "";
+ String propKey = "config." + name.replace(' ', '_') + "." + item.getKey();
+ if (configProps.containsKey(propKey)) {
+ String valStr = configProps.getProperty(propKey);
+ try {
+ switch (item.getType()) {
+ case BOOLEAN:
+ return Boolean.parseBoolean(valStr);
+ case INTEGER:
+ return Integer.parseInt(valStr);
+ case STRING:
+ case CHOICE:
+ return valStr;
+ }
+ } catch (Throwable ignored) {}
+ }
+ return item.getDefaultValue();
+ }
+
+ public synchronized boolean isChatCommandsEnabled(Object target) {
+ if (target == null) return false;
+ String name = (target instanceof ClientPlugin) ? ((ClientPlugin) target).getName()
+ : (target instanceof ClientScript) ? ((ClientScript) target).getName() : "";
+ if (name.isEmpty()) return true;
+ String propKey = "config." + name.replace(' ', '_') + ".chatCommands";
+ return Boolean.parseBoolean(configProps.getProperty(propKey, "true"));
+ }
+
+ public synchronized boolean getConfigBoolean(Object target, PluginConfigItem item) {
+ Object val = getConfigValue(target, item);
+ if (val instanceof Boolean) return (Boolean) val;
+ return Boolean.parseBoolean(String.valueOf(val));
+ }
+
+ public synchronized int getConfigInt(Object target, PluginConfigItem item) {
+ Object val = getConfigValue(target, item);
+ if (val instanceof Number) return ((Number) val).intValue();
+ try {
+ return Integer.parseInt(String.valueOf(val));
+ } catch (Throwable ignored) {
+ return item.getMinValue();
+ }
+ }
+
+ public synchronized void setConfigValue(Object target, PluginConfigItem item, Object value) {
+ if (target instanceof ClientPlugin) {
+ setPluginConfig((ClientPlugin) target, item.getKey(), value);
+ } else if (target instanceof ClientScript) {
+ setScriptConfig((ClientScript) target, item.getKey(), value);
+ }
+ }
+
+ private void applyConfigValue(ClientPlugin plugin, PluginConfigItem item, String valStr) {
+ try {
+ switch (item.getType()) {
+ case BOOLEAN:
+ plugin.onConfigChanged(item.getKey(), Boolean.parseBoolean(valStr));
+ break;
+ case INTEGER:
+ plugin.onConfigChanged(item.getKey(), Integer.parseInt(valStr));
+ break;
+ case STRING:
+ case CHOICE:
+ plugin.onConfigChanged(item.getKey(), valStr);
+ break;
+ }
+ } catch (Throwable ignored) {}
+ }
+
+ private void applyScriptConfigValue(ClientScript script, PluginConfigItem item, String valStr) {
+ try {
+ switch (item.getType()) {
+ case BOOLEAN:
+ script.onConfigChanged(item.getKey(), Boolean.parseBoolean(valStr));
+ break;
+ case INTEGER:
+ script.onConfigChanged(item.getKey(), Integer.parseInt(valStr));
+ break;
+ case STRING:
+ case CHOICE:
+ script.onConfigChanged(item.getKey(), valStr);
+ break;
+ }
+ } catch (Throwable ignored) {}
+ }
+
+ // =========================================================================
+ // Event Dispatch Hooks
+ // =========================================================================
+
+ public void resetEventTracking() {
+ Arrays.fill(lastSkillXp, -1);
+ lastPlayerAnim = Integer.MIN_VALUE;
+ deathNotified = false;
+ }
+
+ private void notifyLogin() {
+ for (int i = 0; i < plugins.size(); i++) {
+ ClientPlugin p = plugins.get(i);
+ if (p.isEnabled()) {
+ try { p.onLogin(); } catch (Throwable ignored) {}
+ }
+ }
+ if (isScriptsAvailable() && activeScript != null && activeScript.isRunning()) {
+ try { activeScript.onLogin(); } catch (Throwable ignored) {}
+ }
+ }
+
+ private void notifyDisconnect() {
+ for (int i = 0; i < plugins.size(); i++) {
+ ClientPlugin p = plugins.get(i);
+ if (p.isEnabled()) {
+ try { p.onDisconnect(); } catch (Throwable ignored) {}
+ }
+ }
+ if (isScriptsAvailable() && activeScript != null && activeScript.isRunning()) {
+ try { activeScript.onDisconnect(); } catch (Throwable ignored) {}
+ }
+ }
+
+ private void notifyPlayerDeath() {
+ for (int i = 0; i < plugins.size(); i++) {
+ ClientPlugin p = plugins.get(i);
+ if (p.isEnabled()) {
+ try { p.onPlayerDeath(); } catch (Throwable ignored) {}
+ }
+ }
+ if (isScriptsAvailable() && activeScript != null && activeScript.isRunning()) {
+ try { activeScript.onPlayerDeath(); } catch (Throwable ignored) {}
+ }
+ }
+
+ public void onGameTick() {
+ if (!context.isLoggedIn()) {
+ if (wasLoggedIn) {
+ wasLoggedIn = false;
+ notifyDisconnect();
+ }
+ resetEventTracking();
+ if (activeScript != null) {
+ stopAllScripts();
+ }
+ return;
+ }
+
+ if (!wasLoggedIn) {
+ wasLoggedIn = true;
+ notifyLogin();
+ }
+
+ if (game.myPlayer != null && game.myPlayer.maxHealth > 0) {
+ if (game.myPlayer.currentHealth == 0) {
+ if (!deathNotified) {
+ deathNotified = true;
+ notifyPlayerDeath();
+ }
+ } else {
+ deathNotified = false;
+ }
+ }
+
+ int currentAnim = context.getPlayerAnim();
+ if (lastPlayerAnim == Integer.MIN_VALUE) {
+ lastPlayerAnim = currentAnim;
+ } else if (currentAnim != lastPlayerAnim) {
+ lastPlayerAnim = currentAnim;
+ onAnimationChanged(currentAnim);
+ }
+
+ // Process plugins
+ for (int i = 0; i < plugins.size(); i++) {
+ ClientPlugin p = plugins.get(i);
+ if (p.isEnabled()) {
+ try {
+ p.onGameTick();
+ } catch (Throwable t) {
+ System.err.println("Plugin " + p.getName() + " tick error: " + t.getMessage());
+ }
+ }
+ }
+
+ // Process active script
+ if (isScriptsAvailable()) {
+ if (activeScript != null && activeScript.isRunning()) {
+ activeScript.processTick();
+ }
+ } else if (activeScript != null) {
+ stopAllScripts();
+ }
+ }
+
+ public void onPostBuildMenu() {
+ if (game.menuActionRow <= 0) return;
+
+ List entries = context.getMenuEntries();
+ for (int i = 0; i < plugins.size(); i++) {
+ ClientPlugin p = plugins.get(i);
+ if (p.isEnabled()) {
+ try {
+ p.onPreMenuRender(entries);
+ } catch (Throwable t) {
+ System.err.println("Plugin " + p.getName() + " menu error: " + t.getMessage());
+ }
+ }
+ }
+ context.setMenuEntries(entries);
+ }
+
+ public boolean onMenuAction(int row) {
+ if (row < 0 || row >= game.menuActionRow) return true;
+ MenuEntry entry = new MenuEntry(
+ game.menuActionName[row],
+ game.menuActionID[row],
+ game.menuActionCmd1[row],
+ game.menuActionCmd2[row],
+ game.menuActionCmd3[row]
+ );
+
+ for (int i = 0; i < plugins.size(); i++) {
+ ClientPlugin p = plugins.get(i);
+ if (p.isEnabled()) {
+ try {
+ if (!p.onMenuAction(entry)) {
+ return false;
+ }
+ } catch (Throwable t) {
+ System.err.println("Plugin " + p.getName() + " action error: " + t.getMessage());
+ }
+ }
+ }
+ return true;
+ }
+
+ public void onChatMessage(int type, String sender, String message) {
+ for (int i = 0; i < plugins.size(); i++) {
+ ClientPlugin p = plugins.get(i);
+ if (p.isEnabled()) {
+ try {
+ p.onChatMessage(type, sender, message);
+ } catch (Throwable ignored) {}
+ }
+ }
+ if (isScriptsAvailable() && activeScript != null && activeScript.isRunning()) {
+ try {
+ activeScript.onChatMessage(type, sender, message);
+ } catch (Throwable ignored) {}
+ }
+ if (message != null && message.toLowerCase().contains("oh dear, you are dead") && !deathNotified) {
+ deathNotified = true;
+ notifyPlayerDeath();
+ }
+ }
+
+ public void onGroundItemSpawn(int itemId, int amount, int worldX, int worldY, int plane) {
+ int baseX = context.isLoggedIn() ? context.getBaseX() : 0;
+ int baseY = context.isLoggedIn() ? context.getBaseY() : 0;
+ int px = context.isLoggedIn() ? context.getPlayerX() : worldX;
+ int py = context.isLoggedIn() ? context.getPlayerY() : worldY;
+ PluginContext.GroundItemWrapper wrapper = new PluginContext.GroundItemWrapper(
+ itemId, amount, worldX, worldY, plane, baseX, baseY, px, py
+ );
+
+ for (int i = 0; i < plugins.size(); i++) {
+ ClientPlugin p = plugins.get(i);
+ if (p.isEnabled()) {
+ try {
+ p.onGroundItemSpawn(itemId, amount, worldX, worldY, plane);
+ p.onGroundItemSpawned(wrapper);
+ } catch (Throwable ignored) {}
+ }
+ }
+ if (isScriptsAvailable() && activeScript != null && activeScript.isRunning()) {
+ try {
+ activeScript.onGroundItemSpawned(wrapper);
+ } catch (Throwable ignored) {}
+ }
+ }
+
+ public void onSkillUpdate(int skillId, int experience, int level) {
+ if (skillId < 0 || skillId >= lastSkillXp.length) return;
+ if (lastSkillXp[skillId] == -1) {
+ lastSkillXp[skillId] = experience;
+ return;
+ }
+ int deltaXp = experience - lastSkillXp[skillId];
+ lastSkillXp[skillId] = experience;
+ if (deltaXp <= 0) return;
+
+ for (int i = 0; i < plugins.size(); i++) {
+ ClientPlugin p = plugins.get(i);
+ if (p.isEnabled()) {
+ try {
+ p.onXpGained(skillId, deltaXp);
+ } catch (Throwable ignored) {}
+ }
+ }
+ if (isScriptsAvailable() && activeScript != null && activeScript.isRunning()) {
+ try {
+ activeScript.onXpGained(skillId, deltaXp);
+ } catch (Throwable ignored) {}
+ }
+ }
+
+ public void onAnimationChanged(int animId) {
+ for (int i = 0; i < plugins.size(); i++) {
+ ClientPlugin p = plugins.get(i);
+ if (p.isEnabled()) {
+ try {
+ p.onAnimationChanged(animId);
+ } catch (Throwable ignored) {}
+ }
+ }
+ if (isScriptsAvailable() && activeScript != null && activeScript.isRunning()) {
+ try {
+ activeScript.onAnimationChanged(animId);
+ } catch (Throwable ignored) {}
+ }
+ }
+
+ public void onRenderOverlays() {
+ if (!context.isLoggedIn()) return;
+
+ for (int i = 0; i < plugins.size(); i++) {
+ ClientPlugin p = plugins.get(i);
+ if (p.isEnabled()) {
+ try {
+ p.onRenderOverlay(graphics);
+ } catch (Throwable t) {
+ System.err.println("Plugin " + p.getName() + " overlay error: " + t.getMessage());
+ }
+ }
+ }
+
+ if (isScriptsAvailable() && activeScript != null && activeScript.isRunning()) {
+ try {
+ activeScript.onRenderOverlay(graphics);
+ } catch (Throwable t) {
+ System.err.println("Script " + activeScript.getName() + " overlay error: " + t.getMessage());
+ }
+ }
+ }
+
+ public boolean onCommand(String input) {
+ if (input == null || !input.startsWith("::")) return false;
+ String clean = input.substring(2).trim();
+ String[] parts = clean.split("\\s+");
+ if (parts.length == 0 || parts[0].isEmpty()) return false;
+
+ String cmd = parts[0].toLowerCase();
+ String[] args = new String[parts.length - 1];
+ System.arraycopy(parts, 1, args, 0, args.length);
+
+ if ("plugins".equalsIgnoreCase(cmd) || "scripts".equalsIgnoreCase(cmd) || "pluginhub".equalsIgnoreCase(cmd)) {
+ if ("scripts".equalsIgnoreCase(cmd) && !isScriptsAvailable()) {
+ if (context != null) {
+ context.sendClientMessage("Automation scripts are only available on World 1.");
+ }
+ PluginPanelUI.openModal(0);
+ return true;
+ }
+ PluginPanelUI.openModal("scripts".equalsIgnoreCase(cmd) ? 1 : 0);
+ return true;
+ }
+
+ if ("reloadplugins".equalsIgnoreCase(cmd) || "reloadscripts".equalsIgnoreCase(cmd)) {
+ reloadExternal();
+ return true;
+ }
+
+ if ("files".equalsIgnoreCase(cmd) || "scriptsdir".equalsIgnoreCase(cmd) || "openfiles".equalsIgnoreCase(cmd)) {
+ AndroidHooks.openScriptsFolder();
+ if (context != null) {
+ context.sendClientMessage(isScriptsAvailable() ? "Opened external plugins and scripts storage." : "Opened external plugins storage.");
+ }
+ return true;
+ }
+
+ // Script-defined :: commands (toggleable per script via chatCommands config)
+ for (ClientScript s : scripts) {
+ List cmds = s.getCommandNames();
+ if (cmds == null || cmds.isEmpty()) continue;
+ for (String c : cmds) {
+ if (cmd.equalsIgnoreCase(c)) {
+ if (!isChatCommandsEnabled(s)) {
+ return false;
+ }
+ if (!isScriptsAvailable()) {
+ if (context != null) {
+ context.sendClientMessage("Automation scripts are only available on World 1.");
+ }
+ return true;
+ }
+ if (s.isRunning()) {
+ stopScript(s);
+ } else {
+ startScript(s);
+ }
+ return true;
+ }
+ }
+ }
+
+ // Pass to plugins
+ for (ClientPlugin p : plugins) {
+ if ((p.isEnabled() || p.handlesCommandsWhenDisabled()) && isChatCommandsEnabled(p) && p.onCommand(cmd, args)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/2006Scape Client/src/main/java/PluginPanelUI.java b/2006Scape Client/src/main/java/PluginPanelUI.java
new file mode 100644
index 00000000..8f98b1d4
--- /dev/null
+++ b/2006Scape Client/src/main/java/PluginPanelUI.java
@@ -0,0 +1,1837 @@
+import java.util.List;
+
+/**
+ * In-game Canvas UI for Tab 7 and the 3D Viewport Interactive Modal.
+ * Styled authentically after native RuneScape 2006 (Revision 377) stone interfaces,
+ * with beveled stone borders, dark parchment/stone background (0x2a251e), gold headers,
+ * authentic red stone close button, seamless segmented button groups, and native RS scrollbar.
+ * Works identically across Desktop (Fixed & Modern) and Android (Fixed & Modern).
+ */
+public class PluginPanelUI {
+
+ private static boolean modalOpen = false;
+ private static int currentModalTab = 0; // 0: Plugins, 1: Scripts, 2: Online Repo, 3: Config Page
+ private static int currentRepoSubTab = 0; // 0: Plugins, 1: Scripts
+ private static int configReturnTab = 0;
+ private static Object configTarget = null; // ClientPlugin or ClientScript currently being configured
+ private static int scrollOffset = 0;
+ private static String searchQuery = "";
+ private static boolean searchFocused = false;
+ private static String openDropdownKey = null;
+ private static int dropdownScrollOffset = 0;
+ private static boolean isDraggingDropdown = false;
+ private static final int DROPDOWN_WIDTH = 172;
+ private static final int DROPDOWN_ROW_H = 22;
+ private static final int DROPDOWN_MAX_VISIBLE = 6;
+
+ private static boolean isDragging = false;
+ private static boolean isDraggingScrollBar = false;
+ private static int lastDragY = -1;
+ private static int dragStartY = -1;
+ private static boolean wasDrag = false;
+
+ // Modal Dimensions - fits cleanly within standard 512x334 interface rectangle like the Bank interface
+ public static final int MODAL_WIDTH = 488;
+ public static final int MODAL_HEIGHT = 308;
+
+ public static boolean isModalOpen() {
+ return modalOpen;
+ }
+
+ public static boolean isSearchFocused() {
+ return modalOpen && searchFocused && (currentModalTab == 0 || currentModalTab == 1 || currentModalTab == 2);
+ }
+
+ public static void handleKeyChar(int ch) {
+ if (!isSearchFocused()) {
+ return;
+ }
+ if (ch == 8) {
+ if (!searchQuery.isEmpty()) {
+ searchQuery = searchQuery.substring(0, searchQuery.length() - 1);
+ scrollOffset = 0;
+ }
+ } else if (ch == 10 || ch == 13 || ch == 27) {
+ searchFocused = false;
+ } else if (ch >= 32 && ch <= 126 && searchQuery.length() < 40) {
+ searchQuery += (char) ch;
+ scrollOffset = 0;
+ }
+ }
+
+ public static void openModal(int tab) {
+ modalOpen = true;
+ searchFocused = false;
+ currentModalTab = (!PluginManager.isScriptsAvailable() && tab == 1) ? 0 : tab;
+ if (currentModalTab == 2) {
+ PluginRepoClient.ensureLoaded();
+ }
+ scrollOffset = 0;
+ isDragging = false;
+ isDraggingScrollBar = false;
+ lastDragY = -1;
+ dragStartY = -1;
+ wasDrag = false;
+ PluginManager pm = PluginManager.get();
+ if (pm != null && pm.getContext() != null) {
+ Game game = pm.getContext().getGame();
+ if (game != null && game.openInterfaceID != -1) {
+ game.closeOpenInterfaces();
+ }
+ }
+ }
+
+ public static void closeModal() {
+ modalOpen = false;
+ searchFocused = false;
+ configTarget = null;
+ scrollOffset = 0;
+ openDropdownKey = null;
+ dropdownScrollOffset = 0;
+ isDragging = false;
+ isDraggingScrollBar = false;
+ isDraggingDropdown = false;
+ lastDragY = -1;
+ dragStartY = -1;
+ wasDrag = false;
+ }
+
+ public static int getScrollOffset() {
+ return scrollOffset;
+ }
+
+ public static void setScrollOffset(int offset) {
+ scrollOffset = offset;
+ }
+
+ public static int getCurrentModalTab() {
+ return currentModalTab;
+ }
+
+ public static void setCurrentModalTab(int tab) {
+ currentModalTab = tab;
+ }
+
+ public static Object getConfigTarget() {
+ return configTarget;
+ }
+
+ public static void setConfigTarget(Object target) {
+ configTarget = target;
+ }
+
+ public static int getModalAreaWidth() {
+ if (ClientSettings.ANDROID || !ClientSettings.isDesktopModern()) {
+ return 512;
+ }
+ return DrawingArea.width > 0 ? DrawingArea.width : ClientSettings.VIEWPORT_WIDTH;
+ }
+
+ public static int getModalAreaHeight() {
+ if (ClientSettings.ANDROID || !ClientSettings.isDesktopModern()) {
+ return 334;
+ }
+ return DrawingArea.height > 0 ? DrawingArea.height : ClientSettings.VIEWPORT_HEIGHT;
+ }
+
+ public static int toLocalX(int x) {
+ if (ClientSettings.ANDROID || !ClientSettings.isDesktopModern()) {
+ return x - 4;
+ }
+ return x;
+ }
+
+ public static int toLocalY(int y) {
+ if (ClientSettings.ANDROID || !ClientSettings.isDesktopModern()) {
+ return y - 4;
+ }
+ return y;
+ }
+
+ public static int getContentAreaY() {
+ int vh = getModalAreaHeight();
+ int my = Math.max(0, (vh - MODAL_HEIGHT) / 2);
+ return my + 28 + 26;
+ }
+
+ public static int getContentAreaHeight() {
+ int vh = getModalAreaHeight();
+ int my = Math.max(0, (vh - MODAL_HEIGHT) / 2);
+ int contentY = getContentAreaY();
+ int footerY = my + MODAL_HEIGHT - 32;
+ return footerY - contentY - 4;
+ }
+
+ public static void handleMouseWheel(int notches) {
+ if (!modalOpen) return;
+ PluginManager pm = PluginManager.get();
+ if (pm == null) return;
+ if (currentModalTab == 3 && openDropdownKey != null) {
+ int maxDropScroll = getOpenDropdownMaxScroll(pm);
+ if (maxDropScroll > 0) {
+ dropdownScrollOffset += notches * DROPDOWN_ROW_H;
+ if (dropdownScrollOffset < 0) dropdownScrollOffset = 0;
+ if (dropdownScrollOffset > maxDropScroll) dropdownScrollOffset = maxDropScroll;
+ return;
+ }
+ }
+ scrollOffset += notches * 30;
+ clampScroll(pm);
+ }
+
+ private static int[] getOpenDropdownBounds(PluginManager pm) {
+ if (openDropdownKey == null || configTarget == null || currentModalTab != 3) return null;
+ List items = getVisibleConfigItems(pm, configTarget);
+ if (items == null) return null;
+ int vw = getModalAreaWidth();
+ int vh = getModalAreaHeight();
+ int mx = Math.max(0, (vw - MODAL_WIDTH) / 2);
+ int my = Math.max(0, (vh - MODAL_HEIGHT) / 2);
+ int wellX = mx + 12;
+ int wellW = MODAL_WIDTH - 24;
+ int contentY = getContentAreaY();
+ int contentH = getContentAreaHeight();
+ int headerH = getConfigHeaderHeight();
+ int wellInnerX = wellX + 2;
+ int wellInnerW = wellW - 4 - 16;
+
+ int rowY = contentY + headerH + 2 - scrollOffset;
+ for (int i = 0; i < items.size(); i++) {
+ PluginConfigItem item = items.get(i);
+ if (openDropdownKey.equals(item.getKey())) {
+ String[] choices = item.getChoices();
+ if (choices == null || choices.length == 0) return null;
+ int visibleCount = Math.min(DROPDOWN_MAX_VISIBLE, choices.length);
+ int dropH = visibleCount * DROPDOWN_ROW_H + 2;
+ int dropX = wellInnerX + wellInnerW - DROPDOWN_WIDTH;
+ int dropY = rowY + 31;
+ if (dropY + dropH > contentY + contentH) {
+ dropY = Math.max(contentY + 2, rowY + 1 - dropH);
+ }
+ return new int[]{dropX, dropY, DROPDOWN_WIDTH, dropH, i, choices.length};
+ }
+ rowY += 32;
+ }
+ return null;
+ }
+
+ private static int getOpenDropdownMaxScroll(PluginManager pm) {
+ int[] b = getOpenDropdownBounds(pm);
+ if (b == null) return 0;
+ int totalH = b[5] * DROPDOWN_ROW_H + 2;
+ return Math.max(0, totalH - b[3]);
+ }
+
+ private static boolean matchesSearch(String name, String desc, String author) {
+ if (searchQuery == null || searchQuery.isEmpty()) {
+ return true;
+ }
+ String q = searchQuery.toLowerCase(java.util.Locale.ROOT);
+ if (name != null && name.toLowerCase(java.util.Locale.ROOT).contains(q)) {
+ return true;
+ }
+ if (desc != null && desc.toLowerCase(java.util.Locale.ROOT).contains(q)) {
+ return true;
+ }
+ return author != null && author.toLowerCase(java.util.Locale.ROOT).contains(q);
+ }
+
+ private static List getFilteredPlugins(PluginManager pm) {
+ List filtered = new java.util.ArrayList<>();
+ if (pm == null || pm.getPlugins() == null) return filtered;
+ for (ClientPlugin p : pm.getPlugins()) {
+ if (matchesSearch(p.getName(), p.getDescription(), null)) {
+ filtered.add(p);
+ }
+ }
+ return filtered;
+ }
+
+ private static List getFilteredScripts(PluginManager pm) {
+ List filtered = new java.util.ArrayList<>();
+ if (pm == null || pm.getScripts() == null) return filtered;
+ for (ClientScript s : pm.getScripts()) {
+ if (matchesSearch(s.getName(), s.getDescription(), null)) {
+ filtered.add(s);
+ }
+ }
+ return filtered;
+ }
+
+ public static int getContentHeight(PluginManager pm) {
+ int contentH = getContentAreaHeight();
+ if (pm == null) return contentH;
+ if (currentModalTab == 0) {
+ return getFilteredPlugins(pm).size() * 38 + 34;
+ } else if (currentModalTab == 1) {
+ if (!PluginManager.isScriptsAvailable()) return contentH;
+ return getFilteredScripts(pm).size() * 38 + 34;
+ } else if (currentModalTab == 2) {
+ List entries = getFilteredRepoEntries();
+ return entries.size() * 38 + 34;
+ } else if (currentModalTab == 3) {
+ if (configTarget == null) {
+ return contentH;
+ }
+ List items = getVisibleConfigItems(pm, configTarget);
+ if (items == null || items.isEmpty()) return contentH;
+ return (items.size() * 32) + getConfigHeaderHeight() + 4;
+ }
+ return contentH;
+ }
+
+ public static List getVisibleConfigItems(PluginManager pm, Object target) {
+ List rawItems = (target instanceof ClientPlugin) ? ((ClientPlugin) target).getConfigItems()
+ : (target instanceof ClientScript) ? ((ClientScript) target).getConfigItems() : null;
+ if (rawItems == null || rawItems.isEmpty()) return rawItems;
+ List visible = new java.util.ArrayList<>();
+ for (PluginConfigItem item : rawItems) {
+ String depKey = item.getVisibleWhen();
+ if (depKey == null || depKey.isEmpty() || pm == null) {
+ visible.add(item);
+ continue;
+ }
+ PluginConfigItem dep = null;
+ for (PluginConfigItem candidate : rawItems) {
+ if (depKey.equals(candidate.getKey())) {
+ dep = candidate;
+ break;
+ }
+ }
+ if (dep == null || pm.getConfigBoolean(target, dep)) {
+ visible.add(item);
+ }
+ }
+ return visible;
+ }
+
+ public static int getConfigHeaderHeight() {
+ if (configTarget != null) {
+ String desc = (configTarget instanceof ClientPlugin) ? ((ClientPlugin) configTarget).getDescription()
+ : (configTarget instanceof ClientScript) ? ((ClientScript) configTarget).getDescription() : null;
+ if (desc != null && !desc.isEmpty()) {
+ return 40;
+ }
+ }
+ return 24;
+ }
+
+ public static int getMaxScroll(PluginManager pm) {
+ int contentH = getContentAreaHeight();
+ if (currentModalTab == 2) {
+ int availH = contentH - 26;
+ int totalH = getContentHeight(pm);
+ return Math.max(0, totalH - availH);
+ } else if (currentModalTab == 3) {
+ int headerH = (configTarget != null) ? getConfigHeaderHeight() : 24;
+ int availH = contentH - headerH;
+ int totalH = getContentHeight(pm);
+ return Math.max(0, totalH - availH);
+ } else {
+ int totalH = getContentHeight(pm);
+ return Math.max(0, totalH - contentH);
+ }
+ }
+
+ public static void clampScroll(PluginManager pm) {
+ int max = getMaxScroll(pm);
+ if (scrollOffset > max) {
+ scrollOffset = max;
+ }
+ if (scrollOffset < 0) {
+ scrollOffset = 0;
+ }
+ }
+
+ public static boolean isModalAt(int x, int y) {
+ if (!modalOpen) return false;
+ int lx = toLocalX(x);
+ int ly = toLocalY(y);
+ int vw = getModalAreaWidth();
+ int vh = getModalAreaHeight();
+ int mx = Math.max(0, (vw - MODAL_WIDTH) / 2);
+ int my = Math.max(0, (vh - MODAL_HEIGHT) / 2);
+ return lx >= mx && lx <= mx + MODAL_WIDTH && ly >= my && ly <= my + MODAL_HEIGHT;
+ }
+
+ public static boolean isScrollBarAt(int x, int y) {
+ if (!modalOpen) return false;
+ PluginManager pm = PluginManager.get();
+ if (pm == null) return false;
+ if (getMaxScroll(pm) <= 0) return false;
+ int lx = toLocalX(x);
+ int ly = toLocalY(y);
+ int vw = getModalAreaWidth();
+ int mx = Math.max(0, (vw - MODAL_WIDTH) / 2);
+ int contentY = getContentAreaY();
+ int contentH = getContentAreaHeight();
+ int sbX = mx + MODAL_WIDTH - 28;
+ int sbY = contentY + 2;
+ int sbH = contentH - 4;
+ return lx >= sbX - 6 && lx <= sbX + 22 && ly >= sbY - 2 && ly <= sbY + sbH + 2;
+ }
+
+ public static boolean isContentAreaAt(int x, int y) {
+ if (!modalOpen) return false;
+ int lx = toLocalX(x);
+ int ly = toLocalY(y);
+ int vw = getModalAreaWidth();
+ int mx = Math.max(0, (vw - MODAL_WIDTH) / 2);
+ int contentY = getContentAreaY();
+ int contentH = getContentAreaHeight();
+ return lx >= mx + 10 && lx <= mx + MODAL_WIDTH - 10 && ly >= contentY && ly <= contentY + contentH;
+ }
+
+ public static void processInput(Game game) {
+ if (!modalOpen || game == null) {
+ isDragging = false;
+ isDraggingScrollBar = false;
+ lastDragY = -1;
+ return;
+ }
+
+ PluginManager pm = PluginManager.get();
+ int maxScroll = pm != null ? getMaxScroll(pm) : 0;
+
+ if (game.clickMode2 == 1) {
+ int mx = toLocalX(game.mouseX);
+ int my = toLocalY(game.mouseY);
+
+ if (!isDragging) {
+ if (isScrollBarAt(game.mouseX, game.mouseY)) {
+ isDragging = true;
+ int contentY = getContentAreaY();
+ int contentH = getContentAreaHeight();
+ int sbY = contentY + 2;
+ int sbH = contentH - 4;
+ if (my < sbY + 16) {
+ scrollOffset -= 24;
+ clampScroll(pm);
+ isDraggingScrollBar = false;
+ } else if (my > sbY + sbH - 16) {
+ scrollOffset += 24;
+ clampScroll(pm);
+ isDraggingScrollBar = false;
+ } else {
+ isDraggingScrollBar = true;
+ handleScrollBarJump(pm, my, maxScroll);
+ }
+ lastDragY = my;
+ dragStartY = my;
+ wasDrag = false;
+ } else if (isContentAreaAt(game.mouseX, game.mouseY)) {
+ int[] dropBounds = getOpenDropdownBounds(pm);
+ isDragging = true;
+ isDraggingScrollBar = false;
+ isDraggingDropdown = (dropBounds != null && mx >= dropBounds[0] && mx <= dropBounds[0] + dropBounds[2]
+ && my >= dropBounds[1] && my <= dropBounds[1] + dropBounds[3]);
+ lastDragY = my;
+ dragStartY = my;
+ wasDrag = false;
+ }
+ } else {
+ if (Math.abs(my - dragStartY) > 5) {
+ wasDrag = true;
+ }
+ if (isDraggingDropdown) {
+ int maxDropScroll = getOpenDropdownMaxScroll(pm);
+ if (maxDropScroll > 0) {
+ int deltaY = my - lastDragY;
+ if (deltaY != 0) {
+ dropdownScrollOffset -= deltaY;
+ if (dropdownScrollOffset < 0) dropdownScrollOffset = 0;
+ if (dropdownScrollOffset > maxDropScroll) dropdownScrollOffset = maxDropScroll;
+ }
+ }
+ } else if (maxScroll > 0) {
+ if (isDraggingScrollBar) {
+ handleScrollBarJump(pm, my, maxScroll);
+ } else {
+ int deltaY = my - lastDragY;
+ if (deltaY != 0) {
+ scrollOffset -= deltaY;
+ clampScroll(pm);
+ }
+ }
+ }
+ lastDragY = my;
+ }
+ } else {
+ isDragging = false;
+ isDraggingScrollBar = false;
+ isDraggingDropdown = false;
+ lastDragY = -1;
+ }
+ }
+
+ private static void handleScrollBarJump(PluginManager pm, int clickY, int maxScroll) {
+ if (pm == null || maxScroll <= 0) return;
+ int contentY = getContentAreaY();
+ int contentH = getContentAreaHeight();
+ int sbY = contentY + 2;
+ int sbH = contentH - 4;
+
+ int trackH = sbH - 32;
+ int thumbH = Math.max(8, (trackH * sbH) / (sbH + maxScroll));
+ if (thumbH > trackH) thumbH = trackH;
+ int trackAvail = trackH - thumbH;
+
+ if (isDraggingScrollBar) {
+ if (trackAvail > 0) {
+ int relY = clickY - (sbY + 16) - (thumbH / 2);
+ relY = Math.max(0, Math.min(relY, trackAvail));
+ scrollOffset = (relY * maxScroll) / trackAvail;
+ clampScroll(pm);
+ }
+ return;
+ }
+
+ // Discrete tap: Up arrow click (16px)
+ if (clickY < sbY + 16) {
+ scrollOffset -= 24;
+ clampScroll(pm);
+ return;
+ }
+ // Down arrow click (16px)
+ if (clickY > sbY + sbH - 16) {
+ scrollOffset += 24;
+ clampScroll(pm);
+ return;
+ }
+
+ // Track and thumb tap jump
+ if (trackAvail > 0) {
+ int relY = clickY - (sbY + 16) - (thumbH / 2);
+ relY = Math.max(0, Math.min(relY, trackAvail));
+ scrollOffset = (relY * maxScroll) / trackAvail;
+ clampScroll(pm);
+ }
+ }
+
+ // =========================================================================
+ // Tab 7 (QoL & Plugins) Rendering and Click Handling
+ // =========================================================================
+
+ public static void drawTab7(Game game) {
+ PluginManager pm = PluginManager.get();
+ if (pm == null) return;
+
+ try {
+ int centerX = 95;
+ int currentY = 6;
+ int stepY = 36;
+ int textTop = 13;
+ int textBottom = 27;
+ int textMiddle = 20;
+
+ // 1. "PLUGIN HUB" (Opens Viewport Modal)
+ game.drawButton(modalOpen, centerX - 73, currentY, 146);
+ game.aTextDrawingArea_1271.textCenterShadow(0x00ffff, centerX, "PLUGIN HUB", currentY + textTop, true);
+ game.aTextDrawingArea_1271.textCenterShadow(RSColors.YELLOW, centerX, "[Open Modal]", currentY + textBottom, true);
+
+ // Hide remaining QoL buttons when QoL client settings are disabled
+ if (!ClientSettings.ENABLE_QOL) {
+ return;
+ }
+
+ currentY += stepY;
+
+ // 2. Always Visible Player Names
+ game.drawButton(game.customSettingVisiblePlayerNames, centerX - 73, currentY, 146);
+ game.aTextDrawingArea_1271.textCenterShadow(RSColors.YELLOW, centerX, "player names", currentY + textMiddle, true);
+ currentY += stepY;
+
+ // 3. Item Drops Visible
+ game.drawButton(true, centerX - 73, currentY, 146);
+ game.aTextDrawingArea_1271.textCenterShadow(RSColors.YELLOW, centerX, "item drops visible", currentY + textTop, true);
+ game.aTextDrawingArea_1271.textCenterShadow(RSColors.WHITE, centerX, game.intToKOrMil(game.customSettingMinItemValue) + " gp", currentY + textBottom, true);
+ currentY += stepY;
+
+ // 4. Draw Distance
+ game.drawButton(true, centerX - 73, currentY, 146);
+ game.aTextDrawingArea_1271.textCenterShadow(RSColors.YELLOW, centerX, "draw distance", currentY + textTop, true);
+ game.aTextDrawingArea_1271.textCenterShadow(RSColors.WHITE, centerX, WorldController.drawDistance + " tiles", currentY + textBottom, true);
+ currentY += stepY;
+
+ // 5. Experience Tracker Info
+ game.drawButton(game.customSettingShowExperiencePerHour, centerX - 73, currentY, 146);
+ game.aTextDrawingArea_1271.textCenterShadow(RSColors.YELLOW, centerX, "show exp info", currentY + textMiddle, true);
+ currentY += stepY;
+
+ // 6. Debug Info
+ game.drawButton(game.showInfo, centerX - 73, currentY, 146);
+ game.aTextDrawingArea_1271.textCenterShadow(RSColors.YELLOW, centerX, "show debug info", currentY + textMiddle, true);
+ currentY += stepY;
+
+ // 7. Visual Fixes
+ game.drawButton(game.customSettingVisualFixes, centerX - 73, currentY, 146);
+ game.aTextDrawingArea_1271.textCenterShadow(RSColors.YELLOW, centerX, "visual fixes", currentY + textMiddle, true);
+
+ } catch (Throwable ignored) {
+ }
+ }
+
+ public static boolean handleTab7Click(Game game, int clickX, int clickY) {
+ PluginManager pm = PluginManager.get();
+ if (pm == null) return false;
+
+ // In fixed layout, tab body X is 575..720, Y is 210..465
+ int startY = 210 + 6;
+ int stepY = 36;
+
+ // 1. Plugin Hub Open Modal
+ if (clickY >= startY && clickY <= startY + 30) {
+ modalOpen = !modalOpen;
+ if (modalOpen) currentModalTab = 0;
+ return true;
+ }
+
+ // Ignore remaining QoL clicks when QoL client settings are disabled
+ if (!ClientSettings.ENABLE_QOL) {
+ return false;
+ }
+
+ startY += stepY;
+
+ // 2. Player Names
+ if (clickY >= startY && clickY <= startY + 30) {
+ game.customSettingVisiblePlayerNames = !game.customSettingVisiblePlayerNames;
+ return true;
+ }
+ startY += stepY;
+
+ // 3. Item Drops Visible Prompt
+ if (clickY >= startY && clickY <= startY + 30) {
+ game.inputTaken = true;
+ game.inputDialogState = 0;
+ game.messagePromptRaised = true;
+ game.promptInput = "";
+ game.aString1121 = "Enter minimum item value";
+ game.customTabAction = 1;
+ return true;
+ }
+ startY += stepY;
+
+ // 4. Draw Distance Prompt
+ if (clickY >= startY && clickY <= startY + 30) {
+ game.inputTaken = true;
+ game.inputDialogState = 0;
+ game.messagePromptRaised = true;
+ game.promptInput = "";
+ game.aString1121 = "Enter new draw distance";
+ game.customTabAction = 2;
+ return true;
+ }
+ startY += stepY;
+
+ // 5. Exp Tracker
+ if (clickY >= startY && clickY <= startY + 30) {
+ game.customSettingShowExperiencePerHour = !game.customSettingShowExperiencePerHour;
+ game.customSettingShowExperiencePerHourStart = System.currentTimeMillis();
+ game.customSettingShowExperiencePerHourStartExp = game.calculateTotalExp();
+ game.customSettingShowExperiencePerHourStartLevels = game.calculateTotalLevels();
+ return true;
+ }
+ startY += stepY;
+
+ // 6. Debug Info
+ if (clickY >= startY && clickY <= startY + 30) {
+ game.showInfo = !game.showInfo;
+ return true;
+ }
+ startY += stepY;
+
+ // 7. Visual Fixes
+ if (clickY >= startY && clickY <= startY + 30) {
+ game.customSettingVisualFixes = !game.customSettingVisualFixes;
+ ClientSettings.BILINEAR_MINIMAP_FILTERING = !ClientSettings.BILINEAR_MINIMAP_FILTERING;
+ ClientSettings.FIX_TRANSPARENCY_OVERFLOW = !ClientSettings.FIX_TRANSPARENCY_OVERFLOW;
+ ClientSettings.FULL_512PX_VIEWPORT = !ClientSettings.FULL_512PX_VIEWPORT;
+ return true;
+ }
+
+ return false;
+ }
+
+ // =========================================================================
+ // Viewport Modal Rendering & Clicks (Authentic RuneScape 2006 Stone Theme)
+ // =========================================================================
+
+ public static void drawViewportModal(Game game) {
+ if (!modalOpen) return;
+ PluginManager pm = PluginManager.get();
+ if (pm == null) return;
+ PluginGraphics g = pm.getGraphics();
+
+ int vw = getModalAreaWidth();
+ int vh = getModalAreaHeight();
+ int mx = Math.max(0, (vw - MODAL_WIDTH) / 2);
+ int my = Math.max(0, (vh - MODAL_HEIGHT) / 2);
+
+ // 1. Modal Authentic Stone Outer Frame & Background
+ boolean scriptsAvailable = PluginManager.isScriptsAvailable();
+ if (!scriptsAvailable && currentModalTab == 1) {
+ currentModalTab = 0;
+ }
+ drawStoneBox(g, mx, my, MODAL_WIDTH, MODAL_HEIGHT);
+
+ // 2. Centered Header in Authentic RuneScape Gold with drop shadow
+ String title = scriptsAvailable ? "RUNELITE PLUGIN & SCRIPT HUB" : "RUNELITE PLUGIN HUB";
+ if (game != null && game.aTextDrawingArea_1271 != null) {
+ game.aTextDrawingArea_1271.textCenterShadow(0xff981f, mx + (MODAL_WIDTH / 2), title, my + 19, true);
+ } else {
+ g.drawCenteredString(title, mx + (MODAL_WIDTH / 2), my + 19, 0xff981f);
+ }
+
+ // 3. Authentic Carved/Etched Stone Divider Line
+ drawEtchedLine(g, mx + 8, my + 27, MODAL_WIDTH - 16);
+
+ // 4. Authentic Red Stone Circular Close Button
+ int closeX = mx + MODAL_WIDTH - 25;
+ int closeY = my + 5;
+ drawCloseButton(g, closeX, closeY, 18);
+
+ // 5. Authentic RuneScape Full-Width Continuous Subtabs (100% width, 0 gaps)
+ int tabY = my + 28;
+ int tabH = 26;
+ int contentX = mx + 10;
+ int contentW = MODAL_WIDTH - 20;
+
+ int updateCount = PluginRepoClient.countUpdatesAvailable(pm);
+ String onlineLabel = updateCount > 0 ? "Online Repo (" + updateCount + ")" : "Online Repo";
+ int numTabs = scriptsAvailable ? 3 : 2;
+ int tabW = contentW / numTabs;
+ drawSubTab(g, contentX, tabY, tabW, tabH, "Plugins", currentModalTab == 0);
+ if (scriptsAvailable) {
+ drawSubTab(g, contentX + tabW, tabY, tabW, tabH, "Scripts", currentModalTab == 1);
+ drawSubTab(g, contentX + (tabW * 2), tabY, contentW - (tabW * 2), tabH, onlineLabel, currentModalTab == 2);
+ } else {
+ drawSubTab(g, contentX + tabW, tabY, contentW - tabW, tabH, onlineLabel, currentModalTab == 2);
+ }
+
+ // 6. Authentic Sunken Stone Content Well
+ int contentY = getContentAreaY();
+ int contentH = getContentAreaHeight();
+ drawStoneWell(g, contentX, contentY, contentW, contentH);
+
+ int maxScroll = getMaxScroll(pm);
+ clampScroll(pm);
+
+ int sbWidth = 16;
+ int sbX = mx + MODAL_WIDTH - 28;
+ int sbY = contentY + 2;
+ int sbH = contentH - 4;
+ int wellInnerX = contentX + 1;
+ int wellInnerW = (maxScroll > 0) ? (sbX - wellInnerX) : (contentW - 2);
+
+ if (currentModalTab == 0) {
+ drawSearchBar(g, wellInnerX + 4, contentY + 2, wellInnerW - 8, 20);
+ drawEtchedLine(g, wellInnerX, contentY + 25, wellInnerW);
+ try {
+ DrawingArea.setDrawingArea(contentY + contentH - 1, wellInnerX, wellInnerX + wellInnerW, contentY + 26);
+ drawPluginsList(g, pm, wellInnerX, contentY + 28 - scrollOffset, wellInnerW);
+ } finally {
+ DrawingArea.defaultDrawingAreaSize();
+ }
+ } else if (currentModalTab == 1) {
+ drawSearchBar(g, wellInnerX + 4, contentY + 2, wellInnerW - 8, 20);
+ drawEtchedLine(g, wellInnerX, contentY + 25, wellInnerW);
+ try {
+ DrawingArea.setDrawingArea(contentY + contentH - 1, wellInnerX, wellInnerX + wellInnerW, contentY + 26);
+ drawScriptsList(g, pm, wellInnerX, contentY + 28 - scrollOffset, wellInnerW);
+ } finally {
+ DrawingArea.defaultDrawingAreaSize();
+ }
+ } else if (currentModalTab == 2) {
+ drawSubTab(g, wellInnerX + 4, contentY + 2, 72, 22, "Plugins", currentRepoSubTab == 0);
+ drawSubTab(g, wellInnerX + 79, contentY + 2, 72, 22, "Scripts", currentRepoSubTab == 1);
+ int searchX = wellInnerX + 155;
+ int searchRight = (updateCount > 0) ? (wellInnerX + wellInnerW - 148) : (wellInnerX + wellInnerW - 68);
+ if (searchRight - searchX >= 60) {
+ drawSearchBar(g, searchX, contentY + 3, searchRight - searchX, 20);
+ }
+ if (updateCount > 0) {
+ String updAllLabel = PluginRepoClient.getBusyEntryId() != null ? "Updating..." : "Update All";
+ drawStoneButton(g, wellInnerX + wellInnerW - 144, contentY + 2, 76, 22, updAllLabel, 0x55d0ff, false);
+ }
+ String refreshLabel = PluginRepoClient.isLoading() ? "Loading..." : "Refresh";
+ drawStoneButton(g, wellInnerX + wellInnerW - 64, contentY + 2, 62, 22, refreshLabel, 0xffd700, false);
+ drawEtchedLine(g, wellInnerX, contentY + 25, wellInnerW);
+
+ try {
+ DrawingArea.setDrawingArea(contentY + contentH - 1, wellInnerX, wellInnerX + wellInnerW, contentY + 26);
+ drawRepoList(g, pm, wellInnerX, contentY + 28 - scrollOffset, wellInnerW);
+ } finally {
+ DrawingArea.defaultDrawingAreaSize();
+ }
+ } else if (currentModalTab == 3) {
+ if (configTarget instanceof ClientScript && !scriptsAvailable) {
+ configTarget = null;
+ }
+ if (configTarget != null) {
+ String name = (configTarget instanceof ClientPlugin) ? ((ClientPlugin) configTarget).getName()
+ : (configTarget instanceof ClientScript) ? ((ClientScript) configTarget).getName() : "Config";
+ String desc = (configTarget instanceof ClientPlugin) ? ((ClientPlugin) configTarget).getDescription()
+ : (configTarget instanceof ClientScript) ? ((ClientScript) configTarget).getDescription() : null;
+ int headerH = getConfigHeaderHeight();
+
+ g.drawStringBoldTruncated("Settings: " + name, wellInnerX + 8, contentY + 16, wellInnerW - 72, 0xff981f, true);
+ drawStoneButton(g, wellInnerX + wellInnerW - 58, contentY + 2, 56, 20, "< Back", 0xffd700, false);
+ if (desc != null && !desc.isEmpty()) {
+ g.drawStringTruncated(desc, wellInnerX + 8, contentY + 30, wellInnerW - 16, 0xa09484, false);
+ drawEtchedLine(g, wellInnerX, contentY + 36, wellInnerW);
+ } else {
+ drawEtchedLine(g, wellInnerX, contentY + 22, wellInnerW);
+ }
+
+ try {
+ DrawingArea.setDrawingArea(contentY + contentH - 1, wellInnerX, wellInnerX + wellInnerW, contentY + headerH);
+ drawConfigEditor(g, pm, wellInnerX, contentY + headerH + 2 - scrollOffset, wellInnerW);
+ } finally {
+ DrawingArea.defaultDrawingAreaSize();
+ }
+ drawConfigDropdownOverlay(g, pm, wellInnerX, wellInnerW, contentY, contentH, headerH);
+ } else {
+ currentModalTab = 0;
+ }
+ }
+
+ // 7. Authentic 2006Scape Scrollbar with Cache Sprites
+ if (maxScroll > 0) {
+ int totalHeight = sbH + maxScroll;
+ if (game != null && game.scrollBar1 != null && game.scrollBar2 != null) {
+ game.drawScrollThumb(sbH, scrollOffset, sbY, sbX, totalHeight);
+ } else {
+ // Fallback for tests or before cache sprite load
+ g.fillRect(sbX, sbY, sbWidth, sbH, 0x23201b, 255);
+ g.drawRect(sbX, sbY, sbWidth, sbH, 0x332d25);
+ int trackH = sbH - 32;
+ int thumbH = Math.max(8, (trackH * sbH) / totalHeight);
+ if (thumbH > trackH) thumbH = trackH;
+ int trackAvail = trackH - thumbH;
+ int thumbY = sbY + 16 + (trackAvail > 0 ? (scrollOffset * trackAvail) / maxScroll : 0);
+ if (thumbY < sbY + 16) thumbY = sbY + 16;
+ if (thumbY + thumbH > sbY + sbH - 16) thumbY = sbY + sbH - 16 - thumbH;
+ g.fillRect(sbX + 1, thumbY, sbWidth - 2, thumbH, 0x4d4233, 255);
+ g.drawVerticalLine(sbX + 1, thumbY, thumbH, 0x766654);
+ g.drawHorizontalLine(sbX + 1, thumbY, sbWidth - 2, 0x766654);
+ g.drawVerticalLine(sbX + sbWidth - 2, thumbY, thumbH, 0x332d25);
+ g.drawHorizontalLine(sbX + 1, thumbY + thumbH - 1, sbWidth - 2, 0x332d25);
+ }
+ }
+
+ // 8. Authentic Bank-Style Bottom Action Footer (Zero Gaps)
+ int footerY = my + MODAL_HEIGHT - 32;
+ int footerH = 26;
+ drawEtchedLine(g, contentX, footerY - 2, contentW);
+ int w1 = contentW / 2;
+ int w2 = contentW - w1;
+ drawSegmentedFooter(g, contentX, footerY, w1, w2, footerH);
+
+ // 9. Seal any 0x000000 (transparent) pixels inside modal bounds to prevent
+ // RSImageProducer from punching see-through holes through outlines and text drop shadows.
+ sealTransparency(mx, my, MODAL_WIDTH, MODAL_HEIGHT);
+ }
+
+ private static void sealTransparency(int mx, int my, int w, int h) {
+ int[] px = DrawingArea.pixels;
+ if (px == null) return;
+ int x0 = Math.max(0, mx);
+ int y0 = Math.max(0, my);
+ int x1 = Math.min(DrawingArea.width, mx + w);
+ int y1 = Math.min(DrawingArea.height, my + h);
+ for (int y = y0; y < y1; y++) {
+ int row = y * DrawingArea.width;
+ for (int x = x0; x < x1; x++) {
+ if (px[row + x] == 0) {
+ px[row + x] = 0x010101;
+ }
+ }
+ }
+ }
+
+ // =========================================================================
+ // Authentic RS Stone UI Primitive Renderers
+ // =========================================================================
+
+ private static void drawStoneBox(PluginGraphics g, int x, int y, int w, int h) {
+ // Outer black border (use 0x010101 so it is non-zero in drawing buffer)
+ g.drawRect(x, y, w, h, 0x010101);
+ // Bevel layer 1 (outer stone edge)
+ g.drawHorizontalLine(x + 1, y + 1, w - 2, 0x5c5040);
+ g.drawVerticalLine(x + 1, y + 1, h - 2, 0x5c5040);
+ g.drawHorizontalLine(x + 1, y + h - 2, w - 2, 0x1f1a14);
+ g.drawVerticalLine(x + w - 2, y + 1, h - 2, 0x1f1a14);
+ // Bevel layer 2 (inner stone frame)
+ g.drawHorizontalLine(x + 2, y + 2, w - 4, 0x483e32);
+ g.drawVerticalLine(x + 2, y + 2, h - 4, 0x483e32);
+ g.drawHorizontalLine(x + 2, y + h - 3, w - 4, 0x252019);
+ g.drawVerticalLine(x + w - 3, y + 2, h - 4, 0x252019);
+ // Authentic RS interface dark parchment/stone background
+ g.fillRect(x + 3, y + 3, w - 6, h - 6, 0x2a251e, 255);
+ }
+
+ private static void drawStoneWell(PluginGraphics g, int x, int y, int w, int h) {
+ // Outer dark stone border
+ g.drawRect(x, y, w, h, 0x383025);
+ // Recessed well fill
+ g.fillRect(x + 1, y + 1, w - 2, h - 2, 0x1f1b16, 255);
+ // Inner shadow on top and left
+ g.drawHorizontalLine(x + 1, y + 1, w - 2, 0x14110e);
+ g.drawVerticalLine(x + 1, y + 1, h - 2, 0x14110e);
+ // Inner subtle highlight on bottom and right
+ g.drawHorizontalLine(x + 1, y + h - 2, w - 2, 0x2e271f);
+ g.drawVerticalLine(x + w - 2, y + 1, h - 2, 0x2e271f);
+ }
+
+ private static void drawEtchedLine(PluginGraphics g, int x, int y, int w) {
+ // Carved stone groove: dark shadow line above, light highlight line below
+ g.drawHorizontalLine(x, y, w, 0x1a1510);
+ g.drawHorizontalLine(x, y + 1, w, 0x5c5040);
+ }
+
+ private static void drawCloseButton(PluginGraphics g, int x, int y, int size) {
+ // Authentic circular / beveled red stone close button
+ g.drawRect(x, y, size, size, 0x010101);
+ // Bevel highlight (top & left)
+ g.drawHorizontalLine(x + 1, y + 1, size - 2, 0xb82828);
+ g.drawVerticalLine(x + 1, y + 1, size - 2, 0xb82828);
+ // Bevel shadow (bottom & right)
+ g.drawHorizontalLine(x + 1, y + size - 2, size - 2, 0x480808);
+ g.drawVerticalLine(x + size - 2, y + 1, size - 2, 0x480808);
+ // Red stone fill
+ g.fillRect(x + 2, y + 2, size - 4, size - 4, 0x801414, 255);
+ // Crisp white 'X'
+ g.drawCenteredString("X", x + (size / 2), y + 13, 0xffffff);
+ }
+
+ private static void drawSubTab(PluginGraphics g, int x, int y, int w, int h, String label, boolean selected) {
+ g.drawRect(x, y, w, h, 0x010101);
+ if (selected) {
+ // Selected tab: lighter stone, connects seamlessly into content well below
+ g.fillRect(x + 1, y + 1, w - 2, h, 0x2a251e, 255);
+ g.drawHorizontalLine(x + 1, y + 1, w - 2, 0x6e604d);
+ g.drawVerticalLine(x + 1, y + 1, h - 1, 0x6e604d);
+ g.drawVerticalLine(x + w - 2, y + 1, h - 1, 0x1f1a14);
+ // Open seam at bottom
+ g.drawHorizontalLine(x + 1, y + h, w - 2, 0x2a251e);
+ g.drawStringBold(label, x + (w - g.getTextWidth(label)) / 2, y + (h / 2) + 4, 0xff981f, true);
+ } else {
+ // Unselected tab: recessed dark stone, closed bottom
+ g.fillRect(x + 1, y + 1, w - 2, h - 2, 0x1f1b16, 255);
+ g.drawHorizontalLine(x + 1, y + 1, w - 2, 0x3e3529);
+ g.drawVerticalLine(x + 1, y + 1, h - 2, 0x3e3529);
+ g.drawHorizontalLine(x + 1, y + h - 1, w - 2, 0x383025);
+ g.drawVerticalLine(x + w - 2, y + 1, h - 2, 0x16130f);
+ g.drawString(label, x + (w - g.getTextWidth(label)) / 2, y + (h / 2) + 4, 0x9c907e, false);
+ }
+ }
+
+ private static void drawSegmentedFooter(PluginGraphics g, int x, int y, int w1, int w2, int h) {
+ int totalW = w1 + w2;
+ g.drawRect(x, y, totalW, h, 0x010101);
+
+ // Segment 1 (Open Files)
+ g.fillRect(x + 1, y + 1, w1 - 1, h - 2, 0x3e3529, 255);
+ g.drawHorizontalLine(x + 1, y + 1, w1 - 1, 0x655542);
+ g.drawVerticalLine(x + 1, y + 1, h - 2, 0x655542);
+ g.drawHorizontalLine(x + 1, y + h - 2, w1 - 1, 0x1f1a14);
+ g.drawStringBold("Open Files", x + (w1 - g.getTextWidth("Open Files")) / 2, y + (h / 2) + 4, 0xff981f, true);
+
+ // Center divider line
+ g.drawVerticalLine(x + w1, y, h, 0x010101);
+
+ // Segment 2 (Reload Extensions)
+ g.fillRect(x + w1 + 1, y + 1, w2 - 2, h - 2, 0x3e3529, 255);
+ g.drawHorizontalLine(x + w1 + 1, y + 1, w2 - 2, 0x655542);
+ g.drawHorizontalLine(x + w1 + 1, y + h - 2, w2 - 2, 0x1f1a14);
+ g.drawVerticalLine(x + totalW - 2, y + 1, h - 2, 0x1f1a14);
+ g.drawStringBold("Reload Extensions", x + w1 + (w2 - g.getTextWidth("Reload Extensions")) / 2, y + (h / 2) + 4, 0xff981f, true);
+ }
+
+ private static void drawSegmentedToggleGroup(PluginGraphics g, int x, int y, int toggleW, int gearW, int h, boolean enabled, String toggleText) {
+ int totalW = toggleW + gearW;
+ g.drawRect(x, y, totalW, h, 0x010101);
+
+ // Toggle segment (left)
+ int fill = enabled ? 0x1b461f : 0x332c23;
+ int hl = enabled ? 0x347c3c : 0x52473a;
+ int sh = enabled ? 0x0f2611 : 0x181410;
+ int txtColor = enabled ? 0x76ff76 : 0x9c907e;
+ g.fillRect(x + 1, y + 1, toggleW - 1, h - 2, fill, 255);
+ g.drawHorizontalLine(x + 1, y + 1, toggleW - 1, hl);
+ g.drawVerticalLine(x + 1, y + 1, h - 2, hl);
+ g.drawHorizontalLine(x + 1, y + h - 2, toggleW - 1, sh);
+ g.drawStringBold(toggleText, x + (toggleW - g.getTextWidth(toggleText)) / 2, y + (h / 2) + 4, txtColor, true);
+
+ // Center divider line
+ g.drawVerticalLine(x + toggleW, y, h, 0x010101);
+
+ // CFG segment (right)
+ g.fillRect(x + toggleW + 1, y + 1, gearW - 2, h - 2, 0x3e3529, 255);
+ g.drawHorizontalLine(x + toggleW + 1, y + 1, gearW - 2, 0x655542);
+ g.drawHorizontalLine(x + toggleW + 1, y + h - 2, gearW - 2, 0x1f1a14);
+ g.drawVerticalLine(x + totalW - 2, y + 1, h - 2, 0x1f1a14);
+ g.drawStringBold("CFG", x + toggleW + (gearW - g.getTextWidth("CFG")) / 2, y + (h / 2) + 4, 0xffd700, true);
+ }
+
+ private static void drawSegmentedScriptGroup(PluginGraphics g, int x, int y, int stopW, int pauseW, int gearW, int h, boolean paused) {
+ int totalW = stopW + pauseW + gearW;
+ g.drawRect(x, y, totalW, h, 0x010101);
+
+ // Stop segment
+ g.fillRect(x + 1, y + 1, stopW - 1, h - 2, 0x5a1818, 255);
+ g.drawHorizontalLine(x + 1, y + 1, stopW - 1, 0x8a2626);
+ g.drawVerticalLine(x + 1, y + 1, h - 2, 0x8a2626);
+ g.drawHorizontalLine(x + 1, y + h - 2, stopW - 1, 0x300c0c);
+ g.drawStringBold("STOP", x + (stopW - g.getTextWidth("STOP")) / 2, y + (h / 2) + 4, 0xff7676, true);
+
+ // Divider 1
+ g.drawVerticalLine(x + stopW, y, h, 0x010101);
+
+ // Pause segment
+ g.fillRect(x + stopW + 1, y + 1, pauseW - 1, h - 2, 0x544014, 255);
+ g.drawHorizontalLine(x + stopW + 1, y + 1, pauseW - 1, 0x866620);
+ g.drawHorizontalLine(x + stopW + 1, y + h - 2, pauseW - 1, 0x2c220a);
+ String pauseTxt = paused ? "RES" : "PAUS";
+ g.drawStringBold(pauseTxt, x + stopW + (pauseW - g.getTextWidth(pauseTxt)) / 2, y + (h / 2) + 4, 0xffd700, true);
+
+ // Divider 2
+ g.drawVerticalLine(x + stopW + pauseW, y, h, 0x010101);
+
+ // CFG segment
+ g.fillRect(x + stopW + pauseW + 1, y + 1, gearW - 2, h - 2, 0x3e3529, 255);
+ g.drawHorizontalLine(x + stopW + pauseW + 1, y + 1, gearW - 2, 0x655542);
+ g.drawHorizontalLine(x + stopW + pauseW + 1, y + h - 2, gearW - 2, 0x1f1a14);
+ g.drawVerticalLine(x + totalW - 2, y + 1, h - 2, 0x1f1a14);
+ g.drawStringBold("CFG", x + stopW + pauseW + (gearW - g.getTextWidth("CFG")) / 2, y + (h / 2) + 4, 0xffd700, true);
+ }
+
+ private static void drawStoneButton(PluginGraphics g, int x, int y, int w, int h, String label, int textRgb, boolean pressed) {
+ g.drawRect(x, y, w, h, 0x010101);
+ int fill = pressed ? 0x2f2820 : 0x3e3529;
+ int hl = pressed ? 0x1f1a14 : 0x655542;
+ int sh = pressed ? 0x655542 : 0x1f1a14;
+ g.fillRect(x + 1, y + 1, w - 2, h - 2, fill, 255);
+ g.drawHorizontalLine(x + 1, y + 1, w - 2, hl);
+ g.drawVerticalLine(x + 1, y + 1, h - 2, hl);
+ g.drawHorizontalLine(x + 1, y + h - 2, w - 2, sh);
+ g.drawVerticalLine(x + w - 2, y + 1, h - 2, sh);
+ g.drawStringBold(label, x + (w - g.getTextWidth(label)) / 2, y + (h / 2) + 4, textRgb, true);
+ }
+
+ private static void drawColoredButton(PluginGraphics g, int x, int y, int w, int h, String label, int fillRgb, int borderRgb, int shadowRgb, int textRgb) {
+ g.drawRect(x, y, w, h, 0x010101);
+ g.fillRect(x + 1, y + 1, w - 2, h - 2, fillRgb, 255);
+ g.drawHorizontalLine(x + 1, y + 1, w - 2, borderRgb);
+ g.drawVerticalLine(x + 1, y + 1, h - 2, borderRgb);
+ g.drawHorizontalLine(x + 1, y + h - 2, w - 2, shadowRgb);
+ g.drawVerticalLine(x + w - 2, y + 1, h - 2, shadowRgb);
+ g.drawStringBold(label, x + (w - g.getTextWidth(label)) / 2, y + (h / 2) + 4, textRgb, true);
+ }
+
+ // =========================================================================
+ // Content Lists (Plugins, Scripts, Config)
+ // =========================================================================
+
+ private static void drawSearchBar(PluginGraphics g, int x, int y, int w, int h) {
+ int bg = searchFocused ? 0x1a1510 : 0x16120d;
+ int border = searchFocused ? 0xffd700 : 0x453b2e;
+ g.fillRect(x, y, w, h, bg, 255);
+ g.drawRect(x, y, w, h, border);
+ boolean hasQuery = searchQuery != null && !searchQuery.isEmpty();
+ int textMaxW = hasQuery ? (w - 28) : (w - 12);
+ if (hasQuery) {
+ String display = searchFocused ? (searchQuery + "_") : searchQuery;
+ g.drawStringTruncated(display, x + 6, y + 14, textMaxW, 0xffffff, false);
+ int clearX = x + w - 20;
+ g.fillRect(clearX, y + 1, 19, h - 2, 0x352c22, 255);
+ g.drawString("X", clearX + 6, y + 14, 0xff9090, false);
+ } else {
+ String placeholder = searchFocused ? "_" : "Search...";
+ int col = searchFocused ? 0xffffff : 0x807464;
+ g.drawStringTruncated(placeholder, x + 6, y + 14, textMaxW, col, false);
+ }
+ }
+
+ private static void drawPluginsList(PluginGraphics g, PluginManager pm, int x, int y, int w) {
+ List list = getFilteredPlugins(pm);
+ int rowY = y;
+ int i = 0;
+ if (list != null && !list.isEmpty()) {
+ for (; i < list.size(); i++) {
+ if (rowY + 36 >= DrawingArea.topY && rowY <= DrawingArea.bottomY) {
+ ClientPlugin p = list.get(i);
+ int rowFill = (i % 2 == 0) ? 0x26211b : 0x201b15;
+ g.fillRect(x, rowY, w, 38, rowFill, 255);
+ g.drawHorizontalLine(x, rowY, w, 0x16130f);
+ g.drawHorizontalLine(x, rowY + 37, w, 0x322b22);
+
+ // Seamless Segmented Toggle + CFG Control (docked flush against row borders and right edge)
+ int groupW = 84;
+ int groupX = x + w - groupW;
+ int btnY = rowY + 1;
+ int maxTextW = groupX - (x + 10) - 8;
+
+ // Plugin Name and Description (bounded with RuneLite-style ellipsis truncation)
+ g.drawStringBoldTruncated(p.getName() + " v" + p.getVersion(), x + 10, rowY + 16, maxTextW, 0xffffff, true);
+ g.drawStringTruncated(p.getDescription(), x + 10, rowY + 30, maxTextW, 0xa09484, false);
+
+ drawSegmentedToggleGroup(g, groupX, btnY, 50, 34, 36, p.isEnabled(), p.isEnabled() ? "ON" : "OFF");
+ }
+ rowY += 38;
+ }
+ } else if (searchQuery != null && !searchQuery.isEmpty()) {
+ g.drawString("No matching plugins.", x + 10, y + 20, 0xa09484, false);
+ return;
+ }
+ // Fill remaining well area with alternating empty rows
+ while (rowY <= DrawingArea.bottomY) {
+ int rowFill = (i % 2 == 0) ? 0x26211b : 0x201b15;
+ g.fillRect(x, rowY, w, 38, rowFill, 255);
+ g.drawHorizontalLine(x, rowY, w, 0x16130f);
+ g.drawHorizontalLine(x, rowY + 37, w, 0x322b22);
+ rowY += 38;
+ i++;
+ }
+ }
+
+ private static void drawScriptsList(PluginGraphics g, PluginManager pm, int x, int y, int w) {
+ List list = getFilteredScripts(pm);
+ int rowY = y;
+ int i = 0;
+ if (list != null && !list.isEmpty()) {
+ for (; i < list.size(); i++) {
+ if (rowY + 36 >= DrawingArea.topY && rowY <= DrawingArea.bottomY) {
+ ClientScript s = list.get(i);
+ int rowFill = (i % 2 == 0) ? 0x26211b : 0x201b15;
+ g.fillRect(x, rowY, w, 38, rowFill, 255);
+ g.drawHorizontalLine(x, rowY, w, 0x16130f);
+ g.drawHorizontalLine(x, rowY + 37, w, 0x322b22);
+
+ // Seamless Segmented Controls (docked flush against row borders and right edge)
+ int btnY = rowY + 1;
+ int groupW = s.isRunning() ? (44 + 44 + 34) : (50 + 34);
+ int groupX = x + w - groupW;
+ int maxTextW = groupX - (x + 10) - 8;
+
+ // Script Name and status (bounded with RuneLite-style ellipsis truncation)
+ g.drawStringBoldTruncated(s.getName() + " v" + s.getVersion(), x + 10, rowY + 16, maxTextW, 0xffffff, true);
+ g.drawStringTruncated(s.getDescription() + " [" + s.getStatus() + "]", x + 10, rowY + 30, maxTextW, s.isRunning() ? 0x60e080 : 0xa09484, false);
+
+ if (s.isRunning()) {
+ drawSegmentedScriptGroup(g, groupX, btnY, 44, 44, 34, 36, s.isPaused());
+ } else {
+ drawSegmentedToggleGroup(g, groupX, btnY, 50, 34, 36, false, "START");
+ }
+ }
+ rowY += 38;
+ }
+ } else if (searchQuery != null && !searchQuery.isEmpty()) {
+ g.drawString("No matching scripts.", x + 10, y + 20, 0xa09484, false);
+ return;
+ }
+ // Fill remaining well area with alternating empty rows
+ while (rowY <= DrawingArea.bottomY) {
+ int rowFill = (i % 2 == 0) ? 0x26211b : 0x201b15;
+ g.fillRect(x, rowY, w, 38, rowFill, 255);
+ g.drawHorizontalLine(x, rowY, w, 0x16130f);
+ g.drawHorizontalLine(x, rowY + 37, w, 0x322b22);
+ rowY += 38;
+ i++;
+ }
+ }
+
+ private static List getFilteredRepoEntries() {
+ List all = PluginRepoClient.getEntries();
+ List filtered = new java.util.ArrayList<>();
+ if (all == null) return filtered;
+ boolean wantPlugin = (currentRepoSubTab == 0);
+ for (PluginRepoClient.RepoEntry entry : all) {
+ boolean isPlugin = "plugin".equalsIgnoreCase(entry.type);
+ if (isPlugin == wantPlugin && matchesSearch(entry.name, entry.description, entry.author)) {
+ filtered.add(entry);
+ }
+ }
+ return filtered;
+ }
+
+ private static void drawRepoList(PluginGraphics g, PluginManager pm, int x, int y, int w) {
+ if (PluginRepoClient.isLoading() && PluginRepoClient.getEntries().isEmpty()) {
+ g.drawString("Fetching online repository index...", x + 10, y + 20, 0xa09484, false);
+ return;
+ }
+ String err = PluginRepoClient.getLastError();
+ List allEntries = PluginRepoClient.getEntries();
+ if ((allEntries == null || allEntries.isEmpty()) && err != null) {
+ g.drawStringTruncated("Repo error: " + err, x + 10, y + 20, w - 20, 0xff6060, false);
+ return;
+ }
+ List entries = getFilteredRepoEntries();
+ if (entries.isEmpty()) {
+ String emptyMsg = (searchQuery != null && !searchQuery.isEmpty())
+ ? "No matching entries."
+ : ((currentRepoSubTab == 0)
+ ? "No plugins found in online repository."
+ : "No scripts found in online repository.");
+ g.drawString(emptyMsg, x + 10, y + 20, 0xa09484, false);
+ return;
+ }
+
+ int rowY = y;
+ if (err != null && !err.isEmpty()) {
+ g.fillRect(x, rowY, w, 20, 0x3b1818, 255);
+ g.drawStringTruncated(err, x + 8, rowY + 14, w - 16, 0xff7070, false);
+ rowY += 22;
+ }
+ int i = 0;
+ String busyId = PluginRepoClient.getBusyEntryId();
+ for (; i < entries.size(); i++) {
+ if (rowY + 36 >= DrawingArea.topY && rowY <= DrawingArea.bottomY) {
+ PluginRepoClient.RepoEntry entry = entries.get(i);
+ int rowFill = (i % 2 == 0) ? 0x26211b : 0x201b15;
+ g.fillRect(x, rowY, w, 38, rowFill, 255);
+ g.drawHorizontalLine(x, rowY, w, 0x16130f);
+ g.drawHorizontalLine(x, rowY + 37, w, 0x322b22);
+
+ int btnW = 74;
+ int btnX = x + w - btnW;
+ int maxTextW = btnX - (x + 10) - 8;
+
+ String entryKey = entry.id.isEmpty() ? entry.name : entry.id;
+ boolean isBusy = busyId != null && busyId.equals(entryKey);
+ PluginRepoClient.InstallStatus status = PluginRepoClient.getInstallStatus(entry, pm);
+ String verText = "v" + entry.version;
+ if (status == PluginRepoClient.InstallStatus.UPDATE_AVAILABLE) {
+ SemVer installedVer = PluginRepoClient.findInstalledVersion(entry, pm);
+ if (installedVer != null) {
+ verText = "v" + installedVer + " -> v" + entry.version;
+ }
+ }
+ String title = entry.name + " " + verText + " (" + entry.author + ")";
+ g.drawStringBoldTruncated(title, x + 10, rowY + 16, maxTextW, 0xffffff, true);
+ g.drawStringTruncated(entry.description, x + 10, rowY + 30, maxTextW, 0xa09484, false);
+ String btnLabel;
+ int btnColor;
+ if (isBusy) {
+ btnLabel = "...";
+ btnColor = 0xa09484;
+ } else if (status == PluginRepoClient.InstallStatus.INCOMPATIBLE) {
+ btnLabel = "API " + entry.minApi;
+ btnColor = 0xff6060;
+ } else if (status == PluginRepoClient.InstallStatus.UPDATE_AVAILABLE) {
+ btnLabel = "Update";
+ btnColor = 0x55d0ff;
+ } else if (status == PluginRepoClient.InstallStatus.UP_TO_DATE) {
+ btnLabel = "Remove";
+ btnColor = 0xe06060;
+ } else {
+ btnLabel = "Install";
+ btnColor = 0x60e080;
+ }
+ drawStoneButton(g, btnX, rowY + 1, btnW, 36, btnLabel, btnColor, false);
+ }
+ rowY += 38;
+ }
+ while (rowY <= DrawingArea.bottomY) {
+ int rowFill = (i % 2 == 0) ? 0x26211b : 0x201b15;
+ g.fillRect(x, rowY, w, 38, rowFill, 255);
+ g.drawHorizontalLine(x, rowY, w, 0x16130f);
+ g.drawHorizontalLine(x, rowY + 37, w, 0x322b22);
+ rowY += 38;
+ i++;
+ }
+ }
+
+ private static void drawConfigTargetSelector(PluginGraphics g, PluginManager pm, int x, int y, int w) {
+ List list = pm.getPlugins();
+ int rowY = y;
+ int i = 0;
+ if (list != null) {
+ for (; i < list.size(); i++) {
+ if (rowY + 36 >= DrawingArea.topY && rowY <= DrawingArea.bottomY) {
+ ClientPlugin p = list.get(i);
+ int rowFill = (i % 2 == 0) ? 0x26211b : 0x201b15;
+ g.fillRect(x, rowY, w, 38, rowFill, 255);
+ g.drawHorizontalLine(x, rowY, w, 0x16130f);
+ g.drawHorizontalLine(x, rowY + 37, w, 0x322b22);
+
+ int btnW = 74;
+ int btnX = x + w - btnW;
+ int maxTextW = btnX - (x + 10) - 8;
+
+ g.drawStringBoldTruncated(p.getName() + " v" + p.getVersion(), x + 10, rowY + 16, maxTextW, 0xffffff, true);
+ g.drawStringTruncated(p.getDescription(), x + 10, rowY + 30, maxTextW, 0xa09484, false);
+
+ drawStoneButton(g, btnX, rowY + 1, btnW, 36, "Configure", 0xffd700, false);
+ }
+ rowY += 38;
+ }
+ }
+ // Fill remaining well area with alternating empty rows
+ while (rowY <= DrawingArea.bottomY) {
+ int rowFill = (i % 2 == 0) ? 0x26211b : 0x201b15;
+ g.fillRect(x, rowY, w, 38, rowFill, 255);
+ g.drawHorizontalLine(x, rowY, w, 0x16130f);
+ g.drawHorizontalLine(x, rowY + 37, w, 0x322b22);
+ rowY += 38;
+ i++;
+ }
+ }
+
+ private static void drawConfigEditor(PluginGraphics g, PluginManager pm, int x, int y, int w) {
+ List items = getVisibleConfigItems(pm, configTarget);
+
+ if (items == null || items.isEmpty()) {
+ g.drawString("No configurable settings available.", x + 8, y + 16, 0xa09484, false);
+ return;
+ }
+
+ int rowY = y;
+ for (int i = 0; i < items.size(); i++) {
+ if (rowY + 28 >= DrawingArea.topY && rowY <= DrawingArea.bottomY) {
+ PluginConfigItem item = items.get(i);
+ int rowFill = (i % 2 == 0) ? 0x26211b : 0x201b15;
+ g.fillRect(x, rowY, w, 32, rowFill, 255);
+ g.drawHorizontalLine(x, rowY, w, 0x16130f);
+ g.drawHorizontalLine(x, rowY + 31, w, 0x322b22);
+
+ int maxLabelW = (item.getType() == PluginConfigItem.Type.BOOLEAN) ? (w - 60 - 20)
+ : (item.getType() == PluginConfigItem.Type.INTEGER) ? (w - 126 - 20)
+ : (item.getType() == PluginConfigItem.Type.CHOICE) ? (w - DROPDOWN_WIDTH - 20) : (w - 180);
+ g.drawStringTruncated(item.getLabel(), x + 10, rowY + 20, maxLabelW, 0xffffff, false);
+
+ if (item.getType() == PluginConfigItem.Type.BOOLEAN) {
+ boolean currentVal = pm.getConfigBoolean(configTarget, item);
+ int btnW = 60;
+ int btnX = x + w - btnW;
+ int btnY = rowY + 1;
+ if (currentVal) {
+ drawColoredButton(g, btnX, btnY, btnW, 30, "ON", 0x1b461f, 0x347c3c, 0x0f2611, 0x76ff76);
+ } else {
+ drawColoredButton(g, btnX, btnY, btnW, 30, "OFF", 0x332c23, 0x52473a, 0x181410, 0x9c907e);
+ }
+ } else if (item.getType() == PluginConfigItem.Type.INTEGER) {
+ int currentVal = pm.getConfigInt(configTarget, item);
+ int stepperW = 126;
+ int stepX = x + w - stepperW;
+ int btnY = rowY + 1;
+ int btnH = 30;
+
+ // Segmented Stepper [ - | 1000000 | + ] (flush, zero gaps, 126px width)
+ g.drawRect(stepX, btnY, stepperW, btnH, 0x010101);
+
+ // Minus [-]
+ g.fillRect(stepX + 1, btnY + 1, 27, btnH - 2, 0x3e3529, 255);
+ g.drawHorizontalLine(stepX + 1, btnY + 1, 27, 0x655542);
+ g.drawVerticalLine(stepX + 1, btnY + 1, btnH - 2, 0x655542);
+ g.drawHorizontalLine(stepX + 1, btnY + btnH - 2, 27, 0x1f1a14);
+ g.drawStringBold("-", stepX + 11, btnY + 19, 0xffffff, true);
+
+ // Divider 1
+ g.drawVerticalLine(stepX + 28, btnY, btnH, 0x010101);
+
+ // Value display (68px wide compartment, comfortably fits up to 10 digits without overlap)
+ g.fillRect(stepX + 29, btnY + 1, 68, btnH - 2, 0x2a251e, 255);
+ g.drawCenteredString(String.valueOf(currentVal), stepX + 63, btnY + 19, 0xffd700);
+
+ // Divider 2
+ g.drawVerticalLine(stepX + 97, btnY, btnH, 0x010101);
+
+ // Plus [+]
+ g.fillRect(stepX + 98, btnY + 1, 27, btnH - 2, 0x3e3529, 255);
+ g.drawHorizontalLine(stepX + 98, btnY + 1, 27, 0x655542);
+ g.drawHorizontalLine(stepX + 98, btnY + btnH - 2, 27, 0x1f1a14);
+ g.drawVerticalLine(stepX + stepperW - 2, btnY + 1, btnH - 2, 0x1f1a14);
+ g.drawStringBold("+", stepX + 107, btnY + 19, 0xffffff, true);
+ } else if (item.getType() == PluginConfigItem.Type.CHOICE) {
+ String currentVal = String.valueOf(pm.getConfigValue(configTarget, item));
+ int dropX = x + w - DROPDOWN_WIDTH;
+ int btnY = rowY + 1;
+ int btnH = 30;
+ boolean isOpen = item.getKey().equals(openDropdownKey);
+
+ g.drawRect(dropX, btnY, DROPDOWN_WIDTH, btnH, 0x010101);
+ g.fillRect(dropX + 1, btnY + 1, DROPDOWN_WIDTH - 25, btnH - 2, isOpen ? 0x352e25 : 0x2a251e, 255);
+ g.drawHorizontalLine(dropX + 1, btnY + 1, DROPDOWN_WIDTH - 2, 0x52473a);
+ g.drawVerticalLine(dropX + 1, btnY + 1, btnH - 2, 0x52473a);
+ g.drawStringTruncated(currentVal, dropX + 8, btnY + 19, DROPDOWN_WIDTH - 34, 0xffd700, true);
+
+ // Arrow compartment [v] / [^]
+ int arrowX = dropX + DROPDOWN_WIDTH - 24;
+ g.drawVerticalLine(arrowX, btnY, btnH, 0x010101);
+ g.fillRect(arrowX + 1, btnY + 1, 22, btnH - 2, 0x3e3529, 255);
+ g.drawHorizontalLine(arrowX + 1, btnY + 1, 22, 0x655542);
+ g.drawStringBold(isOpen ? "^" : "v", arrowX + 8, btnY + 19, 0xffffff, true);
+ } else {
+ g.drawString("(Edit in .properties or chat)", x + w - 170, rowY + 20, 0xa09484, false);
+ }
+ }
+ rowY += 32;
+ }
+ // Fill remaining well area with alternating empty rows
+ int extraIdx = items.size();
+ while (rowY <= DrawingArea.bottomY) {
+ int rowFill = (extraIdx % 2 == 0) ? 0x26211b : 0x201b15;
+ g.fillRect(x, rowY, w, 32, rowFill, 255);
+ g.drawHorizontalLine(x, rowY, w, 0x16130f);
+ g.drawHorizontalLine(x, rowY + 31, w, 0x322b22);
+ rowY += 32;
+ extraIdx++;
+ }
+ }
+
+ private static void drawConfigDropdownOverlay(PluginGraphics g, PluginManager pm, int wellInnerX, int wellInnerW, int contentY, int contentH, int headerH) {
+ int[] b = getOpenDropdownBounds(pm);
+ if (b == null) return;
+ List items = getVisibleConfigItems(pm, configTarget);
+ if (items == null || b[4] >= items.size()) return;
+ PluginConfigItem item = items.get(b[4]);
+ String[] choices = item.getChoices();
+ if (choices == null || choices.length == 0) return;
+
+ int dropX = b[0];
+ int dropY = b[1];
+ int dropW = b[2];
+ int dropH = b[3];
+ int maxDropScroll = Math.max(0, choices.length * DROPDOWN_ROW_H + 2 - dropH);
+ if (dropdownScrollOffset > maxDropScroll) dropdownScrollOffset = maxDropScroll;
+ if (dropdownScrollOffset < 0) dropdownScrollOffset = 0;
+
+ g.fillRect(dropX, dropY, dropW, dropH, 0x1e1914, 248);
+ g.drawRect(dropX, dropY, dropW, dropH, 0x655542);
+
+ String currentVal = String.valueOf(pm.getConfigValue(configTarget, item));
+ int listW = (maxDropScroll > 0) ? (dropW - 8) : (dropW - 2);
+ try {
+ DrawingArea.setDrawingArea(dropY + dropH - 1, dropX + 1, dropX + 1 + listW, dropY + 1);
+ int optY = dropY + 1 - dropdownScrollOffset;
+ for (int ci = 0; ci < choices.length; ci++) {
+ if (optY + DROPDOWN_ROW_H >= dropY && optY <= dropY + dropH) {
+ boolean selected = choices[ci].equalsIgnoreCase(currentVal);
+ int bg = selected ? 0x3b3226 : ((ci % 2 == 0) ? 0x241f19 : 0x1e1914);
+ g.fillRect(dropX + 1, optY, listW, DROPDOWN_ROW_H, bg, 255);
+ g.drawHorizontalLine(dropX + 1, optY + DROPDOWN_ROW_H - 1, listW, 0x14100c);
+ g.drawStringTruncated(choices[ci], dropX + 8, optY + 15, listW - 14, selected ? 0xffd700 : 0xffffff, selected);
+ }
+ optY += DROPDOWN_ROW_H;
+ }
+ } finally {
+ DrawingArea.defaultDrawingAreaSize();
+ }
+
+ if (maxDropScroll > 0) {
+ int trackX = dropX + dropW - 6;
+ int trackY = dropY + 2;
+ int trackH = dropH - 4;
+ g.fillRect(trackX, trackY, 4, trackH, 0x14100c, 255);
+ int thumbH = Math.max(10, (trackH * dropH) / (choices.length * DROPDOWN_ROW_H + 2));
+ int avail = Math.max(0, trackH - thumbH);
+ int thumbY = trackY + (avail * dropdownScrollOffset) / maxDropScroll;
+ g.fillRect(trackX, thumbY, 4, thumbH, 0x766654, 255);
+ }
+ }
+
+ // =========================================================================
+ // Modal Click Handling
+ // =========================================================================
+
+ public static boolean handleModalClick(int clickX, int clickY) {
+ if (!modalOpen) return false;
+ PluginManager pm = PluginManager.get();
+ if (pm == null) return false;
+
+ if (wasDrag) {
+ wasDrag = false;
+ return true;
+ }
+
+ int cx = toLocalX(clickX);
+ int cy = toLocalY(clickY);
+
+ int vw = getModalAreaWidth();
+ int vh = getModalAreaHeight();
+ int mx = Math.max(0, (vw - MODAL_WIDTH) / 2);
+ int my = Math.max(0, (vh - MODAL_HEIGHT) / 2);
+
+ // Click outside modal closes it
+ if (cx < mx || cx > mx + MODAL_WIDTH || cy < my || cy > my + MODAL_HEIGHT) {
+ closeModal();
+ return true;
+ }
+
+ // Close button [X]
+ int closeX = mx + MODAL_WIDTH - 25;
+ int closeY = my + 5;
+ if (cx >= closeX - 4 && cx <= closeX + 22 && cy >= closeY - 4 && cy <= closeY + 22) {
+ closeModal();
+ return true;
+ }
+
+ // Top Full-Width Tabs (0 gaps)
+ int tabY = my + 28;
+ int contentX = mx + 10;
+ int contentW = MODAL_WIDTH - 20;
+ boolean scriptsAvailable = PluginManager.isScriptsAvailable();
+ int numTabs = scriptsAvailable ? 3 : 2;
+ int tabW = contentW / numTabs;
+
+ if (cy >= tabY && cy <= tabY + 26) {
+ searchFocused = false;
+ if (scriptsAvailable) {
+ // Tab 0: Plugins
+ if (cx >= contentX && cx < contentX + tabW) {
+ currentModalTab = 0;
+ scrollOffset = 0;
+ return true;
+ }
+ // Tab 1: Scripts
+ if (cx >= contentX + tabW && cx < contentX + (tabW * 2)) {
+ currentModalTab = 1;
+ scrollOffset = 0;
+ return true;
+ }
+ // Tab 2: Online Repo
+ if (cx >= contentX + (tabW * 2) && cx <= contentX + contentW) {
+ currentModalTab = 2;
+ configTarget = null;
+ scrollOffset = 0;
+ PluginRepoClient.ensureLoaded();
+ return true;
+ }
+ } else {
+ // Tab 0: Plugins
+ if (cx >= contentX && cx < contentX + tabW) {
+ currentModalTab = 0;
+ scrollOffset = 0;
+ return true;
+ }
+ // Tab 2: Online Repo
+ if (cx >= contentX + tabW && cx <= contentX + contentW) {
+ currentModalTab = 2;
+ configTarget = null;
+ scrollOffset = 0;
+ PluginRepoClient.ensureLoaded();
+ return true;
+ }
+ }
+ }
+
+ // Bottom Footer Action Buttons (Segmented Full-Width, 0 gaps)
+ int footerY = my + MODAL_HEIGHT - 32;
+ int footerH = 26;
+ int w1 = contentW / 2;
+ if (cy >= footerY && cy <= footerY + footerH && cx >= contentX && cx <= contentX + contentW) {
+ // Left Half: Open Files
+ if (cx < contentX + w1) {
+ AndroidHooks.openScriptsFolder();
+ if (pm.getContext() != null) {
+ pm.getContext().sendClientMessage(scriptsAvailable ? "Opened plugins & scripts directory." : "Opened plugins directory.");
+ }
+ return true;
+ }
+ // Right Half: Reload Extensions
+ else {
+ pm.reloadExternal();
+ scrollOffset = 0;
+ if (pm.getContext() != null) {
+ pm.getContext().sendClientMessage(scriptsAvailable ? "Reloaded external plugins and scripts." : "Reloaded external plugins.");
+ }
+ return true;
+ }
+ }
+
+ int contentY = getContentAreaY();
+ int contentH = getContentAreaHeight();
+ int maxScroll = getMaxScroll(pm);
+ int sbX = mx + MODAL_WIDTH - 28;
+ int wellInnerX = contentX + 1;
+ int wellInnerW = (maxScroll > 0) ? (sbX - wellInnerX) : (contentW - 2);
+
+ // Scrollbar click / tap jump
+ if (maxScroll > 0 && isScrollBarAt(clickX, clickY)) {
+ handleScrollBarJump(pm, cy, maxScroll);
+ return true;
+ }
+
+ if (currentModalTab == 0) {
+ if (handleSearchBarClick(cx, cy, wellInnerX + 4, contentY + 2, wellInnerW - 8, 20)) {
+ return true;
+ }
+ searchFocused = false;
+ if (cy < contentY + 26 || cy > contentY + contentH) {
+ return true;
+ }
+ List list = getFilteredPlugins(pm);
+ int rowY = contentY + 28 - scrollOffset;
+ for (ClientPlugin p : list) {
+ if (rowY + 36 >= contentY + 26 && rowY <= contentY + contentH) {
+ int groupW = 84;
+ int groupX = wellInnerX + wellInnerW - groupW;
+ int btnY = rowY + 1;
+ int btnH = 36;
+
+ // Toggle segment
+ if (cx >= groupX && cx < groupX + 50 && cy >= btnY && cy <= btnY + btnH) {
+ pm.togglePlugin(p);
+ return true;
+ }
+ // CFG segment
+ if (cx >= groupX + 50 && cx <= groupX + groupW && cy >= btnY && cy <= btnY + btnH) {
+ configTarget = p;
+ configReturnTab = 0;
+ currentModalTab = 3;
+ scrollOffset = 0;
+ return true;
+ }
+ }
+ rowY += 38;
+ }
+ } else if (currentModalTab == 1) {
+ if (handleSearchBarClick(cx, cy, wellInnerX + 4, contentY + 2, wellInnerW - 8, 20)) {
+ return true;
+ }
+ searchFocused = false;
+ if (cy < contentY + 26 || cy > contentY + contentH) {
+ return true;
+ }
+ List list = getFilteredScripts(pm);
+ int rowY = contentY + 28 - scrollOffset;
+ for (ClientScript s : list) {
+ if (rowY + 36 >= contentY + 26 && rowY <= contentY + contentH) {
+ int btnY = rowY + 1;
+ int btnH = 36;
+ if (s.isRunning()) {
+ int groupW = 44 + 44 + 34; // 122px
+ int groupX = wellInnerX + wellInnerW - groupW;
+ // STOP
+ if (cx >= groupX && cx < groupX + 44 && cy >= btnY && cy <= btnY + btnH) {
+ pm.stopScript(s);
+ return true;
+ }
+ // PAUSE / RESUME
+ if (cx >= groupX + 44 && cx < groupX + 88 && cy >= btnY && cy <= btnY + btnH) {
+ pm.pauseResumeScript(s);
+ return true;
+ }
+ // CFG
+ if (cx >= groupX + 88 && cx <= groupX + groupW && cy >= btnY && cy <= btnY + btnH) {
+ configTarget = s;
+ configReturnTab = 1;
+ currentModalTab = 3;
+ scrollOffset = 0;
+ return true;
+ }
+ } else {
+ int groupW = 50 + 34; // 84px
+ int groupX = wellInnerX + wellInnerW - groupW;
+ // START
+ if (cx >= groupX && cx < groupX + 50 && cy >= btnY && cy <= btnY + btnH) {
+ pm.startScript(s);
+ return true;
+ }
+ // CFG
+ if (cx >= groupX + 50 && cx <= groupX + groupW && cy >= btnY && cy <= btnY + btnH) {
+ configTarget = s;
+ configReturnTab = 1;
+ currentModalTab = 3;
+ scrollOffset = 0;
+ return true;
+ }
+ }
+ }
+ rowY += 38;
+ }
+ } else if (currentModalTab == 2) {
+ int searchX = wellInnerX + 155;
+ int searchRight = (PluginRepoClient.countUpdatesAvailable(pm) > 0)
+ ? (wellInnerX + wellInnerW - 148)
+ : (wellInnerX + wellInnerW - 68);
+ if (searchRight - searchX >= 60 && handleSearchBarClick(cx, cy, searchX, contentY + 3, searchRight - searchX, 20)) {
+ return true;
+ }
+ searchFocused = false;
+ if (cx >= wellInnerX + 4 && cx <= wellInnerX + 76
+ && cy >= contentY + 2 && cy <= contentY + 24) {
+ currentRepoSubTab = 0;
+ scrollOffset = 0;
+ return true;
+ }
+ if (cx >= wellInnerX + 79 && cx <= wellInnerX + 151
+ && cy >= contentY + 2 && cy <= contentY + 24) {
+ currentRepoSubTab = 1;
+ scrollOffset = 0;
+ return true;
+ }
+ if (cx >= wellInnerX + wellInnerW - 144 && cx <= wellInnerX + wellInnerW - 68
+ && cy >= contentY + 2 && cy <= contentY + 24
+ && PluginRepoClient.countUpdatesAvailable(pm) > 0) {
+ PluginRepoClient.updateAllAsync(pm, null);
+ return true;
+ }
+ if (cx >= wellInnerX + wellInnerW - 64 && cx <= wellInnerX + wellInnerW - 2
+ && cy >= contentY + 2 && cy <= contentY + 24) {
+ PluginRepoClient.fetchIndexAsync(null);
+ return true;
+ }
+ if (cy < contentY + 26 || cy > contentY + contentH) {
+ return true;
+ }
+ List entries = getFilteredRepoEntries();
+ if (entries == null || PluginRepoClient.getBusyEntryId() != null) {
+ return true;
+ }
+ int rowY = contentY + 28 - scrollOffset;
+ String err = PluginRepoClient.getLastError();
+ if (err != null && !err.isEmpty()) {
+ rowY += 22;
+ }
+ for (PluginRepoClient.RepoEntry entry : entries) {
+ if (rowY + 36 >= contentY + 26 && rowY <= contentY + contentH) {
+ int btnW = 74;
+ int btnX = wellInnerX + wellInnerW - btnW;
+ int btnY = rowY + 1;
+ int btnH = 36;
+ if (cx >= btnX && cx <= btnX + btnW && cy >= btnY && cy <= btnY + btnH) {
+ PluginRepoClient.InstallStatus status = PluginRepoClient.getInstallStatus(entry, pm);
+ if (status == PluginRepoClient.InstallStatus.NOT_INSTALLED
+ || status == PluginRepoClient.InstallStatus.UPDATE_AVAILABLE) {
+ PluginRepoClient.installOrUpdateAsync(entry, pm, null);
+ } else if (status == PluginRepoClient.InstallStatus.UP_TO_DATE) {
+ PluginRepoClient.uninstall(entry, pm);
+ }
+ return true;
+ }
+ }
+ rowY += 38;
+ }
+ } else if (currentModalTab == 3) {
+ if (configTarget == null) {
+ currentModalTab = configReturnTab;
+ return true;
+ }
+ if (cx >= wellInnerX + wellInnerW - 58 && cx <= wellInnerX + wellInnerW - 2
+ && cy >= contentY + 2 && cy <= contentY + 22) {
+ currentModalTab = configReturnTab;
+ configTarget = null;
+ scrollOffset = 0;
+ openDropdownKey = null;
+ dropdownScrollOffset = 0;
+ return true;
+ }
+
+ List items = getVisibleConfigItems(pm, configTarget);
+ if (items == null) return true;
+
+ int headerH = getConfigHeaderHeight();
+ if (cy < contentY + headerH || cy > contentY + contentH) {
+ openDropdownKey = null;
+ dropdownScrollOffset = 0;
+ return true;
+ }
+
+ // Handle open dropdown popup clicks first
+ int[] dropBounds = getOpenDropdownBounds(pm);
+ if (dropBounds != null) {
+ PluginConfigItem openItem = items.get(dropBounds[4]);
+ if (cx >= dropBounds[0] && cx <= dropBounds[0] + dropBounds[2]
+ && cy >= dropBounds[1] && cy <= dropBounds[1] + dropBounds[3]) {
+ String[] choices = openItem.getChoices();
+ int idx = (cy - (dropBounds[1] + 1) + dropdownScrollOffset) / DROPDOWN_ROW_H;
+ if (idx >= 0 && idx < choices.length) {
+ pm.setConfigValue(configTarget, openItem, choices[idx]);
+ }
+ openDropdownKey = null;
+ dropdownScrollOffset = 0;
+ return true;
+ }
+ int headerDropX = wellInnerX + wellInnerW - DROPDOWN_WIDTH;
+ int headerRowY = contentY + headerH + 2 - scrollOffset + dropBounds[4] * 32;
+ if (cx >= headerDropX && cx <= headerDropX + DROPDOWN_WIDTH
+ && cy >= headerRowY + 1 && cy <= headerRowY + 31) {
+ openDropdownKey = null;
+ dropdownScrollOffset = 0;
+ return true;
+ }
+ openDropdownKey = null;
+ dropdownScrollOffset = 0;
+ }
+
+ int rowY = contentY + headerH + 2 - scrollOffset;
+ for (PluginConfigItem item : items) {
+ if (rowY + 32 >= contentY + headerH && rowY <= contentY + contentH) {
+ int btnY = rowY + 1;
+ int btnH = 30;
+ if (item.getType() == PluginConfigItem.Type.BOOLEAN) {
+ int btnW = 60;
+ int btnX = wellInnerX + wellInnerW - btnW;
+ if (cx >= btnX && cx <= btnX + btnW && cy >= btnY && cy <= btnY + btnH) {
+ boolean currentVal = pm.getConfigBoolean(configTarget, item);
+ pm.setConfigValue(configTarget, item, !currentVal);
+ return true;
+ }
+ } else if (item.getType() == PluginConfigItem.Type.INTEGER) {
+ int stepperW = 126;
+ int stepX = wellInnerX + wellInnerW - stepperW;
+ int range = item.getMaxValue() - item.getMinValue();
+ int step = 1;
+ if (range >= 100000000) step = 1000000;
+ else if (range >= 10000000) step = 100000;
+ else if (range >= 1000000) step = 10000;
+ else if (range >= 100000) step = 1000;
+ else if (range >= 10000) step = 100;
+ else if (range >= 1000) step = 10;
+
+ // Minus segment [-]
+ if (cx >= stepX && cx <= stepX + 28 && cy >= btnY && cy <= btnY + btnH) {
+ int currentVal = pm.getConfigInt(configTarget, item);
+ int nextVal = Math.max(item.getMinValue(), currentVal - step);
+ pm.setConfigValue(configTarget, item, nextVal);
+ return true;
+ }
+ // Plus segment [+]
+ if (cx >= stepX + 97 && cx <= stepX + stepperW && cy >= btnY && cy <= btnY + btnH) {
+ int currentVal = pm.getConfigInt(configTarget, item);
+ int nextVal = Math.min(item.getMaxValue(), currentVal + step);
+ pm.setConfigValue(configTarget, item, nextVal);
+ return true;
+ }
+ } else if (item.getType() == PluginConfigItem.Type.CHOICE && item.getChoices() != null && item.getChoices().length > 0) {
+ int dropX = wellInnerX + wellInnerW - DROPDOWN_WIDTH;
+ if (cx >= dropX && cx <= dropX + DROPDOWN_WIDTH && cy >= btnY && cy <= btnY + btnH) {
+ String[] choices = item.getChoices();
+ openDropdownKey = item.getKey();
+ String currentVal = String.valueOf(pm.getConfigValue(configTarget, item));
+ int curIdx = 0;
+ for (int ci = 0; ci < choices.length; ci++) {
+ if (choices[ci].equalsIgnoreCase(currentVal)) {
+ curIdx = ci;
+ break;
+ }
+ }
+ int visibleH = Math.min(DROPDOWN_MAX_VISIBLE, choices.length) * DROPDOWN_ROW_H + 2;
+ int maxDropScroll = Math.max(0, choices.length * DROPDOWN_ROW_H + 2 - visibleH);
+ dropdownScrollOffset = Math.min(maxDropScroll, Math.max(0, (curIdx - 2) * DROPDOWN_ROW_H));
+ return true;
+ }
+ }
+ }
+ rowY += 32;
+ }
+ }
+
+ return true; // Consume any other click inside modal
+ }
+
+ private static boolean handleSearchBarClick(int cx, int cy, int bx, int by, int bw, int bh) {
+ if (cx >= bx && cx <= bx + bw && cy >= by && cy <= by + bh) {
+ if (searchQuery != null && !searchQuery.isEmpty() && cx >= bx + bw - 20) {
+ searchQuery = "";
+ scrollOffset = 0;
+ }
+ searchFocused = true;
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/2006Scape Client/src/main/java/PluginRepoClient.java b/2006Scape Client/src/main/java/PluginRepoClient.java
new file mode 100644
index 00000000..84d448c5
--- /dev/null
+++ b/2006Scape Client/src/main/java/PluginRepoClient.java
@@ -0,0 +1,481 @@
+import java.io.*;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+
+/**
+ * Fetches, parses, installs, updates, and removes plugins/scripts from the online repository.
+ */
+public class PluginRepoClient {
+
+ public static final String PLUGIN_REPO_SLUG = "2006-Scape/Client-Extensions";
+ public static final String PLUGIN_REPO_BRANCH = "main";
+ public static final String PLUGIN_REPO_URL = "https://github.com/" + PLUGIN_REPO_SLUG;
+ public static final String PLUGIN_REPO_RAW_BASE =
+ "https://raw.githubusercontent.com/" + PLUGIN_REPO_SLUG + "/";
+ public static final String DEFAULT_REPO_INDEX_URL =
+ PLUGIN_REPO_RAW_BASE + PLUGIN_REPO_BRANCH + "/index.json";
+ private static final String REPO_INFO_REFS_URL =
+ PLUGIN_REPO_URL + ".git/info/refs?service=git-upload-pack";
+ private static volatile String resolvedMainSha = null;
+
+ public enum InstallStatus {
+ NOT_INSTALLED,
+ UPDATE_AVAILABLE,
+ UP_TO_DATE,
+ INCOMPATIBLE
+ }
+
+ public static final class RepoEntry {
+ public final String id;
+ public final String name;
+ public final String version;
+ public final String minApi;
+ public final String type;
+ public final String author;
+ public final String description;
+ public final String fileName;
+ public final String downloadUrl;
+
+ public RepoEntry(String id, String name, String version, String minApi,
+ String type, String author, String description,
+ String fileName, String downloadUrl) {
+ this.id = id != null ? id : "";
+ this.name = name != null ? name : "";
+ this.version = (version != null && !version.isEmpty()) ? version : "1.0.0";
+ this.minApi = (minApi != null && !minApi.isEmpty()) ? minApi : "1.0.0";
+ this.type = (type != null && !type.isEmpty()) ? type.toLowerCase() : "script";
+ this.author = author != null ? author : "Unknown";
+ this.description = description != null ? description : "";
+ this.fileName = fileName != null ? fileName : "";
+ this.downloadUrl = downloadUrl != null ? downloadUrl : "";
+ }
+
+ public SemVer getSemVer() {
+ return SemVer.parse(version);
+ }
+ }
+
+ private static volatile List cachedEntries = Collections.emptyList();
+ private static volatile boolean loading = false;
+ private static volatile boolean loadedOnce = false;
+ private static volatile long lastFetchMs = 0L;
+ private static volatile String lastError = null;
+ private static volatile String busyEntryId = null;
+
+ public static List getEntries() {
+ return cachedEntries;
+ }
+
+ public static boolean isLoading() {
+ return loading;
+ }
+
+ public static boolean hasLoadedOnce() {
+ return loadedOnce;
+ }
+
+ public static String getLastError() {
+ return lastError;
+ }
+
+ public static String getBusyEntryId() {
+ return busyEntryId;
+ }
+
+ public static void ensureLoaded() {
+ if (!loading && (!loadedOnce || (System.currentTimeMillis() - lastFetchMs) > 10000L)) {
+ fetchIndexAsync(DEFAULT_REPO_INDEX_URL, null);
+ }
+ }
+
+ public static void fetchIndexAsync(Runnable onComplete) {
+ fetchIndexAsync(DEFAULT_REPO_INDEX_URL, onComplete);
+ }
+
+ public static void fetchIndexAsync(String indexUrl, Runnable onComplete) {
+ if (loading) return;
+ loading = true;
+ lastError = null;
+ Thread t = new Thread(() -> {
+ try {
+ resolveLatestMainSha();
+ String json = httpGet(indexUrl);
+ cachedEntries = Collections.unmodifiableList(parseIndexJson(json));
+ loadedOnce = true;
+ lastFetchMs = System.currentTimeMillis();
+ lastError = null;
+ } catch (Throwable ex) {
+ lastError = ex.getMessage() != null ? ex.getMessage() : ex.getClass().getSimpleName();
+ } finally {
+ loading = false;
+ if (onComplete != null) {
+ try { onComplete.run(); } catch (Throwable ignored) {}
+ }
+ }
+ }, "PluginRepo-Fetch");
+ t.setDaemon(true);
+ t.start();
+ }
+
+ public static InstallStatus getInstallStatus(RepoEntry entry, PluginManager pm) {
+ if (entry == null) return InstallStatus.INCOMPATIBLE;
+ if (!PluginManager.isApiCompatible(entry.minApi)) {
+ return InstallStatus.INCOMPATIBLE;
+ }
+ if (pm == null) return InstallStatus.NOT_INSTALLED;
+
+ SemVer installedVer = findInstalledVersion(entry, pm);
+ if (installedVer == null) {
+ return InstallStatus.NOT_INSTALLED;
+ }
+ if (entry.getSemVer().isNewerThan(installedVer)) {
+ return InstallStatus.UPDATE_AVAILABLE;
+ }
+ return InstallStatus.UP_TO_DATE;
+ }
+
+ public static SemVer findInstalledVersion(RepoEntry entry, PluginManager pm) {
+ if (entry == null || pm == null) return null;
+ for (ClientPlugin p : pm.getPlugins()) {
+ if (p.getName().equalsIgnoreCase(entry.name)) {
+ return p.getSemVer();
+ }
+ }
+ for (ClientScript s : pm.getScripts()) {
+ if (s.getName().equalsIgnoreCase(entry.name)) {
+ return s.getSemVer();
+ }
+ }
+ return null;
+ }
+
+ public static int countUpdatesAvailable(PluginManager pm) {
+ if (pm == null || cachedEntries == null || cachedEntries.isEmpty()) return 0;
+ int count = 0;
+ for (RepoEntry entry : cachedEntries) {
+ if (getInstallStatus(entry, pm) == InstallStatus.UPDATE_AVAILABLE) {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ public static void updateAllAsync(PluginManager pm, Runnable onComplete) {
+ if (pm == null || busyEntryId != null || cachedEntries == null || cachedEntries.isEmpty()) return;
+ List toUpdate = new ArrayList<>();
+ for (RepoEntry entry : cachedEntries) {
+ if (getInstallStatus(entry, pm) == InstallStatus.UPDATE_AVAILABLE
+ && !entry.downloadUrl.isEmpty() && !entry.fileName.isEmpty()) {
+ toUpdate.add(entry);
+ }
+ }
+ if (toUpdate.isEmpty()) return;
+
+ lastError = null;
+ Thread t = new Thread(() -> {
+ int updatedCount = 0;
+ try {
+ for (RepoEntry entry : toUpdate) {
+ busyEntryId = entry.id.isEmpty() ? entry.name : entry.id;
+ try {
+ String content = httpGet(entry.downloadUrl);
+ String safeName = new File(entry.fileName).getName();
+ if (!DesktopHooks.saveExternalScript(safeName, content)) {
+ File target = resolveTargetFile(entry, pm);
+ if (target == null) {
+ throw new IOException("Plugin directory unavailable");
+ }
+ File parent = target.getParentFile();
+ if (parent != null && !parent.exists()) {
+ parent.mkdirs();
+ }
+ try (FileOutputStream out = new FileOutputStream(target)) {
+ out.write(content.getBytes(StandardCharsets.UTF_8));
+ }
+ }
+ updatedCount++;
+ } catch (Throwable ex) {
+ lastError = "Update failed (" + entry.name + "): "
+ + (ex.getMessage() != null ? ex.getMessage() : ex.getClass().getSimpleName());
+ }
+ }
+ if (updatedCount > 0) {
+ pm.reloadExternal();
+ if (pm.getContext() != null) {
+ pm.getContext().sendClientMessage("Updated " + updatedCount + " plugin(s)/script(s) from online repo.");
+ }
+ }
+ } finally {
+ busyEntryId = null;
+ if (onComplete != null) {
+ try { onComplete.run(); } catch (Throwable ignored) {}
+ }
+ }
+ }, "PluginRepo-UpdateAll");
+ t.setDaemon(true);
+ t.start();
+ }
+
+ public static void installOrUpdateAsync(RepoEntry entry, PluginManager pm, Runnable onComplete) {
+ if (entry == null || pm == null || busyEntryId != null) return;
+ if (entry.downloadUrl.isEmpty() || entry.fileName.isEmpty()) {
+ lastError = "Invalid repository entry: missing URL or fileName";
+ return;
+ }
+ busyEntryId = entry.id.isEmpty() ? entry.name : entry.id;
+ lastError = null;
+ Thread t = new Thread(() -> {
+ try {
+ String content = httpGet(entry.downloadUrl);
+ String safeName = new File(entry.fileName).getName();
+ if (!DesktopHooks.saveExternalScript(safeName, content)) {
+ File target = resolveTargetFile(entry, pm);
+ if (target == null) {
+ throw new IOException("Plugin directory unavailable");
+ }
+ File parent = target.getParentFile();
+ if (parent != null && !parent.exists()) {
+ parent.mkdirs();
+ }
+ try (FileOutputStream out = new FileOutputStream(target)) {
+ out.write(content.getBytes(StandardCharsets.UTF_8));
+ }
+ }
+ pm.reloadExternal();
+ if (pm.getContext() != null) {
+ pm.getContext().sendClientMessage("Installed " + entry.name + " v" + entry.version + " from online repo.");
+ }
+ } catch (Throwable ex) {
+ lastError = "Install failed (" + entry.name + "): " + (ex.getMessage() != null ? ex.getMessage() : ex.getClass().getSimpleName());
+ if (pm.getContext() != null) {
+ pm.getContext().sendClientMessage(lastError);
+ }
+ } finally {
+ busyEntryId = null;
+ if (onComplete != null) {
+ try { onComplete.run(); } catch (Throwable ignored) {}
+ }
+ }
+ }, "PluginRepo-Install");
+ t.setDaemon(true);
+ t.start();
+ }
+
+ public static boolean uninstall(RepoEntry entry, PluginManager pm) {
+ if (entry == null || pm == null || entry.fileName.isEmpty()) return false;
+ String safeName = new File(entry.fileName).getName();
+ if (DesktopHooks.deleteExternalScript(safeName)) {
+ pm.reloadExternal();
+ if (pm.getContext() != null) {
+ pm.getContext().sendClientMessage("Removed " + entry.name + ".");
+ }
+ return true;
+ }
+ File target = resolveTargetFile(entry, pm);
+ if (target != null && target.exists() && target.delete()) {
+ pm.reloadExternal();
+ if (pm.getContext() != null) {
+ pm.getContext().sendClientMessage("Removed " + entry.name + ".");
+ }
+ return true;
+ }
+ return false;
+ }
+
+ private static File resolveTargetFile(RepoEntry entry, PluginManager pm) {
+ File base = pm.getPluginBaseDir();
+ if (base == null) return null;
+ String subDir = "plugin".equalsIgnoreCase(entry.type) ? "plugins" : "scripts";
+ String safeName = new File(entry.fileName).getName();
+ return new File(new File(base, subDir), safeName);
+ }
+
+ private static void resolveLatestMainSha() {
+ try {
+ String body = httpGetRaw(REPO_INFO_REFS_URL);
+ int idx = body.indexOf(" refs/heads/" + PLUGIN_REPO_BRANCH);
+ if (idx >= 40) {
+ String candidate = body.substring(idx - 40, idx);
+ if (candidate.matches("[0-9a-fA-F]{40}")) {
+ resolvedMainSha = candidate;
+ }
+ }
+ } catch (Throwable ignored) {
+ }
+ }
+
+ private static String rewriteRawMainUrl(String urlStr) {
+ String sha = resolvedMainSha;
+ if (sha == null || urlStr == null) return urlStr;
+ String lower = urlStr.toLowerCase(Locale.ROOT);
+ String prefix = (PLUGIN_REPO_RAW_BASE + PLUGIN_REPO_BRANCH + "/").toLowerCase(Locale.ROOT);
+ if (lower.startsWith(prefix)) {
+ return PLUGIN_REPO_RAW_BASE + sha + "/" + urlStr.substring(prefix.length());
+ }
+ return urlStr;
+ }
+
+ private static String httpGet(String urlStr) throws IOException {
+ if (resolvedMainSha == null) {
+ resolveLatestMainSha();
+ }
+ String targetUrl = rewriteRawMainUrl(urlStr);
+ String sep = targetUrl.contains("?") ? "&" : "?";
+ return httpGetRaw(targetUrl + sep + "t=" + System.currentTimeMillis());
+ }
+
+ private static String httpGetRaw(String urlStr) throws IOException {
+ String hookRes = DesktopHooks.httpGet(urlStr);
+ if (hookRes != null) {
+ return hookRes;
+ }
+ HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
+ conn.setUseCaches(false);
+ conn.setConnectTimeout(8000);
+ conn.setReadTimeout(10000);
+ conn.setRequestProperty("User-Agent", "2006Scape-Client");
+ conn.setRequestProperty("Cache-Control", "no-cache");
+ int code = conn.getResponseCode();
+ if (code < 200 || code >= 300) {
+ throw new IOException("HTTP " + code);
+ }
+ try (InputStream in = conn.getInputStream();
+ ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
+ byte[] buf = new byte[4096];
+ int n;
+ while ((n = in.read(buf)) != -1) {
+ bos.write(buf, 0, n);
+ }
+ return new String(bos.toByteArray(), StandardCharsets.UTF_8);
+ } finally {
+ conn.disconnect();
+ }
+ }
+
+ /**
+ * Parses the repository index.json "plugins" array without external JSON dependencies.
+ */
+ public static List parseIndexJson(String json) {
+ List result = new ArrayList<>();
+ if (json == null || json.isEmpty()) return result;
+
+ int keyIdx = json.indexOf("\"plugins\"");
+ if (keyIdx < 0) return result;
+ int arrStart = json.indexOf('[', keyIdx);
+ if (arrStart < 0) return result;
+
+ int len = json.length();
+ int i = arrStart + 1;
+ while (i < len) {
+ char c = json.charAt(i);
+ if (c == ']') break;
+ if (c == '{') {
+ int objEnd = findMatchingBrace(json, i);
+ if (objEnd < 0) break;
+ Map fields = parseFlatJsonObject(json.substring(i + 1, objEnd));
+ String name = fields.get("name");
+ String fileName = fields.get("fileName");
+ if (name != null && !name.isEmpty() && fileName != null && !fileName.isEmpty()) {
+ result.add(new RepoEntry(
+ fields.get("id"),
+ name,
+ fields.get("version"),
+ fields.get("minApi"),
+ fields.get("type"),
+ fields.get("author"),
+ fields.get("description"),
+ fileName,
+ fields.get("downloadUrl")
+ ));
+ }
+ i = objEnd + 1;
+ } else {
+ i++;
+ }
+ }
+ return result;
+ }
+
+ private static int findMatchingBrace(String s, int openIdx) {
+ boolean inStr = false;
+ int depth = 0;
+ for (int i = openIdx; i < s.length(); i++) {
+ char c = s.charAt(i);
+ if (c == '"' && (i == 0 || s.charAt(i - 1) != '\\')) {
+ inStr = !inStr;
+ } else if (!inStr) {
+ if (c == '{') depth++;
+ else if (c == '}') {
+ depth--;
+ if (depth == 0) return i;
+ }
+ }
+ }
+ return -1;
+ }
+
+ private static Map parseFlatJsonObject(String body) {
+ Map map = new LinkedHashMap<>();
+ int len = body.length();
+ int i = 0;
+ while (i < len) {
+ int kStart = body.indexOf('"', i);
+ if (kStart < 0) break;
+ int kEnd = findStringEnd(body, kStart + 1);
+ if (kEnd < 0) break;
+ String key = unescapeJson(body.substring(kStart + 1, kEnd));
+
+ int colon = body.indexOf(':', kEnd + 1);
+ if (colon < 0) break;
+
+ int vIdx = colon + 1;
+ while (vIdx < len && Character.isWhitespace(body.charAt(vIdx))) vIdx++;
+ if (vIdx >= len) break;
+
+ if (body.charAt(vIdx) == '"') {
+ int vEnd = findStringEnd(body, vIdx + 1);
+ if (vEnd < 0) break;
+ map.put(key, unescapeJson(body.substring(vIdx + 1, vEnd)));
+ i = vEnd + 1;
+ } else {
+ int comma = body.indexOf(',', vIdx);
+ int end = comma >= 0 ? comma : len;
+ map.put(key, body.substring(vIdx, end).trim());
+ i = end + 1;
+ }
+ }
+ return map;
+ }
+
+ private static int findStringEnd(String s, int start) {
+ for (int i = start; i < s.length(); i++) {
+ char c = s.charAt(i);
+ if (c == '\\') {
+ i++;
+ } else if (c == '"') {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ private static String unescapeJson(String s) {
+ if (s.indexOf('\\') < 0) return s;
+ StringBuilder sb = new StringBuilder(s.length());
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ if (c == '\\' && i + 1 < s.length()) {
+ char next = s.charAt(++i);
+ if (next == 'n') sb.append('\n');
+ else if (next == 'r') sb.append('\r');
+ else if (next == 't') sb.append('\t');
+ else sb.append(next);
+ } else {
+ sb.append(c);
+ }
+ }
+ return sb.toString();
+ }
+}
diff --git a/2006Scape Client/src/main/java/RSApplet.java b/2006Scape Client/src/main/java/RSApplet.java
index e64151b8..da2c55c4 100644
--- a/2006Scape Client/src/main/java/RSApplet.java
+++ b/2006Scape Client/src/main/java/RSApplet.java
@@ -11,7 +11,7 @@ import java.net.URI;
import java.util.Map;
@SuppressWarnings("serial")
-public class RSApplet extends Applet implements Runnable, MouseListener, MouseWheelListener, MouseMotionListener, KeyListener, FocusListener, WindowListener {
+public class RSApplet extends Applet implements Runnable, MouseListener, MouseWheelListener, MouseMotionListener, KeyListener, FocusListener, WindowListener, ComponentListener {
public static boolean ctrlDown = false;
public static boolean shiftDown = false;
@@ -26,16 +26,32 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
public static final int TARGET_MINIMAP = 4;
public static int touchTargetArea = TARGET_DEFAULT;
+ private volatile boolean pendingResize = false;
+ private int pendingWidth = 765;
+ private int pendingHeight = 503;
+
final void createClientFrame(int i, int j) {
+ try {
+ System.setProperty("sun.awt.noerasebackground", "true");
+ } catch (Exception _ex) {
+ }
myWidth = j;
myHeight = i;
this.setPreferredSize(new Dimension(this.myWidth, this.myHeight));
+ this.setBackground(Color.BLACK);
+
+ if (!ClientSettings.ANDROID && ClientSettings.RESIZABLE) {
+ ModernLayout.updateWindowSize(j, i);
+ ClientSettings.VIEWPORT_WIDTH = ClientSettings.isDesktopModern() ? j : 512;
+ ClientSettings.VIEWPORT_HEIGHT = ClientSettings.isDesktopModern() ? i : 334;
+ this.addComponentListener(this);
+ }
gameFrame = new RSFrame(this);
graphics = getGameComponent().getGraphics();
fullGameScreen = new RSImageProducer(myWidth, myHeight, getGameComponent());
- if (ClientSettings.SHOW_NAVBAR) {
+ if (ClientSettings.SHOW_NAVBAR && !ClientSettings.RESIZABLE) {
try {
java.awt.Font arial = new java.awt.Font("Arial", java.awt.Font.PLAIN, 11);
Map attributes = arial.getAttributes();
@@ -249,6 +265,9 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
getGameComponent().addMouseWheelListener(this);
getGameComponent().addKeyListener(this);
getGameComponent().addFocusListener(this);
+ if (!ClientSettings.ANDROID && ClientSettings.RESIZABLE) {
+ getGameComponent().addComponentListener(this);
+ }
if (gameFrame != null) {
gameFrame.addWindowListener(this);
}
@@ -265,6 +284,10 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
System.currentTimeMillis();
while (anInt4 >= 0) {
+ if (pendingResize) {
+ pendingResize = false;
+ handleResize(pendingWidth, pendingHeight);
+ }
if (anInt4 > 0) {
anInt4--;
if (anInt4 == 0) {
@@ -392,11 +415,7 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
@Override
public final void update(Graphics g) {
- if (graphics == null) {
- graphics = g;
- }
- shouldClearScreen = true;
- raiseWelcomeScreen();
+ paint(g);
}
@Override
@@ -404,6 +423,11 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
if (graphics == null) {
graphics = g;
}
+ if (!ModernLayout.inGame && !ClientSettings.ANDROID && ClientSettings.RESIZABLE) {
+ DesktopHooks.checkResize(getGameComponent());
+ DesktopHooks.redrawScaledLoginScreen(g);
+ return;
+ }
shouldClearScreen = true;
raiseWelcomeScreen();
}
@@ -415,8 +439,18 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
int i = mouseevent.getX();
int j = mouseevent.getY();
idleTime = 0;
- clickX = i;
- clickY = j;
+ if (ClientSettings.isDesktopModern()) {
+ touchTargetArea = ModernLayout.hit(i, j);
+ int[] gameCoords = ModernLayout.toGameCoords(touchTargetArea, i, j);
+ clickX = gameCoords[0];
+ clickY = gameCoords[1];
+ mouseX = gameCoords[0];
+ mouseY = gameCoords[1];
+ } else {
+ touchTargetArea = 0;
+ clickX = i;
+ clickY = j;
+ }
clickTime = System.currentTimeMillis();
if (mouseevent.getButton() == MouseEvent.BUTTON2) {
mouseWheelDown = true;
@@ -469,8 +503,16 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
return;
}
idleTime = 0;
- mouseX = x;
- mouseY = y;
+ if (ClientSettings.isDesktopModern()) {
+ touchTargetArea = ModernLayout.hit(x, y);
+ int[] gameCoords = ModernLayout.toGameCoords(touchTargetArea, x, y);
+ mouseX = gameCoords[0];
+ mouseY = gameCoords[1];
+ } else {
+ touchTargetArea = 0;
+ mouseX = x;
+ mouseY = y;
+ }
}
void mouseWheelDragged(int param1, int param2) {
@@ -481,12 +523,26 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
int i = mouseevent.getX();
int j = mouseevent.getY();
idleTime = 0;
- mouseX = i;
- mouseY = j;
+ if (ClientSettings.isDesktopModern()) {
+ touchTargetArea = ModernLayout.hit(i, j);
+ int[] gameCoords = ModernLayout.toGameCoords(touchTargetArea, i, j);
+ mouseX = gameCoords[0];
+ mouseY = gameCoords[1];
+ } else {
+ touchTargetArea = 0;
+ mouseX = i;
+ mouseY = j;
+ }
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
+ if (ClientSettings.isDesktopModern()) {
+ int hitArea = ModernLayout.hit(e.getX(), e.getY());
+ if (hitArea != ModernLayout.TARGET_VIEWPORT) {
+ return;
+ }
+ }
handleMouseWheel(e.getWheelRotation(), e.isControlDown());
}
@@ -682,6 +738,57 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
void raiseWelcomeScreen() {
}
+ void handleResize(int w, int h) {
+ myWidth = w;
+ myHeight = h;
+ ModernLayout.updateWindowSize(w, h);
+ graphics = getGameComponent().getGraphics();
+ if (graphics != null && !ClientSettings.isDesktopModern()) {
+ graphics.setColor(Color.BLACK);
+ graphics.fillRect(0, 0, w, h);
+ }
+ if (fullGameScreen != null) {
+ fullGameScreen = new RSImageProducer(765, 503, getGameComponent());
+ }
+ onResize(w, h);
+ if (!ModernLayout.inGame && !ClientSettings.ANDROID && ClientSettings.RESIZABLE) {
+ DesktopHooks.redrawScaledLoginScreen(graphics);
+ }
+ }
+
+ void onResize(int w, int h) {
+ }
+
+ @Override
+ public void componentResized(ComponentEvent e) {
+ if (!ClientSettings.ANDROID && ClientSettings.RESIZABLE) {
+ Component c = e.getComponent();
+ int w = c.getWidth();
+ int h = c.getHeight();
+ if (w >= 765 && h >= 503 && (w != myWidth || h != myHeight)) {
+ pendingWidth = w;
+ pendingHeight = h;
+ pendingResize = true;
+ if (!ModernLayout.inGame) {
+ DesktopHooks.checkResize(c);
+ Graphics g = getGameComponent().getGraphics();
+ if (g != null) {
+ DesktopHooks.redrawScaledLoginScreen(g);
+ }
+ }
+ }
+ }
+ }
+
+ @Override
+ public void componentMoved(ComponentEvent e) {}
+
+ @Override
+ public void componentShown(ComponentEvent e) {}
+
+ @Override
+ public void componentHidden(ComponentEvent e) {}
+
Component getGameComponent() {
return this;
}
@@ -704,6 +811,14 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
} catch (Exception _ex) {
}
}
+ if (!ClientSettings.ANDROID && ClientSettings.RESIZABLE) {
+ DesktopHooks.checkResize(getGameComponent());
+ if (myWidth != ModernLayout.windowWidth || myHeight != ModernLayout.windowHeight) {
+ myWidth = ModernLayout.windowWidth;
+ myHeight = ModernLayout.windowHeight;
+ shouldClearScreen = true;
+ }
+ }
Font font = new Font("Helvetica", 1, 13);
FontMetrics fontmetrics = getGameComponent().getFontMetrics(font);
Font font1 = new Font("Helvetica", 0, 13);
@@ -750,7 +865,7 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
private boolean shouldClearScreen;
boolean awtFocus;
int idleTime;
- int clickMode2;
+ public int clickMode2;
public int mouseX;
public int mouseY;
private int clickMode1;
diff --git a/2006Scape Client/src/main/java/RSColors.java b/2006Scape Client/src/main/java/RSColors.java
index 7f4aa4b2..c88cd8ad 100644
--- a/2006Scape Client/src/main/java/RSColors.java
+++ b/2006Scape Client/src/main/java/RSColors.java
@@ -9,6 +9,8 @@ public final class RSColors {
public static final int CYAN = 0x00ffff;
public static final int ORANGE = 0xffc800;
public static final int RED = 0xff0000;
+ public static final int GOLD = 0xffd700;
+ public static final int MAGENTA = 0xdc00ff;
public static final int WHITE_DARKER = 0xc0c0c0;
private RSColors() {}
diff --git a/2006Scape Client/src/main/java/RSFrame.java b/2006Scape Client/src/main/java/RSFrame.java
index 05e50420..f8c814a3 100644
--- a/2006Scape Client/src/main/java/RSFrame.java
+++ b/2006Scape Client/src/main/java/RSFrame.java
@@ -10,13 +10,20 @@ final class RSFrame extends Frame {
rsApplet = applet;
setTitle(ClientSettings.SERVER_NAME + " World: " + ClientSettings.SERVER_WORLD + ((ClientSettings.SERVER_IP.equals("localhost") || ClientSettings.SERVER_IP.equals("127.0.0.1")) ? " [Local]" : ""));
- this.setResizable(false);
+ this.setResizable(ClientSettings.RESIZABLE);
this.setBackground(Color.BLACK);
this.setLayout(new BorderLayout());
this.add(applet, BorderLayout.CENTER);
this.pack();
+ if (ClientSettings.RESIZABLE) {
+ Insets insets = this.getInsets();
+ int minW = 765 + (insets != null ? insets.left + insets.right : 0);
+ int minH = 503 + (insets != null ? insets.top + insets.bottom : 0);
+ this.setMinimumSize(new Dimension(minW, minH));
+ }
+
this.setLocationRelativeTo(null);
this.setVisible(true);
this.toFront();
diff --git a/2006Scape Client/src/main/java/RSImageProducer.java b/2006Scape Client/src/main/java/RSImageProducer.java
index e624464c..b8e11881 100644
--- a/2006Scape Client/src/main/java/RSImageProducer.java
+++ b/2006Scape Client/src/main/java/RSImageProducer.java
@@ -37,6 +37,26 @@ final class RSImageProducer implements ImageProducer, ImageObserver {
public void drawGraphics(int i, Graphics g, int k) {
method239();
+ if (ClientSettings.RESIZABLE && !ClientSettings.ANDROID) {
+ if (!ModernLayout.inGame && k >= 0 && i >= 0 && k + anInt316 <= 765 && i + anInt317 <= 503) {
+ if (ClientSettings.isDesktopModern()) {
+ DesktopHooks.drawScaledLoginTile(g, anIntArray315, k, i, anInt316, anInt317);
+ return;
+ }
+ DesktopHooks.updateLoginTile(anIntArray315, k, i, anInt316, anInt317);
+ }
+ if (ClientSettings.isDesktopModern()) {
+ int[] pos = ModernLayout.toWindow(k, i, anInt316, anInt317);
+ if (pos != null) {
+ if (pos.length == 4) {
+ g.drawImage(anImage320, pos[0], pos[1], pos[2], pos[3], this);
+ } else {
+ g.drawImage(anImage320, pos[0], pos[1], this);
+ }
+ }
+ return;
+ }
+ }
g.drawImage(anImage320, k, i, this);
}
diff --git a/2006Scape Client/src/main/java/ScriptInterpreter.java b/2006Scape Client/src/main/java/ScriptInterpreter.java
new file mode 100644
index 00000000..972930a1
--- /dev/null
+++ b/2006Scape Client/src/main/java/ScriptInterpreter.java
@@ -0,0 +1,1383 @@
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.*;
+
+/**
+ * Lightweight, zero-dependency Java/BeanShell-compatible script interpreter.
+ * Runs on both Desktop JVM and Android ART without compiling bytecodes.
+ */
+public class ScriptInterpreter {
+
+ public static class ScriptMetadata {
+ public String name = "Unnamed Script";
+ public String author = "Anonymous";
+ public String description = "";
+ public String version = "1.0.0";
+ public String minApiVersion = "1.0.0";
+ public String type = "script"; // "plugin" or "script"
+ public List commands = new ArrayList<>();
+ public List configItems = new ArrayList<>();
+ }
+
+ public static ScriptMetadata parseMetadata(String source) {
+ ScriptMetadata meta = new ScriptMetadata();
+ String[] lines = source.split("\\r?\\n");
+ for (String line : lines) {
+ String trimmed = line.trim();
+ if (trimmed.startsWith("//") || trimmed.startsWith("#")) {
+ String comment = trimmed.substring(trimmed.startsWith("//") ? 2 : 1).trim();
+ if (comment.startsWith("@name")) {
+ meta.name = comment.substring(5).trim();
+ } else if (comment.startsWith("@author")) {
+ meta.author = comment.substring(7).trim();
+ } else if (comment.startsWith("@desc")) {
+ meta.description = comment.substring(comment.indexOf(' ')).trim();
+ } else if (comment.startsWith("@type")) {
+ meta.type = comment.substring(5).trim().toLowerCase();
+ } else if (comment.startsWith("@version")) {
+ meta.version = comment.substring(8).trim();
+ } else if (comment.startsWith("@minApi")) {
+ meta.minApiVersion = comment.substring(7).trim();
+ } else if (comment.startsWith("@command")) {
+ String rawCmds = comment.substring(8).trim();
+ for (String c : rawCmds.split(",")) {
+ String clean = c.trim();
+ if (clean.startsWith("::")) clean = clean.substring(2).trim();
+ if (!clean.isEmpty()) {
+ meta.commands.add(clean.toLowerCase());
+ }
+ }
+ } else if (comment.startsWith("@config")) {
+ // format: @config key|label|type|defaultValue[|extra][|when:otherKey]
+ String[] parts = comment.substring(7).trim().split("\\|");
+ String visibleWhen = null;
+ int partCount = parts.length;
+ if (partCount >= 5 && parts[partCount - 1].trim().startsWith("when:")) {
+ visibleWhen = parts[partCount - 1].trim().substring(5).trim();
+ partCount--;
+ }
+ if (partCount >= 4) {
+ String key = parts[0].trim();
+ String label = parts[1].trim();
+ String typeStr = parts[2].trim().toLowerCase();
+ String defStr = parts[3].trim();
+ PluginConfigItem item;
+ if ("bool".equals(typeStr) || "boolean".equals(typeStr)) {
+ item = new PluginConfigItem(key, label, "", Boolean.parseBoolean(defStr));
+ } else if ("int".equals(typeStr) || "integer".equals(typeStr)) {
+ int min = partCount >= 5 ? Integer.parseInt(parts[4].trim()) : 0;
+ int max = partCount >= 6 ? Integer.parseInt(parts[5].trim()) : 100;
+ item = new PluginConfigItem(key, label, "", Integer.parseInt(defStr), min, max);
+ } else if ("choice".equals(typeStr) && partCount >= 5) {
+ String[] choices = parts[4].split(",");
+ for (int ci = 0; ci < choices.length; ci++) {
+ choices[ci] = choices[ci].trim();
+ }
+ item = new PluginConfigItem(key, label, "", defStr, choices);
+ } else {
+ item = new PluginConfigItem(key, label, "", defStr);
+ }
+ if (visibleWhen != null && !visibleWhen.isEmpty()) {
+ item.setVisibleWhen(visibleWhen);
+ }
+ meta.configItems.add(item);
+ }
+ }
+ } else if (!trimmed.isEmpty()) {
+ // First non-comment line, stop header parsing
+ break;
+ }
+ }
+ if (!meta.commands.isEmpty()) {
+ boolean hasToggle = false;
+ for (PluginConfigItem item : meta.configItems) {
+ if ("chatCommands".equals(item.getKey())) {
+ hasToggle = true;
+ break;
+ }
+ }
+ if (!hasToggle) {
+ StringBuilder cmdLabel = new StringBuilder();
+ for (int i = 0; i < meta.commands.size(); i++) {
+ if (i > 0) cmdLabel.append(", ");
+ cmdLabel.append("::").append(meta.commands.get(i));
+ }
+ meta.configItems.add(new PluginConfigItem("chatCommands", "Chat Commands",
+ "Allow " + cmdLabel + " in chat", true));
+ }
+ }
+ return meta;
+ }
+
+ /**
+ * Runtime execution environment holding functions, global variables, and evaluator.
+ */
+ private static String lastEvalExpr = "";
+
+ public static class Environment {
+ private final Map globals = new HashMap<>();
+ private final Map functions = new HashMap<>();
+
+ public Environment() {
+ }
+
+ public void setVariable(String name, Object value) {
+ globals.put(name, value);
+ }
+
+ public Object getVariable(String name) {
+ return globals.get(name);
+ }
+
+ public boolean hasFunction(String name) {
+ return functions.containsKey(name);
+ }
+
+ public void registerFunction(String name, List paramNames, String body) {
+ functions.put(name, new FunctionDef(name, paramNames, body));
+ }
+
+ public Object invoke(String name, Object... args) {
+ FunctionDef fn = functions.get(name);
+ if (fn == null) return null;
+ return fn.execute(this, args);
+ }
+ }
+
+ public static class FunctionDef {
+ final String name;
+ final List params;
+ final String body;
+
+ FunctionDef(String name, List params, String body) {
+ this.name = name;
+ this.params = params;
+ this.body = body;
+ }
+
+ public Object execute(Environment parentEnv, Object[] argValues) {
+ Scope scope = new Scope(parentEnv.globals);
+ for (int i = 0; i < params.size() && i < argValues.length; i++) {
+ scope.setLocal(params.get(i), argValues[i]);
+ }
+ try {
+ return executeBlock(body, scope, parentEnv);
+ } catch (ReturnSignal r) {
+ return r.value;
+ } catch (Throwable t) {
+ System.err.println("Script runtime error in function " + name + " [expr=" + lastEvalExpr + "]: " + t.getMessage());
+ t.printStackTrace();
+ return null;
+ }
+ }
+ }
+
+ public static class Scope {
+ private final Map globals;
+ private final Map locals = new HashMap<>();
+ private final boolean isGlobal;
+
+ public Scope(Map globals) {
+ this(globals, false);
+ }
+
+ public Scope(Map globals, boolean isGlobal) {
+ this.globals = globals;
+ this.isGlobal = isGlobal;
+ }
+
+ public void set(String name, Object value) {
+ if (isGlobal) {
+ globals.put(name, value);
+ } else if (globals.containsKey(name) && !locals.containsKey(name)) {
+ globals.put(name, value);
+ } else {
+ locals.put(name, value);
+ }
+ }
+
+ public void setLocal(String name, Object value) {
+ locals.put(name, value);
+ }
+
+ public Object get(String name) {
+ if (locals.containsKey(name)) return locals.get(name);
+ return globals.get(name);
+ }
+
+ public boolean contains(String name) {
+ return locals.containsKey(name) || globals.containsKey(name);
+ }
+ }
+
+ private static class ReturnSignal extends RuntimeException {
+ final Object value;
+ ReturnSignal(Object value) {
+ this.value = value;
+ }
+ }
+
+ /**
+ * Parses source code into functions and initial statements, returning an Environment.
+ */
+ public static Environment compile(String source) {
+ Environment env = new Environment();
+ env.setVariable("Math", Math.class);
+ env.setVariable("System", System.class);
+ env.setVariable("RSColors", RSColors.class);
+ env.setVariable("ItemID", ItemID.class);
+ env.setVariable("SkillID", SkillID.class);
+ env.setVariable("NpcID", NpcID.class);
+ env.setVariable("ObjectID", ObjectID.class);
+ env.setVariable("PluginContext", PluginContext.class);
+ String cleaned = cleanComments(source);
+ Scope globalScope = new Scope(env.globals, true);
+
+ // Find function declarations: void onStart(...) { ... } or int loop(...) { ... }
+ int pos = 0;
+ int len = cleaned.length();
+
+ while (pos < len) {
+ // Find next function signature or statement
+ int openBrace = cleaned.indexOf('{', pos);
+ if (openBrace == -1) {
+ // Execute trailing statements
+ String statementBlock = cleaned.substring(pos).trim();
+ if (!statementBlock.isEmpty()) {
+ executeBlock(statementBlock, globalScope, env);
+ }
+ break;
+ }
+
+ String prefix = cleaned.substring(pos, openBrace).trim();
+ int lastSemi = prefix.lastIndexOf(';');
+ if (lastSemi != -1) {
+ String precedingStmts = prefix.substring(0, lastSemi + 1);
+ executeBlock(precedingStmts, globalScope, env);
+ prefix = prefix.substring(lastSemi + 1).trim();
+ }
+
+ int closeParen = prefix.lastIndexOf(')');
+ int openParen = prefix.lastIndexOf('(');
+
+ if (openParen != -1 && closeParen != -1 && openParen < closeParen) {
+ // Looks like function: [type] name(arg1, arg2...)
+ String funcHeader = prefix.substring(0, openParen).trim();
+ String[] words = funcHeader.split("\\s+");
+ String funcName = words[words.length - 1];
+
+ String paramsStr = prefix.substring(openParen + 1, closeParen).trim();
+ List paramList = new ArrayList<>();
+ if (!paramsStr.isEmpty()) {
+ for (String p : paramsStr.split(",")) {
+ String[] pParts = p.trim().split("\\s+");
+ paramList.add(pParts[pParts.length - 1]);
+ }
+ }
+
+ // Match closing brace
+ int closeBrace = findMatchingBrace(cleaned, openBrace);
+ if (closeBrace != -1) {
+ String funcBody = cleaned.substring(openBrace + 1, closeBrace);
+ env.registerFunction(funcName, paramList, funcBody);
+ pos = closeBrace + 1;
+ continue;
+ }
+ }
+
+ // Not a function, advance pos to semicolon
+ int semi = cleaned.indexOf(';', pos);
+ if (semi != -1 && semi < openBrace) {
+ String stmt = cleaned.substring(pos, semi + 1);
+ executeBlock(stmt, globalScope, env);
+ pos = semi + 1;
+ } else {
+ pos = openBrace + 1;
+ }
+ }
+
+ return env;
+ }
+
+ private static int findMatchingBrace(String s, int openIndex) {
+ int depth = 1;
+ for (int i = openIndex + 1; i < s.length(); i++) {
+ char c = s.charAt(i);
+ if (c == '{') depth++;
+ else if (c == '}') {
+ depth--;
+ if (depth == 0) return i;
+ }
+ }
+ return -1;
+ }
+
+ private static String cleanComments(String s) {
+ StringBuilder sb = new StringBuilder(s.length());
+ int len = s.length();
+ boolean inStr = false;
+ for (int i = 0; i < len; i++) {
+ char c = s.charAt(i);
+ if (c == '"' && (i == 0 || s.charAt(i - 1) != '\\')) {
+ inStr = !inStr;
+ sb.append(c);
+ } else if (!inStr && c == '/' && i + 1 < len && s.charAt(i + 1) == '/') {
+ // Line comment
+ int nextNl = s.indexOf('\n', i);
+ if (nextNl == -1) break;
+ i = nextNl - 1;
+ } else if (!inStr && c == '/' && i + 1 < len && s.charAt(i + 1) == '*') {
+ // Block comment
+ int close = s.indexOf("*/", i + 2);
+ if (close == -1) break;
+ i = close + 1;
+ } else {
+ sb.append(c);
+ }
+ }
+ return sb.toString();
+ }
+
+ private static Object executeBlock(String block, Scope scope, Environment env) {
+ int pos = 0;
+ int len = block.length();
+
+ while (pos < len) {
+ // Skip whitespace
+ while (pos < len && Character.isWhitespace(block.charAt(pos))) pos++;
+ if (pos >= len) break;
+
+ // Check control statements
+ if (block.startsWith("if", pos) && !Character.isJavaIdentifierPart(block.charAt(pos + 2))) {
+ pos = executeIfStatement(block, pos, scope, env);
+ continue;
+ }
+
+ if (block.startsWith("while", pos) && (pos + 5 == len || !Character.isJavaIdentifierPart(block.charAt(pos + 5)))) {
+ int openParen = block.indexOf('(', pos);
+ int closeParen = findMatchingParen(block, openParen);
+ String condStr = block.substring(openParen + 1, closeParen);
+ int openBrace = block.indexOf('{', closeParen);
+ int closeBrace = findMatchingBrace(block, openBrace);
+ String loopBlock = block.substring(openBrace + 1, closeBrace);
+ int guard = 0;
+ while (guard++ < 1000 && isTruthy(evalExpression(condStr, scope, env))) {
+ executeBlock(loopBlock, scope, env);
+ }
+ pos = closeBrace + 1;
+ continue;
+ }
+
+ if (block.startsWith("return", pos) && (pos + 6 == len || !Character.isJavaIdentifierPart(block.charAt(pos + 6)))) {
+ int semi = block.indexOf(';', pos);
+ String retExpr = semi != -1 ? block.substring(pos + 6, semi).trim() : block.substring(pos + 6).trim();
+ Object val = retExpr.isEmpty() ? null : evalExpression(retExpr, scope, env);
+ throw new ReturnSignal(val);
+ }
+
+ // Normal statement ending with semicolon
+ int semi = block.indexOf(';', pos);
+ if (semi == -1) {
+ semi = len;
+ }
+ String stmt = block.substring(pos, semi).trim();
+ executeStatement(stmt, scope, env);
+ pos = semi + 1;
+ }
+
+ return null;
+ }
+
+ private static int executeIfStatement(String block, int pos, Scope scope, Environment env) {
+ int len = block.length();
+ int openParen = block.indexOf('(', pos);
+ int closeParen = findMatchingParen(block, openParen);
+ String condStr = block.substring(openParen + 1, closeParen);
+ boolean cond = isTruthy(evalExpression(condStr, scope, env));
+
+ int openBrace = block.indexOf('{', closeParen);
+ int closeBrace = findMatchingBrace(block, openBrace);
+ String thenBlock = block.substring(openBrace + 1, closeBrace);
+
+ if (cond) {
+ executeBlock(thenBlock, scope, env);
+ return skipElseChain(block, closeBrace + 1);
+ }
+
+ int nextPos = closeBrace + 1;
+ while (nextPos < len && Character.isWhitespace(block.charAt(nextPos))) nextPos++;
+
+ if (nextPos + 4 <= len && block.startsWith("else", nextPos)
+ && (nextPos + 4 == len || !Character.isJavaIdentifierPart(block.charAt(nextPos + 4)))) {
+ int afterElse = nextPos + 4;
+ while (afterElse < len && Character.isWhitespace(block.charAt(afterElse))) afterElse++;
+ if (afterElse + 2 <= len && block.startsWith("if", afterElse)
+ && (afterElse + 2 == len || !Character.isJavaIdentifierPart(block.charAt(afterElse + 2)))) {
+ return executeIfStatement(block, afterElse, scope, env);
+ }
+ int elseBrace = block.indexOf('{', afterElse);
+ int elseClose = findMatchingBrace(block, elseBrace);
+ String elseBlock = block.substring(elseBrace + 1, elseClose);
+ executeBlock(elseBlock, scope, env);
+ return elseClose + 1;
+ }
+
+ return nextPos;
+ }
+
+ private static int skipElseChain(String block, int pos) {
+ int len = block.length();
+ while (pos < len) {
+ int nextPos = pos;
+ while (nextPos < len && Character.isWhitespace(block.charAt(nextPos))) nextPos++;
+ if (nextPos + 4 <= len && block.startsWith("else", nextPos)
+ && (nextPos + 4 == len || !Character.isJavaIdentifierPart(block.charAt(nextPos + 4)))) {
+ int afterElse = nextPos + 4;
+ while (afterElse < len && Character.isWhitespace(block.charAt(afterElse))) afterElse++;
+ if (afterElse + 2 <= len && block.startsWith("if", afterElse)
+ && (afterElse + 2 == len || !Character.isJavaIdentifierPart(block.charAt(afterElse + 2)))) {
+ int openParen = block.indexOf('(', afterElse);
+ int closeParen = findMatchingParen(block, openParen);
+ int openBrace = block.indexOf('{', closeParen);
+ int closeBrace = findMatchingBrace(block, openBrace);
+ pos = closeBrace + 1;
+ continue;
+ }
+ int elseBrace = block.indexOf('{', afterElse);
+ int elseClose = findMatchingBrace(block, elseBrace);
+ return elseClose + 1;
+ }
+ return pos;
+ }
+ return pos;
+ }
+
+ private static int findMatchingParen(String s, int openIndex) {
+ int depth = 1;
+ for (int i = openIndex + 1; i < s.length(); i++) {
+ char c = s.charAt(i);
+ if (c == '(') depth++;
+ else if (c == ')') {
+ depth--;
+ if (depth == 0) return i;
+ }
+ }
+ return -1;
+ }
+
+ private static void executeStatement(String stmt, Scope scope, Environment env) {
+ if (stmt == null || stmt.isEmpty()) return;
+
+ // Compound assignment: += or -=
+ int plusEq = stmt.indexOf("+=");
+ int minusEq = stmt.indexOf("-=");
+ if (plusEq != -1 || minusEq != -1) {
+ boolean isAdd = plusEq != -1 && (minusEq == -1 || plusEq < minusEq);
+ int opIdx = isAdd ? plusEq : minusEq;
+ String varName = stmt.substring(0, opIdx).trim();
+ String right = stmt.substring(opIdx + 2).trim();
+ Object cur = scope.get(varName);
+ Object rhs = evalExpression(right, scope, env);
+ if (isAdd && (cur instanceof String || rhs instanceof String)) {
+ scope.set(varName, safeToString(cur) + safeToString(rhs));
+ } else if (isIntegral(cur) && isIntegral(rhs)) {
+ long res = isAdd ? (((Number) cur).longValue() + ((Number) rhs).longValue())
+ : (((Number) cur).longValue() - ((Number) rhs).longValue());
+ scope.set(varName, toIntegralResult(cur, rhs, res));
+ } else {
+ double a = toDouble(cur);
+ double b = toDouble(rhs);
+ scope.set(varName, isAdd ? (a + b) : (a - b));
+ }
+ return;
+ }
+
+ // Check for variable declaration: var x = ..., int x = ..., String s = ...
+ int eqIndex = stmt.indexOf('=');
+ if (eqIndex != -1 && !stmt.startsWith("==") && (eqIndex == 0 || stmt.charAt(eqIndex - 1) != '!' && stmt.charAt(eqIndex - 1) != '<' && stmt.charAt(eqIndex - 1) != '>')) {
+ String left = stmt.substring(0, eqIndex).trim();
+ String right = stmt.substring(eqIndex + 1).trim();
+
+ String varName = left;
+ String[] parts = left.split("\\s+");
+ if (parts.length > 1) {
+ varName = parts[parts.length - 1];
+ }
+
+ Object val = evalExpression(right, scope, env);
+ scope.set(varName, val);
+ return;
+ }
+
+ // Increment / decrement: i++ or i--
+ if (stmt.endsWith("++") || stmt.endsWith("--")) {
+ boolean isInc = stmt.endsWith("++");
+ String varName = stmt.substring(0, stmt.length() - 2).trim();
+ Object cur = scope.get(varName);
+ int num = (cur instanceof Number) ? ((Number) cur).intValue() : 0;
+ scope.set(varName, isInc ? num + 1 : num - 1);
+ return;
+ }
+
+ // Expression statement (e.g. method call)
+ evalExpression(stmt, scope, env);
+ }
+
+ public static Object evalExpression(String expr, Scope scope, Environment env) {
+ if (expr == null) return null;
+ expr = expr.trim();
+ lastEvalExpr = expr;
+ if (expr.isEmpty()) return null;
+
+ // Parentheses
+ if (expr.startsWith("(") && expr.endsWith(")")) {
+ int closeParen = findMatchingParen(expr, 0);
+ if (closeParen == expr.length() - 1) {
+ return evalExpression(expr.substring(1, expr.length() - 1), scope, env);
+ }
+ }
+
+ // Logical OR: ||
+ int orIdx = findTopLevelOp(expr, "||");
+ if (orIdx != -1) {
+ boolean left = isTruthy(evalExpression(expr.substring(0, orIdx), scope, env));
+ if (left) return true;
+ return isTruthy(evalExpression(expr.substring(orIdx + 2), scope, env));
+ }
+
+ // Logical AND: &&
+ int andIdx = findTopLevelOp(expr, "&&");
+ if (andIdx != -1) {
+ boolean left = isTruthy(evalExpression(expr.substring(0, andIdx), scope, env));
+ if (!left) return false;
+ return isTruthy(evalExpression(expr.substring(andIdx + 2), scope, env));
+ }
+
+ // Equality: == and !=
+ int eqIdx = findTopLevelOp(expr, "==");
+ if (eqIdx != -1) {
+ Object a = evalExpression(expr.substring(0, eqIdx), scope, env);
+ Object b = evalExpression(expr.substring(eqIdx + 2), scope, env);
+ return safeEquals(a, b);
+ }
+ int neIdx = findTopLevelOp(expr, "!=");
+ if (neIdx != -1) {
+ Object a = evalExpression(expr.substring(0, neIdx), scope, env);
+ Object b = evalExpression(expr.substring(neIdx + 2), scope, env);
+ return !safeEquals(a, b);
+ }
+
+ // Comparison: <=, >=, <, >
+ int lteIdx = findTopLevelOp(expr, "<=");
+ if (lteIdx != -1) {
+ double a = toDouble(evalExpression(expr.substring(0, lteIdx), scope, env));
+ double b = toDouble(evalExpression(expr.substring(lteIdx + 2), scope, env));
+ return a <= b;
+ }
+ int gteIdx = findTopLevelOp(expr, ">=");
+ if (gteIdx != -1) {
+ double a = toDouble(evalExpression(expr.substring(0, gteIdx), scope, env));
+ double b = toDouble(evalExpression(expr.substring(gteIdx + 2), scope, env));
+ return a >= b;
+ }
+ int ltIdx = findTopLevelOp(expr, "<");
+ if (ltIdx != -1) {
+ double a = toDouble(evalExpression(expr.substring(0, ltIdx), scope, env));
+ double b = toDouble(evalExpression(expr.substring(ltIdx + 1), scope, env));
+ return a < b;
+ }
+ int gtIdx = findTopLevelOp(expr, ">");
+ if (gtIdx != -1) {
+ double a = toDouble(evalExpression(expr.substring(0, gtIdx), scope, env));
+ double b = toDouble(evalExpression(expr.substring(gtIdx + 1), scope, env));
+ return a > b;
+ }
+
+ // Addition & Subtraction: + and -
+ int addIdx = findTopLevelOp(expr, "+");
+ if (addIdx != -1) {
+ Object a = evalExpression(expr.substring(0, addIdx), scope, env);
+ Object b = evalExpression(expr.substring(addIdx + 1), scope, env);
+ if (a instanceof String || b instanceof String) {
+ return safeToString(a) + safeToString(b);
+ }
+ if (isIntegral(a) && isIntegral(b)) {
+ return toIntegralResult(a, b, ((Number) a).longValue() + ((Number) b).longValue());
+ }
+ return toDouble(a) + toDouble(b);
+ }
+ int subIdx = findTopLevelOp(expr, "-");
+ if (subIdx != -1 && subIdx > 0 && !isOperator(expr.charAt(subIdx - 1))) {
+ Object a = evalExpression(expr.substring(0, subIdx), scope, env);
+ Object b = evalExpression(expr.substring(subIdx + 1), scope, env);
+ if (isIntegral(a) && isIntegral(b)) {
+ return toIntegralResult(a, b, ((Number) a).longValue() - ((Number) b).longValue());
+ }
+ return toDouble(a) - toDouble(b);
+ }
+
+ // Multiplication & Division: * and /
+ int mulIdx = findTopLevelOp(expr, "*");
+ if (mulIdx != -1) {
+ Object a = evalExpression(expr.substring(0, mulIdx), scope, env);
+ Object b = evalExpression(expr.substring(mulIdx + 1), scope, env);
+ if (isIntegral(a) && isIntegral(b)) {
+ return toIntegralResult(a, b, ((Number) a).longValue() * ((Number) b).longValue());
+ }
+ return toDouble(a) * toDouble(b);
+ }
+ int divIdx = findTopLevelOp(expr, "/");
+ if (divIdx != -1) {
+ double a = toDouble(evalExpression(expr.substring(0, divIdx), scope, env));
+ double b = toDouble(evalExpression(expr.substring(divIdx + 1), scope, env));
+ return b != 0 ? a / b : 0;
+ }
+
+ // Unary NOT: !
+ if (expr.startsWith("!")) {
+ return !isTruthy(evalExpression(expr.substring(1), scope, env));
+ }
+
+ // Unary Negation: -
+ if (expr.startsWith("-")) {
+ return -toDouble(evalExpression(expr.substring(1), scope, env));
+ }
+
+ // Literals
+ if (expr.startsWith("\"") && expr.endsWith("\"") && expr.length() >= 2) {
+ return expr.substring(1, expr.length() - 1);
+ }
+ if ("true".equalsIgnoreCase(expr)) return Boolean.TRUE;
+ if ("false".equalsIgnoreCase(expr)) return Boolean.FALSE;
+ if ("null".equalsIgnoreCase(expr)) return null;
+
+ if (expr.matches("^0[xX][0-9a-fA-F]+$")) {
+ return (int) Long.parseLong(expr.substring(2), 16);
+ }
+ if (expr.matches("^-?\\d+$")) {
+ try {
+ return Integer.parseInt(expr);
+ } catch (NumberFormatException e) {
+ return Long.parseLong(expr);
+ }
+ }
+ if (expr.matches("^-?\\d*\\.\\d+$")) {
+ return Double.parseDouble(expr);
+ }
+
+ // Method invocation or member access: obj.method(args) or func(args)
+ if (expr.endsWith(")")) {
+ int openParen = findMethodOpenParen(expr);
+ if (openParen != -1) {
+ String callerAndMethod = expr.substring(0, openParen).trim();
+ String argsStr = expr.substring(openParen + 1, expr.length() - 1).trim();
+ List