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; } }