Compare commits

..
27 Commits
Author SHA1 Message Date
Josh Shippam 60463d7c31 Client, Script & Plugin Improvements (#687)
* fix(audio,client): start music immediately on login/track change and remove non-HD tooltip jitter

Eliminates artificial client-side music start and fade-out delays across all platforms, prioritizes music packets at the start of server login, and replaces jittery non-HD hover tooltips in Game.java.

### Core & Client Rendering
- 2006Scape Client/src/main/java/Game.java:
  - Updated method49() to call method853(musicVolume2, is, aBoolean995) directly on all platforms instead of routing through method684/method899 fade-out queues.
  - Reset anInt720 to 0 in constructMusic(), method853(), and method368() when stopped so the initial track and post-login music start without a 20-tick (~400ms) delay.
  - Replaced the non-HD chatTextDrawingArea.method390(..., loopCycle / 1000, ...) fallback with chatTextDrawingArea.textLeftShadow(...) so Walk here and hover tooltips render crisply with HD disabled.

### Server Login Audio
- 2006Scape Server/src/main/java/com/rs2/net/PacketSender.java:
  - Moved music/sound volume configs (168, 169), player.getPlayList().sendMusicConfigs(), and Music.playMusic(player) to run right after frame 249 and duplicate-login checks in loginPlayer(), flushing the login song before quest, skill, sidebar, and equipment packets.

* refactor(ui): use ClientSettings.SERVER_NAME in Plugin Hub modal title

Replaces the hardcoded RUNELITE prefix in the Plugin Hub modal header with ClientSettings.SERVER_NAME so the UI branding stays consistent with the configured server name.

### UI & Styling
- 2006Scape Client/src/main/java/PluginPanelUI.java:
  - Updated drawViewportModal title formatting to use ClientSettings.SERVER_NAME + " PLUGIN & SCRIPT HUB" (and " PLUGIN HUB" when scripts are unavailable).

* feat(client): migrate Ground Items and Menu Entry Swapper plugins to online repository

Removes the built-in `GroundItemsOverlayPlugin` and `MenuEntrySwapperPlugin` classes from the client bundle so players install them manually from the Online Repo tab (`2006scape-plugins`), and adds minimal `ScriptInterpreter`, `PluginContext`, and `PluginGraphics` host support so both plugins run natively in the interpreted plugin dialect.

### Plugin Host Infrastructure
- `ScriptInterpreter.java`:
  - Added `@defaultEnabled` metadata parsing (`ScriptMetadata.defaultEnabled`) and overrode `InterpretedPlugin.isEnabledByDefault()`.
  - Registered `MenuEntry.class` in `compile(String)` so interpreted plugins can invoke `MenuEntry.stripColorTags(...)` and menu entry helpers.
  - Overrode `InterpretedPlugin.onCommand(String, String[])` to forward chat commands (`command`, joined `args`) to interpreted plugins.
- `PluginContext.java`:
  - Added `createList()` and `createMap()` collection helpers for interpreted plugins.
- `PluginGraphics.java`:
  - Added `worldToScreenList(int, int, int)` returning a 2-element `List<Integer>` for array-free coordinate projection.

### Cleanups & Deprecations
- `PluginManager.java`:
  - Removed `MenuEntrySwapperPlugin` and `GroundItemsOverlayPlugin` registrations from `registerBuiltIns()`, leaving `Hd317Plugin`.
- `MenuEntrySwapperPlugin.java`, `GroundItemsOverlayPlugin.java`:
  - Removed built-in plugin classes (migrated to `2006scape-plugins/plugins/MenuEntrySwapper.java` and `GroundItems.java`).

* perf(plugins): optimize ScriptInterpreter/PluginContext and fix Web Online Repo SHA lookup

Improve script/plugin execution speed for TeaVM/Web and Desktop/Android, add throttled in-game chat error reporting, and fix Online Repo commit SHA resolution on Web.

### Script & Plugin Engine
- `PluginContext.java`
  - Added `getGroundItems(int radius)` to scan only `[plx - radius, plx + radius]` x `[ply - radius, ply + radius]` instead of the full 104x104 tile grid, with a `game == null` fallback to `getGroundItems()` for unit test mocks.
- `ScriptInterpreter.java`
  - Pre-parsed `FunctionDef` bodies into `List<Stmt>` (`parseBlock`, `parseIfStatement`, `parseSimpleStatement`) at compile time, removing per-execution substring scanning in `executeStmts`.
  - Added `METHOD_CACHE` (`getCachedMethods`) to index public methods by lowercase name per `Class<?>`, eliminating repeated `clazz.getMethods()` scans in `invokeReflectiveMethod`.
  - Added `Environment.reportedErrors` and `reportRuntimeError` to surface the first uncaught runtime error per function to in-game chat.
- `PluginManager.java`
  - Added `reportedPluginErrors` (cleared on `reloadExternal()`) and `reportPluginError` across `onGameTick`, `onPostBuildMenu`, and `onRenderOverlays` to surface the first error per plugin/phase to in-game chat.

### Online Repository
- `PluginRepoClient.java`
  - Added `REPO_COMMIT_API_URL` using `PLUGIN_REPO_SLUG` (`2006-Scape/Client-Extensions`) and `PLUGIN_REPO_BRANCH` (`main`) as a CORS-friendly fallback in `resolveLatestMainSha()` when `.git/info/refs` is unavailable in the browser.

* perf(graphics): add native drawTileLabelBatches for ground item overlays

Move per-frame ground item tile and label rendering loops from interpreted script execution into compiled Java on `PluginGraphics` to eliminate per-frame TeaVM reflection and AST overhead.

### Graphics Pipeline
- `PluginGraphics.java`
  - Added `drawTileLabelBatches(List<?>, int, int)` to project cached tile coordinates (`worldToScreen` with `worldToScreenList` fallback for unit test mocks), lazily cache `getTextWidth`, render lootbeams, and draw label boxes/text in compiled Java.

* perf(plugins): add ground item signature and native tile batch builder to PluginContext

Eliminate periodic stutters caused by `GroundItems` rebuilding its tile cache in `ScriptInterpreter` every 500ms by providing a zero-allocation ground item fingerprint and compiled batch builder.

### Plugin API
- `PluginContext.java`
  - Added `getGroundItemsSignature(int radius)` to compute a lightweight FNV-1a fingerprint of ground items within `radius` tiles without allocating `GroundItemWrapper` objects or looking up `ItemDef`.
  - Added `buildGroundItemTiles(...)` to perform wildcard filtering, duplicate collapsing, sorting, label/quantity/value formatting, and border/lootbeam preparation in compiled Java.

* refactor(plugins): remove GroundItems-specific buildGroundItemTiles from PluginContext

Keep `PluginContext` limited to generic client API primitives (`getGroundItems(int)` and `getGroundItemsSignature(int)`) while moving Ground Items-specific grouping, tier coloring, and label formatting back into the plugin.

### Cleanups & Deprecations
- `PluginContext.java`
  - Removed `buildGroundItemTiles(...)` and its private helpers (`matchesAnyPattern`, `getGroundItemColor`, `formatItemQuantity`, `formatItemValue`) along with unused `Map`/`HashMap`/`LinkedHashMap` imports.

* feat(scripts): add ternary, modulo, compound assignments, constructors, list literals, and indexing

Expand `ScriptInterpreter` expression and statement support to simplify plugin and script authoring across Desktop, Android, and Web.

### Script & Plugin Engine
- `ScriptInterpreter.java`
  - Added short-circuiting ternary (`cond ? a : b` with `findMatchingTernaryColon`), `%` modulo operator, and unified `+=`, `-=`, `*=`, `/=`, `%=` compound assignments.
  - Added `target[index]` reads and `target[index] = value` writes for `List`, `Map`, arrays, and `String`, plus bracket-aware `findTopLevelOp` and `parseArguments`.
  - Added `[a, b, c]` list literals and `new ClassName(...)` constructors (`ArrayList`, `HashMap`, `LinkedHashMap`, `HashSet`, `StringBuilder`, `WorldArea`, `MenuEntry`, plus reflective constructor fallback).
  - Fast-pathed `StringBuilder` (`append`, `toString`, `length`, `setLength`) in `invokeMethod` and fixed `findMethodOpenParen` to ignore parentheses inside string literals.
- `ScriptInterpreterTest.java`
  - Added `evaluatesTernaryModuloConstructorsAndIndexing` covering ternary, `%`, `*=`, `/=`, `%=`, list literals, `new HashMap()`, `new StringBuilder()`, indexing, and unbalanced parentheses inside strings.

* fix(scripts): support long literals with L suffix in ScriptInterpreter

Parse integer literals ending in `l` or `L` (e.g. `0L`) as `Long` instead of returning `null`.

### Bug Fixes & Edge Cases
- `ScriptInterpreter.java`
  - Added `^-?\d+[lL]$` literal handling in `evalExpression` before standard integer literal parsing.

* feat(scripts): add for/for-each/switch/break/continue, braceless blocks, and TeaVM fast-paths

Expand `ScriptInterpreter` control-flow support and add direct non-reflective fast-paths for `PluginContext`, `PluginGraphics`, `MenuEntry`, and `GroundItemWrapper` to eliminate TeaVM `Class.getMethods()` `ReferenceError`s and per-tick reflection overhead.

### Script & Plugin Engine
- `ScriptInterpreter.java`
  - Added `for (init; cond; update)`, enhanced `for (var : iterable)`, `switch`/`case`/`default`, `break`/`continue` (`BreakSignal`, `ContinueSignal`), and braceless single-statement bodies (`parseBodyOrSingleStatement`) for `if`, `else`, `while`, and `for`.
  - Added direct fast-paths in `invokeMethod` for `PluginContext` (`isLoggedIn`, `getGroundItems`, `getGroundItemsSignature`, `createList`, `createMap`, `sendClientMessage`, `getPlayerX`, `getPlayerY`, `getPlayerAnim`, `isBankOpen`, `getInventoryCount`, `walkTo`), `PluginContext.GroundItemWrapper` (`getDistance`), `MenuEntry` (`stripColorTags`, `matches`, `getAction`, `getTarget`, `getRawText`, `setRawText`), and `PluginGraphics` (`drawTileLabelBatches`, `fillRect`, `drawRect`, `drawCenteredString`, `drawString`, `drawStringBold`, `getTextWidth`, `getTextWidthBold`, `worldToScreenList`, `drawLootbeam`, `getViewportWidth`, `getViewportHeight`).
  - Added `try/catch` guard around `clazz.getMethods()` in `getCachedMethods` and included `[expr|phase]` diagnostics in `reportRuntimeError`.

### Unit Tests
- `ScriptInterpreterTest.java`
  - Added `evaluatesForLoopsBreakContinueBracelessAndSwitch` covering `for`, `for-each`, `break`, `continue`, braceless `if`, `switch` fallthrough/default, and `MenuEntry` fast-paths.

* feat(plugin-hub): add multi-line STRING config editor overlay and localStorage config seeding

Replaces the non-editable "(Edit in .properties or chat)" placeholder in Plugin Hub settings with an interactive multi-line text editor overlay supporting cursor navigation and click positioning. Also seeds plugin settings on first boot and adds live localStorage reload support for web/cross-platform storage editing.

### Command Infrastructure
- `PluginManager.java`:
  - Added `reloadStorage()` and `applyConfigToPlugin(...)` so external storage edits hot-reload `2006scape_plugin_settings` and `2006scape_script_*` entries into active plugins and scripts.
  - Updated `loadConfig()` to call `saveConfig()` when `DesktopHooks.loadPluginConfig()` returns `null`, seeding `2006scape_plugin_settings` on first boot.
- `RSApplet.java`:
  - Queued Left (`1`) and Right (`2`) arrow keys into `charQueue` when `PluginPanelUI.isSearchFocused()` is true so arrow-key cursor movement reaches the modal editor without affecting normal gameplay.

### UI & Edge Cases
- `PluginPanelUI.java`:
  - Replaced `(Edit in .properties or chat)` with a `220px` preview box in `drawConfigEditor` and `handleConfigTab`.
  - Added `drawConfigStringEditorOverlay`, `getStringEditorBounds`, and `wrapTextForWidth` to render a focused multi-line wrapped editor (up to 1,024 chars) with Clear, Cancel, and Save buttons.
  - Added `editingStringCursor` with Left/Right arrow, Home/End, mid-string insert/backspace, vertical gold caret rendering, auto-scroll to keep the cursor line visible, and pixel-accurate click-to-place-cursor support.
  - Added `commitStringEdit(PluginManager)` to auto-commit on blur, Back, or Close.
2026-12-02 18:29:47 +00:00
Josh Shippam c37e3e8dfb Various Changes & Issue Fixes (#686)
* fix(client): restore authentic 317/377 minimap fallback walk radius in doWalkTo

Restores the client-side pathfinding fallback search radius in `Game.doWalkTo` to match authentic 2006 RS2 / 317 client behavior when clicking unreachable tiles such as underground void or blocked terrain. Previously, the search radius was restricted to a single tile, causing minimap and ground clicks more than one tile into unwalkable areas to be silently ignored.

### Bug Fixes & Edge Cases
- `2006Scape Client/src/main/java/Game.java` (`doWalkTo`):
  - Expanded the alternative-destination search loop from `k5 < 2` (1-tile radius) to `k5 < 11` (10-tile Chebyshev radius, matching authentic 317/377 clients) when `flag` is `true` and the exact target tile is unreachable.
  - Preserves the existing `i5 = 100` maximum path-cost threshold and `104x104` region boundary checks (`i6 >= 0 && l6 >= 0 && i6 < 104 && l6 < 104`), allowing players to walk to the nearest reachable tile when clicking black void on the minimap.

Closes #380

* fix(firemaking): fix fire lighting race, object sync, level scaling, and log walk-on

Fixes firemaking reliability, object lifecycle desyncs, and authentic 2006 RS2 movement and level-scaling behavior on the server. Previously, rapid firemaking could cancel the next attempt and still spawn phantom ashes, fires were spawned on hardcoded height 0 with mismatched ObjectManager/ObjectHandler state, and ground-log lighting triggered from an adjacent tile instead of walking onto the logs first.

### Bug Fixes & Edge Cases
- `2006Scape Server/src/main/java/com/rs2/game/content/skills/firemaking/Firemaking.java`:
  - Removed the delayed `stopFiremaking(c)` call from the 2-tick post-lighting `turnPlayerTo` event so rapid consecutive firemaking attempts no longer cancel the next log's cycle.
  - Moved the `100 + Misc.random(98)` tick fire-despawn and ashes (`592`) event inside the lit branch so aborted/cancelled attempts never leave behind phantom ashes.
  - Spawned fires on `c.heightLevel` (instead of `0`) and removed `fireObj` directly from `GameEngine.objectManager.objects` via `updateObject(fireObj)` on burnout, eliminating `ObjectManager` stale-entry desyncs.
  - Replaced the redundant 4-iteration `firemakingItems` loop with `isFiremakingItem(...)`, gated colored firelighters (`7329`, `7330`, `7331`) to regular logs (`1511`), and ensured `stopFiremaking` / skilling interruptions call `container.stop()`.
- `2006Scape Server/src/main/java/com/rs2/game/items/UseItem.java`:
  - Fixed the `||` / `&&` operator precedence bug on `firemakingItems` checks and added `break` after matching a firemaking item.
- `2006Scape Server/src/main/java/com/rs2/net/packets/impl/ItemOnGroundItem.java`:
  - Added `isFiremakingItem(...)` and `isInRange(...)` so using a tinderbox or firelighter on ground logs requires standing on `(gItemX, gItemY)` rather than stopping 1 tile away.

### Authentic 2006 RS2 Behavior
- `2006Scape Server/src/main/java/com/rs2/game/content/skills/firemaking/Firemaking.java`:
  - Moved `Region.getClipping` step-off (`West -> East -> South -> North`) and `walkTo` to execute when the fire catches rather than when lighting begins, and turned the player to `(x, y)` after stepping off.
  - Added `canLightLog(int level, LogData log)` using RS2 `interpolate(low, high, level)` rolls out of 256 (re-rolling every 3 ticks on failure with animation `733` and `SoundList.FIRE_LIGHT`).
- `2006Scape Server/src/main/java/com/rs2/world/clip/Region.java` & `Firemaking.java`:
  - Added `Region.hasSceneryObject(x, y, z)` (`objectType >= 9 && objectType != 22`) and `Firemaking.isTileBlocked(x, y, height)` checking `ObjectManager`, `ObjectHandler`, static scenery objects, and tile clipping (`0x1280100`) before starting and before spawning the fire.

Closes #295
Closes #543

* fix(objects): preserve cache-defined orientation when opening and closing chests

Fixes chest and toggleable object rotation bugs where opening or closing an object not listed in `ObjectDefaults.GET_FACE` rotated it to face South (`0`), and `OpenObject` passed swapped `type`/`face` arguments to `Region.addObject`. Looking up the existing object's orientation from `Region` and `ObjectHandler` ensures all toggleable objects preserve their cache-defined facing across the world.

### Bug Fixes & Edge Cases
- `2006Scape Server/src/main/java/com/rs2/game/objects/ObjectDefaults.java`:
  - Updated `getObjectFace(Player, int)` to check `Region.getObject(...)` and `GameEngine.objectHandler.objectExists(...)` for the current object's `objectFace` before falling back to the hardcoded `GET_FACE` / `switch` defaults.
- `2006Scape Server/src/main/java/com/rs2/game/objects/impl/OpenObject.java`:
  - Preserved the object's `face` and `objectType` when toggling between closed and open IDs in `OBJECT_DATA`.
  - Removed the previous object from `Region` and `GameEngine.objectHandler.globalObjects` before adding and placing the toggled object, and fixed the swapped `type`/`face` parameter order in `Region.addObject(newId, x, y, h, type, face, false)`.

Closes #549

* fix(desert): start desert heat timer on entry and remove shared static state

Fixes instantaneous desert heat damage when entering the desert, eliminates per-tick `CycleEvent` accumulation, and removes shared `static` state across players. Previously, `player.lastDesert` defaulted to `0` on login and was never reset on exit, causing immediate damage on the first tick inside `Boundary.DESERT`, while `Player.process()` queued a new `CycleEvent` every tick.

### Bug Fixes & Edge Cases
- `2006Scape Server/src/main/java/com/rs2/game/players/Player.java`:
  - Updated `process()` to invoke `DesertHeat.callHeat(this)` unconditionally so `lastDesert` resets whenever the player leaves `Boundary.DESERT`, moves off `heightLevel == 0`, or enters `Boundary.NO_HEAT`.
- `2006Scape Server/src/main/java/com/rs2/game/content/traveling/DesertHeat.java`:
  - Initialized `player.lastDesert = now` on desert heat entry (`lastDesert == 0`) instead of applying damage on the first tick, and reset `lastDesert = 0` when outside desert heat.
  - Evaluated the `90s` base (`+10s` per equipped desert clothing piece) timer directly per tick in `callHeat(Player)` rather than spawning duplicate 1-tick `CycleEvent`s.
  - Replaced shared `static int DAMAGE` and `static int waterskin` fields with per-hit `1 + Misc.random(9)` (`1-10`) damage rolls and a local `checkWaterskin(Player)` loop.
  - Replaced hardcoded waterskin item IDs with `StaticItemList.WATERSKIN0` through `StaticItemList.WATERSKIN4` ordered from lowest to highest dose.

Closes #596

* fix(shops): start restock timer on purchase from full stock

Fixes instantaneous restocking of the first item purchased from a fully stocked shop and cleans up shop tick processing. Previously, `shopItemsRestock[shop_id][j]` remained `0` (or stale) when a player bought from full stock, causing `ShopHandler.process()` to immediately restock 1 item on the next tick.

### Bug Fixes & Edge Cases
- `2006Scape Server/src/main/java/com/rs2/game/shops/ShopHandler.java`:
  - Updated `buyItem(int, int, int)` to set `shopItemsRestock[shop_id][j] = System.currentTimeMillis()` and reset `shopItemsDelay[shop_id][j] = 0` when a purchase reduces stock from at/above standard stock (`shopItemsSN`) to below `shopItemsSN`, without resetting an in-progress restock timer on subsequent purchases.
  - Fixed the off-by-one standard-stock boundary in `process()` (`j < shopItemsStandard[i]` instead of `<=`), removed the redundant `shopItemsDelay[i][j] = 1;` assignment, and gated `refreshshop(i)` on `shopUpdated` so unchanged shops are not broadcast every tick.
  - Cleared `shopItemsRestock[shopID][ArrayID] = 0` in `ResetItem(int, int)` when a shop slot is emptied.

Closes #595

* feat(randomevents): migrate random events, lamps, and Thessalia to Kotlin plugins and add ::randomevent

Rewrite all legacy Java random events, experience lamps, and Thessalia interactions into Kotlin plugins under plugins/game/content/randomevents/, plugins/game/content/items/lamps/, plugins/npc/thessalia/, and Revision 377 quest packages, while adding Zanaris Choir and developer testing commands. Core Java hooks now post RandomActionEvent and NpcDeathEvent, preserve legacy save migration via PlayerPluginData, and enforce authentic 2006 RS2 (Revision 377) mechanics, dialogues, and variable XP rate scaling.

### Command Infrastructure
- `RandomActionEvent.java` & `NpcDeathEvent.java`:
  - Added core event classes posted from skilling/action/shop handlers (`Fishing`, `Woodcutting`, `Mining`, `Prayer`, `ShopAssistant.openShop`, `Cooking`, `Potatoes`, `Runecrafting`, `SoftClay`, `SearchForTraps`, `Pickpocket`, `Stalls`, `MagicTeleports`, `PlayerAssistant`, `NpcHandler`) and NPC death processing.
- `ClickNPC.java` & `NpcHandler.java`:
  - Fixed `ClickNPC` to pass `npc.npcId` instead of `player.npcClickIndex` (which `firstClickNpc` resets to `0`) to `NpcFirstClickEvent`.
  - Added `NpcHandler.spawnNpcReturn` and guarded `npcs[i] == null` after `Player.postNpcTick` to prevent NPEs when tick plugins despawn NPCs.
- `Player.java` & `PlayerSave.java`:
  - Removed obsolete random event fields from `Player` while migrating legacy `randomActions` and `recievedReward` save keys into `PlayerPluginData`.

### Migrated Command Plugins
- `RandomToggle.kt` (`::random`, `::randomtoggle`, `::togglerandom`):
  - Migrated `randomEventsEnabled` toggling out of `Commands.java` into `plugins/commands/`.
- `Teleport.kt` (`::teleport`, `::tele`):
  - Added `zanaris` (`2452, 4470, 0`) to `NAMED_LOCATIONS` and `VALID_CITIES_MESSAGES`.

### New Search Commands
- `TriggerRandomEvent.kt` (`::randomevent <name>`, `::randomevents`, `::revent`):
  - Added developer command plugin to trigger `sandwich`, `chicken`, `forester`, `swarm`, `genie`, `frog`, `troll`, `golem`, `spirit`, `shade`, `zombie`, and `choir` on demand, with multi-line help and Zanaris location hint.

### Random Event & Lamp Plugins
- `RandomEventSupport.kt`, `RandomEventDispatcherPlugin.kt`, `RandomEventNpcDeathPlugin.kt`, & `RandomEventFollowPlugin.kt`:
  - Implemented per-player session state, clipped adjacent tile spawning, active NPC slot tracking, unified non-combat NPC following/facing/despawn (`GENIE`, `SANDWICH_LADY`, `FROG_PRINCE`, `FROG_PRINCESS`, `ZANARIS_CHOIR`), and global guards (`randomEventsEnabled`, `!inFightCaves()`, `tutorialProgress >= 36`, `MONKEY_GREEGREE`).
- `CombatRandoms.kt`:
  - Unified `EvilChicken`, `RiverTroll` (Fishing), `RockGolem` (Mining), `TreeSpirit` (Woodcutting), `Shade` & `Zombie` (Prayer bone burying), and `Swarm` with full `3..138` combat level coverage.
- `GeniePlugin.kt`, `SandwichLadyPlugin.kt`, `SandwichLadyTalkPlugin.kt`, `FrogPlugin.kt`, `FreakyForesterPlugin.kt`, `FreakyForesterPortalPlugin.kt`, `ZanarisChoirPlugin.kt`, & `ZanarisChoirTalkPlugin.kt`:
  - Implemented authentic 2006 RS2 NPC spawns, dialogues (`Master`/`Mistress` Genie greeting, Kiss-the-Frog, Freaky Forester 1–4 tail pheasants, Sandwich Lady tray `16135`, Zanaris Choir), and `DialogueFactory.onAction` reward/despawn sequencing.
- `LampInterfaceSupport.kt` & Revision 377 Lamp Plugins:
  - Replaced `ExperienceLamp.java` with config `261` (`1..21`) skill highlighting and `VARIABLE_XP_RATE` / `XP_RATE` scaling across Genie Lamp (`2528`, `10 * level`), One Small Favour (`4447`, level 30+, `10,000` XP), A Tail of Two Cats (`6543`, level 30+, `2,500` XP), Shadow of the Storm (`6796`, combat skills, `10,000` XP), and Recipe for Disaster (`7498`, level 50+, `20,000` XP).
- `ThessaliaFirstClickPlugin.kt` & `ThessaliaSecondClickPlugin.kt`:
  - Migrated Thessalia (`548`) Talk-to shop/Frog Token (`6183`) exchange and Trade (`shop 12`) actions out of `DialogueHandler` and `Shops.java` into `plugins/npc/thessalia/`.

### Cleanups & Deprecations
- Removed all 12 legacy Java classes under `com/rs2/game/content/randomevents/`, `ExperienceLamp.java`, and dead random-event/dialogue/button hooks across `ClickingButtons.java`, `ClickItem.java`, `DialogueHandler.java`, `NpcActions.java`, `ObjectsActions.java`, and `Shops.java`.

* feat(audio): overhaul 377 music, audio playback, and GameOptionsPlugin

Overhauls the 2006Scape Server and Client audio systems to match authentic 2006 RS2 (Revision 377) behavior, fixing MIDI deadlocks, volume persistence, title-screen music handoff, and varp-driven track unlocking. Consolidates all interface 904 Settings-tab buttons into a single Kotlin plugin and populates PlayList and Music with cache-verified 377 track and region mappings.

### Audio & Client Playback Fixes
- `Class56_Sub1_Sub1.java` & `Class56.java` & `Class56_Sub1_Sub2.java`
  - Split `RECEIVER_LOCK` from `MIDI_LOCK` so Java Sound's `Sequencer.stop()` cannot deadlock against `Receiver.send(...)` when switching tracks.
  - Replaced `method835(0, i, -1L)` with `method840(i, -1L)` in `method827` to reset all 16 channel volumes and unconditionally apply `musicVolume` on track changes.
  - Added `setLoop(boolean loop, boolean restartIfStopped)` to toggle looping live via `config 19` and rewind/restart finished tracks when `LOOP` is enabled while unmuted.
- `Game.java` & `DesktopHooks.java` & `SoundPlayer.java`
  - Stops title-screen `Scape Main` on login (`method55(false); currentSong = -1;`) so region music starts immediately.
  - Respects `!loggedIn || variousSettings[19] == 1` for track looping while keeping jingles one-shot.
  - Replaced unbounded per-sound thread creation in `SoundPlayer` with a 4-thread daemon executor and try-with-resources stream/line cleanup, and fixed `DesktopHooks` MIDI receiver/synthesizer cleanup.
- `HdMaterial.java`
  - Added `populateSingleLayer(int layerId, ByteBuffer diffuseLayerBuf, ByteBuffer normalLayerBuf)` sharing `writeLayerToBuffers` for memory-constrained Android texture streaming.

### Server Music & Playlist Architecture
- `PlayList.java`
  - Mapped all 383 clickable songs from `interface 962` to cache-verified `idx3` MIDI IDs and the 14 native RS2 music unlock varps (`20, 21, 22, 23, 24, 25, 298, 311, 346, 414, 464, 598, 662, 721`), fixing 25 legacy mis-mapped song IDs and `FAITHLESS` `childId` (`10129`).
  - Replaced `fixAllColors()` `sendColor` bursts with `sendMusicConfigs()` sending the 14 music varps plus `config 18` (`AUTO`/`MAN`) and `config 19` (`LOOP`), handling `Strange Place` (`464`, bit `17`) natively.
  - Fixed `AUTO` (`24125`), `MAN` (`24126`), and `LOOP` (`38197`) action button IDs in `handleButton`.
- `Music.java`
  - Expanded `MUSIC_DATA` to 517 unique regions cross-checked against the 377 `map_index`, `LostCityRS`, and OSRS Wiki polygons, and fixed Ape Atoll `(43, 43)` to `303` (`Monkey Madness`) and 73 legacy mismatches.
  - Removed `player.musicOn` gates in `Music.playMusic`, `ChangeRegions`, `ClickingButtons`, and `PacketSender.login` so tracks still unlock and `PlayList` controls work while muted.
- `PacketSender.java` & `Player.java` & `PlayerSave.java`
  - Flushed `sendSong` immediately and standardized `sendSound` on packet 174 (`id`, `volume`, `delay`).
  - Persisted `musicVolume`, `soundVolume`, `mouseButton`, `chatEffects`, and `acceptAid` in `PlayerSave` and synced configs `168`, `169`, `170`, `171`, `287`, and `427` on login.

### New & Migrated Plugins
- `GameOptionsPlugin.kt`
  - Migrated `BrightnessButtons.java`, `MusicVolumeButtons.java`, `SoundVolumeButtons.java`, and `ToggleSplitChatButtons.java` plus `Mouse Buttons` (`3145`/`3146`), `Chat Effects` (`3147`/`3148`), and `Accept Aid` (`48176`/`48177`) into a single Kotlin plugin using named constants and lookup maps, removing legacy `500`–`503` configs and stale `74176`/`74180`/`74188` cases from `ClickingButtons.java`.
- `UnlockSongs.kt`
  - Added developer command `::unlocksongs` (`::unlockmusic`, `::allsongs`) to unlock all playlist tracks and refresh music varps.

* fix(client): replace ThreadFactory lambda in SoundPlayer for JDK 8 javac

Replaces the `ThreadFactory` lambda in `SoundPlayer.SOUND_EXECUTOR` with an anonymous `ThreadFactory` class to resolve a JDK 8 `javac` definite-assignment bug (`variable r might not have been initialized`) hit by GitHub Actions CI on PR #686.

### Bug Fixes
- `SoundPlayer.java`
  - Replaced `r -> { ... }` in `Executors.newFixedThreadPool(4, ...)` with an anonymous `ThreadFactory` implementation.

* refactor(combat): replace DeprecatedItems.getItemName with ItemDefinition.lookup in AutocastCancelButtonPlugin

Removes the deprecated `DeprecatedItems.getItemName(weaponId)` call from `AutocastCancelButtonPlugin.kt` in favor of `ItemDefinition.lookup(weaponId)?.name`, eliminating the Kotlin compiler deprecation warning.

### Cleanups & Deprecations
- `AutocastCancelButtonPlugin.kt`
  - Replaced `DeprecatedItems.getItemName(weaponId)` with `ItemDefinition.lookup(weaponId)?.name ?: "Unarmed"` (preserving `"Unarmed"` when `weaponId == -1`).

* build(maven): set explicit UTF-8 source and reporting encoding across modules

Configures `project.build.sourceEncoding` and `project.reporting.outputEncoding` to `UTF-8` in the root and server POMs so resource filtering and Java compilation are platform-independent and free of platform-encoding warnings.

### Build Configuration
- `pom.xml` & `2006Scape Server/pom.xml`
  - Added `<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>` and `<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>`.

* style(client): fix space-before-tab indentation in Class56_Sub1_Sub2

Replace mixed space-and-tab indentation with spaces in Class56_Sub1_Sub2 to clear the git diff --check whitespace lint prior to merging PR #686.

### Cleanups & Deprecations
- 2006Scape Client/src/main/java/Class56_Sub1_Sub2.java:
  - Normalized line 34 indentation inside setLoop(boolean, boolean) from space-before-tab to 8 spaces.

* fix(audio): remove post-377 Stronghold of Security song entries from Music

Remove the four legacy Stronghold of Security region music mappings from Music.java so MUSIC_DATA stays strictly aligned with Revision 377 (May 2006) tracks and PlayList idx3 entries.

### Cleanups & Deprecations
- 2006Scape Server/src/main/java/com/rs2/game/content/music/Music.java:
  - Removed pre-existing post-377 Stronghold of Security entries { 29, 81, 537 }, { 31, 81, 558 }, { 33, 82, 559 }, and { 36, 81, 560 } from MUSIC_DATA.
2026-12-02 00:08:13 +00:00
Josh Shippamandipkpjersi 26f1c6d2ac Read Description (#685)
* refactor(commands): organize command plugins into permission-tiered subfolders

* feat(commands): Rename Drops Command to SearchDrops and make Drops an alias

* refactor(client): remove unofficial client-side search command implementation

Remove the hardcoded client-side ::search command interception and definitionSearch
handler from Game.java in favor of the server-side interface-driven
search plugins (::searchitem, ::searchnpc, and ::searchdrops).

### Input Handling
- Game.java:
  - Remove ::search prefix checks and inputDialogState mutators during character
    typing and backspacing in the chatbox input loop.

### Cleanups & Deprecations
- Game.java:
  - Remove definitionSearch(String, int) method, eliminating unused client-side
    item/NPC/object cache iteration, fake bank interface manipulation, and local
    chat message flooding.

* feat(clipping): implement authentic 377 object and npc reachability, collision bounds, and fallback pathfinding

Implements authentic Revision 377 RS2 collision detection, object interaction reachability, and fallback pathfinding across the game server. Replaces custom coordinate workarounds and hardcoded checks with cache-driven collision rules, decoding opcode 69 (`walkToMask`) and enforcing authentic line-of-sight and perimeter validation for both objects and entities. When an unreachable entity or object is clicked, pathfinding smoothly navigates the player to the nearest valid alternative tile before halting with an authentic "I can't reach that." message.

### Core System Architecture
* `Region.java`:
  - Implemented `canReach` to handle all standard RS2 object types: wall objects (types 0–3, 9), wall decorations (types 6–8), multi-tile landscape objects (types 10–11), and ground decorations (type 22).
  - Implemented `canReachObject` supporting rectangular object bounding boxes ($sizeX \times sizeY$) and directional walk-to masks rotated according to object orientation (`(walkToMask << face & 0xf) | (walkToMask >> (4 - face))`).
  - Implemented `canReachNpcMelee` strictly enforcing cardinal adjacency for $1 \times 1$ NPCs while allowing diagonal melee contact against larger monsters ($size > 1$) when intervening corners are unblocked.
  - Implemented `canReachNpc` supporting distance-2 interactions over impassable low barriers (e.g. bank counters, tables) by validating that the intermediate tile is collision-blocked (`(getClipping & 0x1280100) != 0`) while projectile line-of-sight remains clear.
* `ObjectDefinitionDecoder.java` & `ObjectDefinition.java`:
  - Decoded opcode 69 (`walkToMask`) from the Revision 377 cache definition buffer (`definition.setWalkToMask(data.get() & 0xFF)`).
  - Added `walkToMask` getter and setter to `ObjectDefinition`.
* `PathFinder.java`:
  - Updated `findRoute` to return a `boolean` status indicating whether an authentic path or closest alternative destination was found.
  - Handled the edge case where the closest alternative coordinate matches the player's current coordinate (`curX == player.getLocalX() && curY == player.getLocalY()`), clearing the queue and returning `false`.
* `Objects.java`:
  - Added safety boundaries against negative or out-of-range object definitions (`objectId < 0 || objectId >= ObjectDefinition.count()`).
  - Added `getWalkToMask()` helper delegating to the decoded `ObjectDefinition`.

### Object & NPC Interaction Infrastructure
* `ClickObject.java`:
  - Implemented `isObjectReached` combining `Region.canReach`, door reachability (`Doors.canReachDoor`, `DoubleDoors.canReachDoor`), and generic door/gate adjacency.
  - Added fallback pathfinding (`PathFinder.findRoute(player, objectX, objectY, true, size[0], size[1])`) when an unreachable object is clicked from a distance.
  - Triggered instant interaction upon reaching interaction bounds (`if (reached)`), stopping character movement and resetting the walking queue without tick lag.
  - Replaced raw magic numbers with `StaticObjectList` (`TARGET_2513`, `DRAMEN_TREE`, `TREE_2409`) and `StaticNpcList` (`TREE_SPIRIT_655`, `SHAMUS`) constants.
* `ClickNPC.java`:
  - Extracted shared interaction logic across `FIRST_CLICK`, `SECOND_CLICK`, and `THIRD_CLICK` into a unified `handleNpcInteraction(Player, int, Consumer<Npc>)` method, removing redundant cycle event boilerplate.
  - Added fallback pathfinding towards the target NPC's bounds on initial click if not immediately reachable.
  - Ensured `"I can't reach that."` is sent only after walking finishes at the closest blocking perimeter (e.g. Al-Kharid border fence).
* `ItemOnNpc.java`:
  - Added NPC array index and null validation (`i < 0 || i >= NpcHandler.npcs.length || NpcHandler.npcs[i] == null`).
  - Added reachability check via `Region.canReachNpc`, halting player movement and sending `"I can't reach that."` if unreachable.
  - Replaced raw item and NPC magic numbers with `StaticItemList` (`SHEARS`, `WOOL`, `COINS_995`, `BUCKET_OF_MILK`, `BUCKET`, `SEASONED_SARDINE`, `FLUFFS_KITTEN`) and `StaticNpcList` (`TOOL_LEPRECHAUN`, `SHEEP_43`, `EMILY`, `GERTRUDES_CAT_2997`) constants.
* `PlayerAssistant.java`:
  - Implemented `getFollowNpcLocation` to determine the closest reachable perimeter tile around an NPC, preventing invalid diagonal melee coordinates for $1 \times 1$ NPCs.
  - Consolidated fallback route error handling in `followNpc()` for both melee and ranged/magic attack paths.
* `Player.java`:
  - Prevented walking directly inside an NPC's collision tile during combat and interaction approach in `getNextWalkingDirection()`.

### Combat Collision & Line of Sight
* `CombatAssistant.java`:
  - Added `Region.canReachNpcMelee` verification in both `attackingNpcTick()` and `attackNpc()` to prevent hitting NPCs through walls or fences.
  - Added projectile path clearance verification (`PathFinder.isProjectilePathClear`) for ranged weapons, bows, magic spells, and halberds.
  - Cleared attack and follow state cleanly when a target cannot be reached without freezing character movement.

### Doors & Gates Mechanics
* `GateHandler.java` & `DoubleGates.java`:
  - Replaced raw gate IDs with `StaticObjectList` constants (`GATE_1551`, `GATE_1552`, `GATE_7049`, `GATE_7050`, `GATE_7051`, `GATE_7052`, etc.).
  - Added `getOpenGateId`, `getClosedGateId`, and `isOpenGate` to support toggling open gates shut on interaction.
  - Consolidated `openDoubleGate` to delegate directly to `openSpecialGate`, eliminating redundant gate despawn/respawn code.
  - Added `SoundList.OPEN_GATE` audio triggers on gate interaction.
* `Doors.java` & `DoubleDoors.java`:
  - Added `canReachDoor(player, id, x, y, z)` proximity checking for both single and double doors, allowing players to reach doors by checking both current and original coordinates within distance 1.
  - Removed unused `isDoor` dead helper methods.

### Cleanups & Deprecations
* `Woodcutting.java`:
  - Removed custom coordinate check hack `p.absX == 2717 && p.absY == 3461` ("You can't cut the tree from here!"), now natively handled by authentic object collision bounds.
  - Removed redundant movement stopping inside `startWoodcutting`, now handled uniformly at the packet level in `ClickObject.java`.
* `BorderGuardFirstClick.kt`:
  - Removed plugin-specific coordinate gate check (`absX <= 3267`) and redundant `facePlayer` calls, relying on global collision flags and `ClickNPC.java` pathfinding.

* feat(client): implement android modern resizable viewport support and platform gating

Add dynamic viewport sizing and modern resizable display mode hooks to the shared 317 client while strictly isolating all mobile changes behind platform checks. All additions are gated behind ClientSettings.ANDROID and ClientSettings.RESIZABLE flags so that desktop client rendering, coordinates, and fixed 512x334 gameplay remain 100% authentic and unaffected. This enables Android Mobile to render an edge-to-edge 3D world with floating HUD panels while guaranteeing complete regression-free desktop parity.

### System Architecture
- Game.java:
  - Introduce updateViewportSize(int width, int height) synchronized method to dynamically resize the aRSImageProducer_1165 viewport buffer, recalculate texture scanline offsets, and invoke WorldController.method310 with custom dimensions.
  - Enforce explicit ClientSettings.ANDROID platform guards across all viewport-dimension checks to ensure desktop builds unconditionally retain fixed 512x334 behavior.

### Display & Viewport Handling
- WorldController.java:
  - Adjust vertical camera offset (anInt494) in portrait mobile mode to (int) (l * 0.38f) when ClientSettings.ANDROID && ClientSettings.RESIZABLE && k < l, ensuring the player character remains centered above bottom UI sheets, falling back to authentic l / 2 on desktop and landscape.
- Game.java:
  - Gate action tooltip coordinates behind ClientSettings.ANDROID: modern mobile displays render at (16, 28) in portrait or (72, 28) in landscape, while desktop preserves the original 317 baseline at (4, 15).
  - Gate debug and XP overlay positions behind platform checks, preventing mobile offsets from shifting desktop stats.
  - Retain desktop frame border drawing (drawFixedFrameBorders()) unconditionally whenever needDrawFrameBorders is raised.

### Input & Click Hit-Testing
- Game.java:
  - Update touch target validation in processChatModeClick(), processMinimapActions(), and processTabClick() to verify ClientSettings.ANDROID && (ClientSettings.RESIZABLE || ClientSettings.VIEWPORT_WIDTH > 512).
  - Preserve standard 317 desktop tab boundary hit-testing (saveClickX >= 539 && saveClickX <= 573, etc.) when !ClientSettings.ANDROID.
  - Update custom settings tab and scrollbar hit-testing to respect target touch areas without altering desktop mouse interactions.

* refactor(server): clean up redundant interaction checks, consolidate packet logic, and harden packet boundaries

Consolidates redundant distance checks and interaction logic made obsolete by cache-driven Revision 377 collision and reachability systems across the server. Enforces strict array bounds and packet validation on item, object, player, and magic interaction packets to prevent remote exploitation and index out-of-bounds exceptions. Eliminates memory leaks, duplicate iterations, and legacy PI distance hacks while preserving 2006 RS2 gameplay authenticity.

### Core & Packet Infrastructure
* `AttackPlayer.java`:
  - Added strict array index boundary checks (`player.playerIndex < 0 || player.playerIndex >= PlayerHandler.players.length || PlayerHandler.players[player.playerIndex] == null`) for both `ATTACK_PLAYER` and `MAGE_PLAYER` packets.
  - Replaced dead/impossible non-crystal bow condition (`playerEquipment < 4212 && playerEquipment > 4223`) with `!RangeData.usingCrystalBow(player)` to correctly trigger the out-of-arrows message in PvP.
* `ClickNPC.java`:
  - Added array index and null validation on `player.npcIndex` in `ATTACK_NPC` and `MAGE_NPC` packet processing.
  - Removed duplicate `NpcHandler.npcs[player.npcIndex] == null` check in `ATTACK_NPC`.
  - Replaced dead condition (`< 4212 && > 4223`) with `!RangeData.usingCrystalBow(player)` in PvN combat.
* `FollowPlayer.java`:
  - Added index boundary validation on target `followPlayer` ID before array indexing.
* `Walking.java`:
  - Removed 47 lines of legacy commented-out walking packet code to keep the packet pipeline clean.

### Reachability & Interaction Handlers
* `ItemOnObject.java`:
  - Migrated from crude Manhattan distance (`goodDistance(..., 3)`) to `ClickObject.isObjectReached(...)`, validating object boundaries, facing direction, wall clipping, and cache `walkToMask`.
  - Preserved explicit 5-tile radius for Ectofuntus interactions while halting unreachable attempts with "I can't reach that.".
* `ItemOnPlayer.java`:
  - Added authentic 1-tile reachability distance check (`!player.goodDistance(..., 1)`) with "I can't reach that." before Christmas cracker interactions.
  - Added array boundary validation for `playerId` and inventory `slot`.
  - Replaced magic number `962` with `StaticItemList.CHRISTMAS_CRACKER`.
* `ItemOnGroundItem.java`:
  - Added authentic 1-tile reachability check (`!player.goodDistance(..., 1)`) with "I can't reach that." before firemaking ground logs, preventing remote fire lighting.
  - Replaced magic numbers `590`, `7329`, `7330`, and `7331` with `StaticItemList` constants (`TINDERBOX`, `RED_FIRELIGHTER`, `GREEN_FIRELIGHTER`, `BLUE_FIRELIGHTER`).
* `ItemClick2OnGroundItem.java`:
  - Removed debugging `System.out.println(...)` output.
  - Replaced magic number `590` with `StaticItemList.TINDERBOX`.
* `ItemOnItem.java`:
  - Added boundary validation on `usedWithSlot` and `itemUsedSlot` before indexing `player.playerItems`.
* `MagicOnObject.java`:
  - Added `player.endCurrentTask()` to properly cancel active player walking/skilling events.
  - Added `Region.objectExists` check and a 4-tile reachability check (`!player.goodDistance(..., 4)`) with "I can't reach that.", preventing remote orb charging.
  - Replaced raw magic numbers `2150..2153` with `StaticObjectList` constants (`OBELISK_OF_EARTH`, `OBELISK_OF_WATER`, `OBELISK_OF_AIR`, `OBELISK_OF_FIRE`).
* `MagicOnFloorItems.java`:
  - Removed redundant second `player.stopMovement()` call inside telegrab packet handling.

### Door & World Object Mechanics
* `ChangeRegions.java`:
  - Removed redundant and harmful `Doors.getSingleton().load();` call on region loading (packet 121), which repeatedly re-read `doors.json` from disk and duplicated door instances in memory.
* `Doors.java` & `DoubleDoors.java`:
  - Replaced raw distance calculations in `Doors.handleDoor` with `canReachDoor(player, id, x, y, z)`.
  - Added `canReachDoor` check to `DoubleDoors.handleDoor` before processing double door state changes.
* `ClickObject.java`:
  - Removed obsolete `> 25` tile check in `completeObjectClick` (already guaranteed reachable by `onObjectReached`).
  - Removed redundant `stopMovement()` and `resetWalkingQueue()` calls in `case 9472` (already performed upon reach).
  - Replaced raw target ID `2513` with `StaticObjectList.TARGET_2513`.
* `AlKharidGateFirstClick.kt`:
  - Removed redundant `if (!isNearGate(player))` check, as `ClickObject.isObjectReached` already enforces gate reachability prior to event dispatch.

### Bug Fixes & Edge Cases
* `NpcActions.java`:
  - Removed erroneous `player.turnPlayerTo(player.objectX, player.objectY)` in `case 8689` (dairy cow milking), which incorrectly rotated the player to face coordinates `(0, 0)` due to uninitialized object coordinates in NPC packets.
* `ObjectsActions.java`:
  - Removed duplicate `player.turnPlayerTo(player.objectX, player.objectY)` calls in lines 1413, 1417, and 1887, already handled uniformly at the start of `ClickObject.completeObjectClick`.
* `DropItem.java` & `PickupItem.java`:
  - Consolidated duplicate consecutive loops over `LogData.values()` into a single loop with an early `break;`.
  - Removed redundant duplicate `resetPlayerAttack()` call in `PickupItem.java`.

### Cleanups & Deprecations
* `Woodcutting.java`:
  - Removed legacy PI distance check `if (Misc.goodDistance(p.objectX, p.objectY, p.absX, p.absY, 3))` in `startWoodcutting`, now handled by authentic 377 collision bounds in `ClickObject.java`.
  - Removed redundant duplicate `if (p.isWoodcutting)` guard inside `startWoodcutting`.
* `Fishing.java` & `SilverCrafting.java`:
  - Removed redundant chained `.toLowerCase().toLowerCase()` invocations in chat and message strings.

* feat(client): add android platform hooks and 117hd pipeline bridge behind ClientSettings.ANDROID

Integrates dynamic viewport sizing and pure-Java 117HD GPU pipeline bridge hooks into the shared 317 client codebase while strictly isolating all mobile features behind ClientSettings.ANDROID. Ensures 100% authentic fixed 512x334 Revision 377 desktop gameplay without file duplication between desktop and mobile repositories.

### Core / System Architecture
- `HD117Pipeline.java`:
  - Introduced pure-Java GPU bridge interface (`HdRendererBackend`) strictly gated by `ClientSettings.ANDROID && ClientSettings.HD_117`.
  - Defined callback lifecycle signatures for scene upload, per-frame camera matrix uniform updates, simple/shaped tile dispatch, and model rendering.
- `Game.java`:
  - Added synchronized `updateViewportSize(int width, int height)` and `setHD117Enabled(boolean enabled)` guarded by `ClientSettings.ANDROID`.
  - Gated mobile touch target areas (`TARGET_VIEWPORT`, `TARGET_MINIMAP`, `TARGET_TAB`) and responsive action tooltips behind `ClientSettings.ANDROID`.
- `ClientSettings.java`:
  - Added `RESIZABLE` and `HD_117` flags (`false` by default on desktop) and made RSA modulus/exponent mutable for mobile world switching.

### Display & Viewport Handling
- `WorldController.java`:
  - Gated portrait mobile camera vertical offset `(int) (l * 0.38f)` behind `ClientSettings.ANDROID && ClientSettings.RESIZABLE && k < l`, defaulting to authentic `l / 2` on desktop.
  - Implemented concentric ring tile traversal `r = 0..drawDistance` and 3D frustum culling (`isHdTileInFrustum`) gated behind `ClientSettings.ANDROID && ClientSettings.HD_117 && HD117Pipeline.isGpuActive()`.
- `Model.java`:
  - Gated near-plane clipping threshold `(ClientSettings.ANDROID ? 20 : 50)` so desktop retains authentic 50-unit threshold.
  - Preserved vertex normals and model GPU dispatch strictly when `ClientSettings.ANDROID` is active.
- `Class40.java` & `Class43.java`:
  - Gated overlay face and tile tracking strictly behind `ClientSettings.ANDROID`.

### Bug Fixes & Edge Cases
- `ObjectManager.java`:
  - Gated upper-floor ground tile roof checking (`!hideRoofs && !lowMem`) behind `ClientSettings.ANDROID`, ensuring Lumbridge Castle gatehouse upper floors render properly on mobile while preserving authentic desktop `hideBuggyVarrockSwordShopSnow`.

### Submodule Updates
- `2006Scape-Android`:
  - Updated submodule pointer to commit `8b74a318` containing v3.32 launcher UI polish and 117HD OpenGL ES 3.0 renderer.

* chore(mobile): update 2006Scape-Android submodule to v3.33 authentic rs2 launcher ui

Updates the 2006Scape-Android mobile submodule to commit 11e754e2. Integrates authentic 2006 RS2 beveled stone boxes, crimson-and-gold login buttons, and custom stone checkmark widgets.

### Submodule Updates
- `2006Scape-Android`:
  - Updated submodule pointer to commit `11e754e2` containing v3.33 authentic 2006 RS2 launcher redesign.

* feat(mobile): update android submodule to v3.34 with live world indicators and stone dividers

Updates the Android mobile client submodule to release v3.34. Introduces real-time server socket reachability indicators on world selector buttons and classic 2006 RS2 etched stone bevel dividers framing launcher panels without modifying server or desktop client logic.

### UI & Visual Improvements
- `2006Scape-Android`:
  - Added live socket connectivity pings to World 1 (port 43594) and World 2 (port 43598).
  - Integrated authentic etched stone bevel dividers (`divider_rs_stone.xml`) under the header and across configuration sections.
  - Formatted Display Mode selectors with two-line layout descriptions (`Fixed 4:3` and `Resizable`).
  - Bumped release version to v3.34 (versionCode 94).

* feat(mobile): update android submodule to v3.35 with classic touch ribbon toggle

Updates the Android mobile submodule to release v3.35. Adds a user setting in the client launcher to enable or disable onscreen touch ribbons when running in Classic (Fixed 4:3) display mode.

### Migrated Features
- `2006Scape-Android`:
  - Added `Classic Mode Touch Ribbons` launcher toggle under Client Features.
  - Wired preference persistence and intent propagation into `GameSurfaceView`.
  - Bumped release build to v3.35 (versionCode 95).

* feat(mobile): update android submodule to v3.36 with classic portrait console and landscape lock

Updates the Android mobile submodule to release v3.36. Integrates portrait bottom console layout for Classic (Fixed 4:3) mode and a launcher toggle to lock landscape orientation.

### UI & Visual Improvements
- `2006Scape-Android`:
  - Added dedicated two-row bottom thumb console for portrait orientation in Classic mode.
  - Added `Lock Landscape in Classic` startup preference toggle.
  - Clamped ribbon text width and added landscape safety bounds checks.
  - Bumped release build to v3.36 (versionCode 96).

* feat(mobile): update android submodule to v3.37 with portrait launcher support

Updates the Android mobile submodule to release v3.37. Adds full portrait orientation support to the client launcher with a dedicated stacked panel layout and bottom-anchored Play button.

### UI & Visual Improvements
- `2006Scape-Android`:
  - Created `res/layout-port/activity_launcher.xml` for portrait orientation.
  - Enabled dynamic orientation handling in `LauncherActivity.java` with instant status cache preservation.
  - Bumped release build to v3.37 (versionCode 97).

* fix(mobile): update android submodule to v3.38 with centered classic portrait canvas

Updates the Android mobile submodule to release v3.38. Restores exact vertical centering for the 4:3 game canvas in Classic mode across all screen orientations.

### UI & Visual Improvements
- `2006Scape-Android`:
  - Centered the 4:3 game canvas vertically in portrait mode.
  - Positioned the portrait touch console inside the lower letterbox region below the centered view.
  - Bumped release build to v3.38 (versionCode 98).

* feat(mobile): update android submodule to v3.39 with authentic cache sprite ribbons

Updates the Android mobile submodule to release v3.39. Introduces authentic Revision 377 game cache sprite rendering for mobile touch ribbons, accompanied by 3D beveled stone button tiles, RS Red-Stone active tab fills, live rotating compass needle, and glowing runic gems.

### UI & Visual Formatting
- `2006Scape-Android`:
  - Converted Revision 377 `sideIcons` and `compass` sprite into ARGB Android Bitmaps with nearest-neighbor crisp filtering.
  - Implemented 3D beveled stone tiles with directional chisel lighting (top/left highlight, bottom/right shadow).
  - Added authentic RS Red-Stone active tab fills (`#731818`) with glowing gold borders (`#FFD700`).
  - Added dynamic real-time compass yaw rotation on the NORTH button tracking `game.minimapInt1`.
  - Added RuneScape Gold (`#FF981F`) and Yellow (`#FFFF00`) typography with authentic 1px solid black drop-shadows.
  - Added 3D glowing runic gems for utility controls (`DROP` emerald green, `117 HD` cyan).
  - Added medieval stone backing pillars in landscape and unified console deck in portrait.
  - Bumped release build to v3.39 (versionCode 99).

* fix(mobile): update android submodule to v3.40 with masked circular compass

Updates the Android mobile submodule to release v3.40. Masks out the raw Revision 377 red square boundary surrounding the circular compass sprite for clean presentation on the ribbon stone tile.

### UI & Visual Formatting
- `2006Scape-Android`:
  - Clipped raw `compass` sprite to its circular diameter (`dx^2 + dy^2 <= r^2`).
  - Chroma-keyed the red border pixels to 100% transparency.
  - Bumped release build to v3.40 (versionCode 100).

* fix(mobile): update android submodule to v3.41 with enlarged tightly cropped compass

Updates the Android mobile submodule to release v3.41. Tightly crops the circular compass rose and scales it up to 35dp to match the prominent size of the other tab sprites.

### UI & Visual Formatting
- `2006Scape-Android`:
  - Cropped non-transparent compass bounds tightly, removing outer dead space.
  - Centered the cropped circular compass rose inside an exact square bitmap.
  - Omitted sublabel on the NORTH button and raised icon size to 35dp.
  - Bumped release build to v3.41 (versionCode 101).

* feat(mobile): update android submodule to v3.42 with 1:1 authentic tab order ribbons

Updates the Android mobile submodule to release v3.42. Reorders the touch ribbons so that the left ribbon (and portrait row 1) directly mirrors the game's top-row tabs (0..6), and the right ribbon (portrait row 2) mirrors the bottom-row tabs (7..13).

### UI & Visual Formatting
- `2006Scape-Android`:
  - Reordered left buttons to: NORTH, Combat (0), Stats (1), Quests (2), Inventory (3), Equip (4), Prayer (5), Magic (6), DROP.
  - Reordered right buttons to: CHAT, QoL (7), Friends (8), Ignore (9), Logout (10), Options (11), Music (13), 117 HD, 60 FPS.
  - Bumped release build to v3.42 (versionCode 102).

* fix(renderer): dynamic camera traversal bounds and GPU clipping for 117 HD terrain

Resolve missing terrain tiles during camera rotation and zoom in 117 HD mode by dynamically expanding the traversal radius around the player and delegating frustum culling to GPU hardware. Preserves Revision 377 client compatibility while preventing camera orbit clipping across region boundaries.

### Core Architecture
- `WorldController.java`:
  - Calculate `effectiveDrawDist` dynamically using `Math.min(60, drawDistance + (hdCamDistToPlayer >> 7) + 12)` for Android HD mode.
  - Expand loop bounds `anInt449..anInt450` and `anInt451..anInt452` to prevent camera orbit culling at map borders.
  - Remove inaccurate 2D CPU screen-space frustum bounds checking in favor of exact hardware OpenGL ES 3.0 clipping.
  - Retain safe camera-depth rejection (`cz < -1280`) to protect shadow casters and multi-tile structures behind the camera.

* feat(renderer): extended software draw distance, synchronized model culling, and QoL zoom gating

Synchronize 3D model culling with active terrain boundaries to prevent entities from floating over the black void, dynamically extend software draw distance during camera orbit zoom, and gate zoom controls in classic display mode behind the QoL client argument. Maintains exact Revision 377 parity while improving visual consistency on mobile widescreen viewports.

### Core Architecture
- `WorldController.java`:
  - Calculate `effectiveDrawDist` dynamically up to 38 tiles in software mode on Android based on camera-to-player orbit distance (`hdCamDistToPlayer`).
  - Update rasterizer `loopDist` to use `effectiveDrawDist` in software passes so ground tiles fully cover the playfield when zoomed out.
  - Expose `effectiveDrawDist` as a public static field for entity and model distance synchronization.
- `Model.java`:
  - In software mode on Android, clamp model draw distance strictly to `effectiveDrawDist * 128 + 128` to guarantee models are never rendered over unrendered ground voids.
  - In 117 HD mode, scale model distance to match dynamic fog horizon (`4800+` units).
  - Preserve desktop Revision 377 culling formula (`drawDistance * 256`) when not running on Android.
- `Game.java`:
  - Update `hdCamDistToPlayer` across all Android display modes regardless of whether 117 HD is toggled on or off.
  - Restrict `adjustZoom` and `handleMouseWheel` in fixed classic display mode (`!RESIZABLE`) so camera zoom is locked to 0 unless `CUSTOM_SETTINGS_TAB` (QoL) is enabled.

* feat(client): add -resizable modern desktop layout with shared ModernLayout engine and floating stone HUD overlays

Implement a native resizable modern window mode for the desktop client activated via the `-resizable` (or `-resize`) launch argument while preserving 100% shared source parity with the Android client. Consolidates layout geometry, elliptical/rounded-corner hit-testing, and coordinate translation into a pure-Java `ModernLayout` class, and renders zero-flicker double-buffered floating Revision 377 stone HUD widgets (circular lizard minimap, stone-framed chatbox, and symmetrical 4-way masked rounded stone tab block).

### Core / System Architecture
- `ModernLayout.java`:
  - Implemented platform-neutral layout engine with zero `java.awt` or `android.*` imports for automatic sharing with the Android `syncSharedSources` build pipeline.
  - Added `hit(int x, int y)` routing cursor and click coordinates to `TARGET_MINIMAP`, `TARGET_TAB`, `TARGET_CHAT`, `TARGET_VIEWPORT`, or `TARGET_DEFAULT` when `!inGame`.
  - Implemented `isInsideMinimap(int localX, int localY)` using circular compass bounds ($r = 16$ at $(16, 16)$) and elliptical map bounds ($R_x = 76, R_y = 78$ at $(132, 84)$) so clicks in transparent air fall through to `TARGET_VIEWPORT`.
  - Implemented `isInsideTabArea(int localX, int localY)` with a 4-way symmetrical corner inset profile (`TAB_CORNER_DX`) matching the sculpted Revision 377 corner stone contour ($234 \times 335$ active ring inside the $249 \times 343$ region).
  - Added `toGameCoords(int area, int x, int y)` and `toWindow(int fixedX, int fixedY, int width, int height)` for bidirectional mapping between dynamic window dimensions and classic $765 \times 503$ coordinates.
- `ClientSettings.java`:
  - Added `isModernLayout()`, `isDesktopModern()`, `usesTouchTargets()`, and `usesClassicTabHitboxes()` predicates to unify desktop resizable and Android modern layout conditionals.
- `ClientArgs.java`:
  - Added `-resizable` and `-resize` launch arguments enabling `ClientSettings.RESIZABLE = true` and automatically hiding the top browser navigation bar (`ClientSettings.SHOW_NAVBAR = false`).

### UI & Visual Formatting
- `DesktopHooks.java` & `AndroidHooks.java`:
  - Added offscreen double buffering (`getRenderGraphics` and `flip`) backed by a window-sized `BufferedImage` so 3D viewport rendering and floating HUD overlays composite atomically without 50 Hz screen flickering.
  - Implemented `drawModernMinimap` compositing the live $172 \times 156$ minimap producer (`1164`) masked via `AlphaComposite.DstIn` against `hud_minimap_hole.png` and overlaid with `hud_minimap_bezel.png` at $(w - 249, 0)$.
  - Implemented `drawModernChat` compositing `hud_chat_frame.png` ($519 \times 165$) with chat parchment (`1166`, $479 \times 96$) at $(17, 19)$ and chat buttons (`1123`, $496 \times 50$) at $(0, 115)$, docked at $(0, h - 165)$.
  - Implemented `drawModernTab` stitching the 3-part left vertical stone pillar (`backVmidIP2` $37 \times 133$, `backVmidIP2_2` $553 \times 19$ rightmost $37\text{px}$, and `backVmidIP3` $57 \times 109$ rightmost $37\text{px}$) alongside top tabs (`1125`), tab body (`1163`), right pillar (`backRightIP2`), and left-cropped bottom tabs (`1124` at offset $20\text{px}$), masked to 100% transparency outside the rounded stone contour.
- `hud_chat_frame.png`, `hud_minimap_bezel.png`, & `hud_minimap_hole.png`:
  - Added authentic floating stone HUD bezel and alpha mask resources to `2006Scape Client/src/main/resources/`.

### Bug Fixes & Edge Cases
- `Game.java`:
  - Added `applyWindowSize(int w, int h)` and `drawModernDesktopOverlays()` to dynamically resize the 3D software rasterizer and `WorldController` frustum while docking floating HUD overlays.
  - Tracked `ModernLayout.inGame` across `drawLoginScreen()`, `drawGameScreen()`, and `resetLogout()` so the 9-tile login screen and fullscreen interfaces center cleanly with black letterboxing.
  - Fixed `processLoginScreenInput()` to evaluate button hitboxes against the $765 \times 503$ reference frame rather than dynamic window dimensions.
- `RSFrame.java`, `RSApplet.java`, & `RSImageProducer.java`:
  - Enabled window resizing and maximize controls when `ClientSettings.RESIZABLE` is active, enforcing a minimum frame size of $765 \times 503$ plus window insets.
  - Queued `ComponentListener` resize events safely onto the game thread via `pendingResize` and mapped mouse press, move, drag, and wheel events through `ModernLayout`.

* feat(client): add aspect-ratio-scaled login and loading screens with flicker-free resize rendering

Scale and center the classic 765x503 Revision 377 login screen and startup loading progress bars across resizable desktop window dimensions to match the Android client's welcomeScale architecture. Consolidates background tile assembly and offscreen bilinear scaling into a thread-synchronized composite buffer, eliminating multi-threaded race conditions between game rendering and flame animations while preserving aspect-ratio-locked button hitboxes. Implements flicker-free live window resizing by handling AWT paint cycles immediately and suppressing front-buffer background erasures.

### System Architecture
- `ModernLayout.java`:
  - Added `getScaledScreenBounds(int w, int h)` computing aspect-ratio-preserved scaled dimensions and centering offsets `[originX, originY, scaledW, scaledH]`.
  - Updated `toGameCoords` and `toWindow` when `!inGame` to bidirectionally project cursor inputs and full-screen coordinates between scaled window dimensions and the classic 765x503 reference coordinate space.
- `DesktopHooks.java`:
  - Added `updateLoginTile()` and `redrawScaledLoginScreen()` synchronized under a dedicated `loginLock` mutex to serialize buffer updates across the main game loop, flame worker thread, and AWT Event Dispatch Thread.
  - Implemented smooth bilinear interpolation (`KEY_INTERPOLATION` / `VALUE_INTERPOLATION_BILINEAR`) scaling from `loginScreenBuffer` to dynamic window bounds with clean black letterbox/pillarbox margins.
  - Decoupled tile `1110` (left torch) from triggering intermediate screen blits so both torch flames composite atomically and flip on tile `1111` (right torch).
  - Implemented `checkResize(Component comp)` to synchronously synchronize window dimensions during early startup.

### UI & Visual Formatting
- `Game.java`:
  - In `drawLogo()`, atomically populates all 9 background tiles (`1107` through `1115`) into `loginScreenBuffer` as soon as `title.dat` and `logo` are decoded, guaranteeing complete stone archway, pillars, and logo coverage during all loading stages.
  - In `drawLoadingText()`, polls window resizing via `DesktopHooks.checkResize()` on each loading step so progress bars ("Unpacking config", "Unpacking textures", etc.) remain centered and scaled to window height on top of the background.
- `RSApplet.java`:
  - Enabled `sun.awt.noerasebackground` on client frame creation and suppressed live `graphics.fillRect(0, 0, w, h)` clears in `handleResize()` when modern desktop mode is active to prevent front-buffer black flashes.
  - Routed `paint(Graphics g)` and `update(Graphics g)` during `!inGame` directly into `DesktopHooks.redrawScaledLoginScreen(g)`, repainting the scaled buffer immediately on every AWT expose event without waiting for background game loop ticks.
  - In `componentResized(ComponentEvent e)`, updates `ModernLayout` bounds and triggers immediate offscreen repaint during interactive window dragging.
- `RSImageProducer.java`:
  - Intercepts 765x503 drawing area blits during `!inGame` to route pixel updates directly into `DesktopHooks.drawScaledLoginTile()`.

* feat(client): migrate shared 117 HD core and add desktop OpenGL renderer with -hd flag and ::hd command

Unify the 117 HD / RLHD 3D rendering pipeline across desktop and Android by migrating `HdMaterial`, `HdGroundMaterial`, `HdProceduralGenerator`, `HdSceneUploader`, and GLSL shader definitions into the shared `2006Scape Client` source tree. Introduces `DesktopHd117Renderer` backed by JNA OpenGL (EGL/GLES 3.0+ on Linux and WGL/OpenGL 3.3 on Windows), disabled by default and toggleable via the `-hd` launch argument or the `::hd` in-game client command while preserving full Java 8 `java.nio.Buffer` bytecode compatibility.

### Core / System Architecture
- `HD117Pipeline.java`:
  - Removed `ClientSettings.ANDROID` platform restrictions from `isGpuActive()`, `onSceneLoad()`, `beginFrame()`, `endFrame()`, and `onToggle()` so the 117 HD pipeline operates identically across Desktop and Android.
  - Consolidated the shared GLSL shader sources (`SHADOW_VERT`, `SHADOW_FRAG`, `SCENE_VERT`, `SCENE_FRAG`, `POST_VERT`, `POST_FRAG`), `adaptGlslForDesktop330()`, and pure-Java 4x4 matrix functions (`setLookAtM`, `orthoM`, `multiplyMM`).
- `DesktopHd117Renderer.java` & `pom.xml`:
  - Added `net.java.dev.jna:jna:4.4.0` dependency and implemented `HD117Pipeline.HdRendererBackend` for desktop platforms.
  - Implemented cross-platform offscreen OpenGL context initialization using JNA (`libEGL.so.1` + `libGLESv2.so.2` with `EGL_PLATFORM_SURFACELESS_MESA` fallback on Linux, and `opengl32.dll` / `gdi32.dll` / `user32.dll` WGL OpenGL 3.3 context creation on Windows).
  - Executed the 3-pass 117 HD pipeline: Pass 1 ($2048 \times 2048$ directional sun shadow depth FBO), Pass 2 (3-vertex height-splatted terrain, Sobel normal mapping, 9-tap PCF soft shadows, Fresnel water waves, 16 dynamic point lights, and distance fog), and Pass 3 (5-tap highlight bloom, S-curve tonemapping, and zero-copy BGRA readout into `DrawingArea.pixels`).
- `DesktopHooks.java`:
  - Added `initHdBackend()` to lazily instantiate and register `DesktopHd117Renderer` onto `HD117Pipeline.backend`.

### Migrated 117 HD Shared Modules
- `HdMaterial.java` & `HdGroundMaterial.java`:
  - Migrated material layer definitions (`0..49` enhanced RS2 cache textures and `50..63` procedural 117 HD PBR materials) and the 64-layer $128 \times 128$ RGBA8 diffuse + heightfield and Sobel tangent-space normal-map generator (`populateTextureBuffers`) into shared client sources.
  - Added deterministic spatial vertex hashing (`getMaterialForVertex`) and 317 floor/HSL classification (`resolve`).
- `HdProceduralGenerator.java`:
  - Migrated smooth $105 \times 105$ terrain normal calculation, per-tile underlay/overlay resolution, corner splatting, and dynamic point light extraction from world objects.
  - Added `tileIsIndoor` detection from the RS2 map roof flag (`(byteGroundArray[plane][x][z] & 4) != 0`) and adjacent doorway thresholds.
- `HdSceneUploader.java`:
  - Migrated 64-byte cache-aligned vertex staging for `Class43` simple tiles, `Class40` shaped tiles, and 3D `Model` geometry with exact $(P, M, N)$ texture triangle UV projection.

### New Commands & Launch Arguments
- `ClientArgs.java`:
  - Added `-hd` and `-117hd` launch flags enabling `ClientSettings.HD_117 = true` at startup (disabled by default).
- `Game.java`:
  - Added the `::hd` (and `::117hd`) in-game client command available to all players, toggling `setHD117Enabled(!ClientSettings.HD_117)` and printing `"117 HD is now: enabled"` or `"117 HD is now: disabled"` in the chatbox.
  - Updated `setHD117Enabled(boolean)` and the 3D viewport render pass (`method146`) to support runtime toggling on both Desktop and Android.

### Bug Fixes & Edge Cases
- `HdSceneUploader.java` & `HD117Pipeline.java`:
  - Fixed coplanar stacked polygon Z-fighting on multi-layer models (such as the Varrock Castle blue rug's gold border and white stars, red dining room rug lion crests, and wall shields) by encoding a strictly monotonic per-face priority (`anIntArray1638`) and face-order (`f / faceCount`) fraction into `aMatAndBary.w` and applying a zoom-invariant clip-space depth offset in `SCENE_VERT`.
  - Fixed pillow/cylinder shading distortion on flat horizontal floor models (`vyA == vyB && vyB == vyC`) by assigning pure vertical geometric normals $(0, -1, 0)$ instead of corner normals averaged with vertical perimeter skirts.
  - Fixed indoor castle checkered flooring by assigning roofed interior tiles (`tileIsIndoor`) a uniform, smooth honed architectural stone material (`HD_STONE_PAVERS_2`) without outdoor Voronoi cobblestone bumps or cross-corner dirt splatting, and made `HD_DIRT_1..2` hue-neutral.
  - Replaced GLSL reserved keyword `packed` with `packedVal` in `SCENE_VERT` and cast all `Buffer.position(int)` calls to `((Buffer) ...).position(...)` to prevent `NoSuchMethodError` on Java 8 runtimes.
- `Model.java`, `Class40.java`, & `WorldController.java`:
  - Preserved `hdVertexNormals`, `anIntArray1640`, and `isOverlayFace` during scene loading regardless of initial HD state so toggling `::hd` mid-session renders smooth normals and overlay seams without reloading the map region.

* feat(client): add automatic fixed and modern gameframe switching at original 765x503 size in resizable mode

Decouples desktop window resizability from active modern floating HUD mode so that a `-resizable` client automatically renders the authentic 765x503 classic fixed gameframe (with a 512x334 3D viewport and stone border producers) whenever sized at 765x503, and transitions to the full-window modern floating HUD gameframe whenever expanded beyond 765x503. Preserves full Revision 377 coordinate translation, login screen tile caching, and Android client parity.

### Layout Mode & Coordinate Infrastructure
- `ClientSettings.java`:
  - Updated `isDesktopModern()` to evaluate `!ANDROID && RESIZABLE && (ModernLayout.windowWidth > 765 || ModernLayout.windowHeight > 503)`, distinguishing window resizability (`RESIZABLE`) from the active modern HUD layout.
  - Updated `isModernLayout()` to delegate to `isDesktopModern()` on desktop while preserving `RESIZABLE || VIEWPORT_WIDTH > 512` on Android.
  - Updated `usesTouchTargets()` to return `ANDROID || isDesktopModern()` so hit-area target routing is disabled when the desktop window is at the classic 765x503 dimensions.
- `ModernLayout.java`:
  - Updated `hit(int x, int y)`, `toGameCoords(int area, int x, int y)`, and `toWindow(int fixedX, int fixedY, int width, int height)` guards from `!ClientSettings.RESIZABLE` to `!ClientSettings.isModernLayout()` so fixed-mode coordinates pass through untranslated at 765x503.

### Dynamic Viewport & Gameframe Switching
- `Game.java`:
  - Updated `applyWindowSize(int w, int h)` to dynamically select a `512x334` 3D viewport when `ClientSettings.isDesktopModern()` is false and a full-window `w x h` 3D viewport when `ClientSettings.isDesktopModern()` is true.
  - Set `needDrawFrameBorders = !ClientSettings.isDesktopModern()` and `welcomeScreenRaised = true` on resize so returning to 765x503 immediately redraws all 9 classic stone border image producers (`backLeftIP1..backVmidIP2_2`) and fixed UI panels.
  - Kept `updateViewportSize(int width, int height)`, `drawLogo()`, and `drawLoadingText()` gated on `!ClientSettings.ANDROID && ClientSettings.RESIZABLE` so viewport resizing and login tile caching remain active across all window sizes.
- `DesktopHooks.java`:
  - Updated `checkResize(Component comp)` to run whenever `ClientSettings.RESIZABLE` is enabled on desktop and compute `VIEWPORT_WIDTH` / `VIEWPORT_HEIGHT` as `512x334` at `765x503` or `w x h` when larger.

### AWT Event & Image Producer Routing
- `RSApplet.java`:
  - Registered the AWT `ComponentListener` and routed `createClientFrame`, `paint`, `handleResize`, `componentResized`, and `drawLoadingText` whenever `!ClientSettings.ANDROID && ClientSettings.RESIZABLE` is active.
  - Reset `touchTargetArea = 0` in the `else` branches of `mousePressed`, `mouseDragged`, and `mouseMoved` when `ClientSettings.isDesktopModern()` transitions to false so stale modern HUD hit targets never leak into classic fixed mode.
- `RSImageProducer.java`:
  - Updated `drawGraphics(int i, Graphics g, int k)` to cache login screen tiles via `DesktopHooks.updateLoginTile(...)` whenever `ClientSettings.RESIZABLE && !ClientSettings.ANDROID && !ModernLayout.inGame` is true, while only intercepting with scaled offscreen rendering and `ModernLayout.toWindow(...)` offsets when `ClientSettings.isDesktopModern()` is active.

* fix(combat): resolve autocast interface selection, weapon style sync, and pathfinding clipping

This commit addresses interface synchronization, autocasting state persistence, and authentic 2006 RS2 combat pathfinding and clipping across both player and NPC interactions. Interface 328 configuration bitmasks and style configs have been aligned with authentic Revision 377 cache behavior, ensuring single-style selection and proper style persistence across weapon swaps. Melee reach, projectile line-of-sight, and halberd distance mechanics have been corrected to strictly prevent attacks through solid masonry and low fences.

### Combat Infrastructure
- `Player.java`:
  - Reclassified halberds (`isUsingHally()`) as melee combat under `isMeleeCombat()` while keeping `isUsingProjectileCombat()` strictly for actual ranged and magic attacks.
  - Implemented centralized attack distance calculation supporting bows, darts, throwing knives, magic spells, halberds (distance 2), and standard melee (distance 1).
  - Added authentic `assignAutocast()` handling with interface 328 restoration, spell name text updates on child 352, and bitmask tracking.

### Autocasting & Combat Style Synchronization
- `PlayerAssistant.java` & `ItemAssistant.java`:
  - Enhanced `handleWeaponStyle()` to dynamically evaluate active autocasting versus physical staff attack modes (`0` Bash, `2` Focus-Block, `1` Pound).
  - Wired `handleWeaponStyle()` into `ItemAssistant.sendWeapon()` to ensure equipped styles are immediately highlighted when swapping between swords, bows, and staves.
  - Corrected autocast config 108 bitmask transmission: bit 0 controls active autocast red box (`1`), bit 1 controls spell name visibility (`2`), transmitting `3` when active, `2` when configured, and `0` when reset.
- `ClickingButtons.java`:
  - Dispatched `sendConfig(43, -1)` on autocast selection (buttons 1093/1094 and spell selection) to clear melee style highlights on interface 328, preventing simultaneous dual red box highlights.
  - Added interface cancel/close button handling for normal (1829/2004), ancient (1689/6161), and slayer staff (12050/12101) autocast menus.

### Pathfinding & Collision Clipping
- `Region.java`:
  - Refactored `getClipping(int x, int y, int height, int moveTypeX, int moveTypeY)` to delegate directly to `canMove(x, y, height, dir)` via `Misc.directionFromDelta()`, eliminating start-tile coordinate checks and off-by-one errors on diagonal steps.
  - Relaxed `canReachNpc()` distance-2 halberd checks to allow cardinal attacks across open space as well as projectile-penetrable low barriers (fences, railings, counters).
- `CombatAssistant.java`:
  - Integrated `Region.canReachNpcMelee()` for 1-tile melee and `Region.canReachNpc()` for halberds in `attackingPlayerTick()` and `attackPlayer()`, preventing PvP attacks through fences, closed doors, and walls.
  - Updated NPC melee reach checks in `attackingNpcTick()` and `attackNpc()` to support distance-2 reach when wielding halberds.
  - Updated `getRequiredDistance()` to return `CombatConstants.HALBERD_ATTACK_DISTANCE` when using halberds.
- `NpcData.java` & `NpcCombat.java`:
  - Updated `checkClip(Npc n)` so ranged and magic NPCs (`!melee`) verify `PathFinder.isProjectilePathClear(...)` before launching attacks.
  - Added line-of-sight verification to `multiAttackDamage()` and `multiAttackGfx()` to prevent area spells and dragonfire from penetrating solid obstacles.
- `PlayerAssistant.java`:
  - Enhanced `followPlayer()` so ranged and magic attackers halt upon entering attack distance with a clear projectile line of sight.
  - Updated `getFollowLocation()` so candidate melee tiles evaluate line-of-sight and reach against obstacles.
  - Updated `getFollowNpcLocation()` and `followNpc()` to allow valid 2-tile safe-spotting positions for halberd users.
- `NpcHandler.java`:
  - Updated `followPlayer()` so pursuing NPCs do not freeze when separated by barriers; ranged/magic NPCs require clear projectile paths to halt, while melee NPCs require valid melee reach.

### Bug Fixes & Edge Cases
- `AttackPlayer.java` & `ClickNPC.java`:
  - Unified follow distance initialization to use `player.getAttackDistance()`.
  - Replaced raw projectile checks for halberds with `Region.canReachNpc()` to prevent diagonal distance-2 halberd attacks against NPCs.
  - Handled frozen state attack resets when target cannot be reached behind obstacles.

### Cleanups & Deprecations
- `NpcHandler.java` & `NpcData.java`:
  - Consolidated redundant attack distance checks and removed duplicate hardcoded switch branches.
  - Deprecated legacy hardcoded distance conditionals in favor of unified `distanceRequired()` and `getAttackDistance()` lookups.

* feat(client): isolate modal openInterface into dedicated producer and expose dynamic bounds

This update decouples modal interfaces (Bank, Shop, Trade) from the main game scene rasterizer when running on mobile resizable layouts. By rasterizing modal interfaces into an independent off-screen buffer with transparent backgrounds, the client enables responsive floating positioning without viewport stretching or clipping. Exact interface dimensions are resolved dynamically through the interface cache to eliminate artificial padding and coordinate misalignments.

### Core Architecture & Producer Pipelines
- `src/main/java/Game.java`:
  - Implemented dedicated off-screen `openInterfaceProducer` (12 \times 334$) and pre-allocated line offsets `openInterfaceOffsets` for Android resizable rendering.
  - Initialized isolated drawing area before rasterizing `drawInterface()` and cleared pixels to zero (`DrawingArea.setAllPixelsToZero()`) to ensure transparent compositing over the 3D scene.
  - Added `getOpenInterfaceWidth()` and `getOpenInterfaceHeight()` helper methods querying `RSInterface.interfaceCache` to report true interface boundaries (88 \times 314$ for bank interfaces).
  - Normalized mouse input tracking and scrollbar hit-testing to top-left origin coordinates under mobile resizable configurations.

* fix(client): return canonical 512x334 bounds for modal viewport interfaces

Resolves an issue where query methods for open modal interface dimensions returned sub-container cache widths (e.g. 154x110) rather than the standard 512x334 viewport interface dimensions. In Revision 317, parent interface definitions in cache store sub-element sizes while modal interfaces are rasterized across the standard 512x334 drawing canvas. Returning canonical 512x334 dimensions ensures consumers correctly sample and crop the full interface surface.

### System Architecture & Viewport Dimensions
- `src/main/java/Game.java`:
  - Updated `getOpenInterfaceWidth()` and `getOpenInterfaceHeight()` to return canonical 12 \times 334$ dimensions for all modal viewport interfaces.
  - Eliminated erroneous sub-element `RSInterface.interfaceCache` width/height queries that caused partial rendering and severe viewport cropping.

* fix(client): preserve opaque black text drop shadows and primitive fills

Prevents intentional black text glyphs, text drop shadows, and drawing primitives from being erased as transparent background pixels on direct alpha composited viewports. Remaps zero color arguments (black) to 0x000001 so off-screen alpha producers distinguish drawn black pixels from unwritten transparent background pixels.

### Rasterization & Alpha Transparency
- `src/main/java/TextDrawingArea.java`:
  - Remapped `i1 == 0` in `method392` to `1` (`0x000001`) to ensure drop shadows (`_shadow` pass) and black text render as solid opaque pixels rather than transparent alpha cutouts.
  - Remapped `j1 == 0` in `method394` to `1` for identical shadow preservation across colored text drawing.
- `src/main/java/DrawingArea.java`:
  - Remapped zero color fills and horizontal/vertical drawing lines to `1` to prevent solid black geometric frames from punching transparent holes through modal interfaces.

* fix(client): revert DrawingArea zero-fill color remapping to restore sprite transparency

Reverts zero-color remapping in DrawingArea fillArea and line routines. ItemDef.getSprite initializes transparent 32x32 sprite rasters using DrawingArea.fillArea(32, 0, 0, 32, 0), where color 0 is required as the transparent keying value for sprite clipping. Reverting restores transparent item backgrounds across inventory and bank containers while TextDrawingArea retains opaque black drop shadow preservation for typography.

### Rasterization & Sprites
- `src/main/java/DrawingArea.java`:
  - Reverted `_color == 0` remapping in `fillArea`, `drawHorizontalLine`, and `drawVerticalLine` to restore authentic 0-keyed alpha transparency in dynamic sprite generation.

* feat(plugins): implement client plugin engine, ground items overlay, menu swapper, and script runtime

Implements an extensible client plugin and scripting architecture for 2006Scape, enabling modular overlays, menu modifications, and automation hooks while preserving vanilla 317 client timing and protocol integrity. Replaces the legacy hardcoded QoL options tab with an interactive tab and viewport modal interface for configuring built-in and externally loaded plugins. Integrates seamless cross-platform hooks to support runtime script interpretation, ground item tracking, and dynamic menu action rewrites.

### System Architecture
* `PluginManager.java`:
  * Central singleton managing plugin and script lifecycles (`init`, `onGameTick`, `onRenderOverlays`, `onPostBuildMenu`, `onMenuAction`, `onChatMessage`, `onGroundItemSpawn`, `onCommand`).
  * Implements event dispatching with isolated try-catch error boundaries and state persistence for user preferences.
* `ClientPlugin.java` & `ClientScript.java`:
  * Base lifecycle interfaces defining metadata (`getName`, `getDescription`, `getVersion`, `getAuthor`), configuration schemas, and activation states.
* `PluginContext.java` & `PluginGraphics.java`:
  * Encapsulates safe client interactions, viewport coordinate transforms, world-to-screen projections, and 317 `DrawingArea` rendering utilities.
* `ExternalPluginLoader.java` & `ScriptInterpreter.java`:
  * Facilitates loading external compiled plugins (.jar / .dex) and parsing custom automation scripts at runtime from user storage.

### Migrated Features
* `PluginPanelUI.java`:
  * Migrated legacy Tab 7 options into a modernized in-game plugin configuration hub and interactive modal UI.
  * Implemented clickable toggle buttons, category navigation, dynamic scrollable configuration panels, and modal dismiss handling.
* `Game.java` & `AndroidHooks.java`:
  * Integrated plugin dispatch triggers across game loop ticks, chat message reception, ground item registration, and action menu construction.
  * Added native dialog hooks and bridge methods to delegate plugin management to native Android or desktop modal UIs.

### New Features & Additions
* `GroundItemsOverlayPlugin.java`:
  * Renders world-projected labels and item quantity text for items on the ground with configurable price-tier coloring and despawn timers.
  * Automatically filters and highlights valuable drops based on configurable coin value thresholds.
* `MenuEntrySwapperPlugin.java`:
  * Rewrites contextual right-click option menus to swap default actions (e.g., Talk-to -> Bank/Trade, Shift-click drop).
  * Provides configurable entry prioritization based on opcode and menu index ordering.
* `ChickenFeatherFarmerScript.java`:
  * Example automated routine demonstrating state machine architecture for targeting NPCs, pathing, and collecting dropped items.

### Bug Fixes & Edge Cases
* `processMenuClick`:
  * Intercepts viewport modal click events to prevent unintended pathfinding or entity interaction clicks when interacting with open plugin menus.
* `onGroundItemSpawn`:
  * Validates coordinate bounds and height plane offsets to avoid out-of-bounds array access during region chunk transitions.

* fix(ui): show explicit on-off toggle states and clean up redundant qol buttons

Improves plugin configuration usability by adding explicit visual state rendering and click interactions for boolean and integer config items within the Plugin Hub modal. Cleans up the Tab 7 QoL panel by removing hardcoded buttons for Menu Entry Swapper and Feather Farmer, restoring the canonical client quality-of-life options while delegating plugin controls entirely to the modal hub.

### Core / System Architecture
* `PluginManager.java`:
  * Added `getConfigValue`, `getConfigBoolean`, `getConfigInt`, and `setConfigValue` accessor/mutator methods to query live config properties with default fallbacks.
  * Automatically serializes altered plugin and script configurations to `plugin_settings.properties` and triggers live `onConfigChanged` callbacks.

### UI & Visual Formatting
* `PluginPanelUI.java`:
  * Replaced ambiguous `"TOGGLE"` button labels with explicit colored states: `[ ON ]` with green fill (`0x1e6828`), green border (`0x3cd04f`), and emerald text (`0x50c878`), vs `[ OFF ]` with red fill (`0x6e2222`), red border (`0xd03c3c`), and coral text (`0xff7070`).
  * Added integer value indicators rendered between `[-]` and `[+]` stepper buttons in gold (`0xffd700`).
  * Added touch-forgiving click handling for the Config subtab in `handleModalClick`, allowing instant toggling of boolean settings and bounds-checked stepping of numeric values.

### Cleanups & Deprecations
* `drawTab7` & `handleTab7Click`:
  * Removed redundant persistent buttons for Menu Entry Swapper and Feather Farmer from the Tab 7 sidebar.
  * Restored standard QoL button stack below `PLUGIN HUB [Open Modal]`: Player Names, Item Drops Visible, Draw Distance, Exp Info, Debug Info, and Visual Fixes with 36px vertical stride.

* fix(combat): resolve npc attack opcode mapping and accurate chicken combat tracking

Fixes an issue where the Chicken Feather Farmer script became stuck in a stagnant "Fighting chicken" state while standing idle. Resolves the client NPC interaction action ID mapping to dispatch authentic packet 72 (`ATTACK_NPC`) rather than dialogue packet 155, and introduces precise target-matching logic to discern active combat from passive entity interactions.

### Core / System Architecture
* `PluginContext.java`:
  * `interactNpc`: Explicitly maps the `"Attack"` action to actionId `412` (the 317 client action ID sending packet 72 `ATTACK_NPC`) instead of fallback option index 0 which incorrectly sent packet 155 (`FIRST_CLICK` / `Talk-to`).
  * `getPlayerInteractingNpc`: Added helper to query the exact NPC instance `myPlayer` is currently interacting with via `interactingEntity` bounds validation.
  * `getNpcAttackingPlayer`: Added helper scanning `npcIndices` to detect any NPC currently targeting the player (`npc.interactingEntity == myPlayerIndex + 32768`).
  * `isPlayerInCombat`: Refactored to require an alive, combat-capable opponent (`combatLevel > 0`) or active incoming attacks, eliminating false combat flags caused by previous dialogue interactions (e.g. Fred the Farmer).
  * `NpcWrapper.isDead`: Added check for chicken death animation (`anim == 5389`) in addition to zero health points.

### Migrated Command Plugins
* `ChickenFeatherFarmerScript.java`:
  * Replaced generic `isPlayerInCombat()` / `isPlayerIdle()` check with specific chicken target verification: checks if the player is actively fighting a living chicken or being attacked by one before falling through to target scanning.
  * Automatically retaliates against attacking chickens and dispatches authentic attack interactions to the nearest idle chicken when not in combat.

* fix(combat): resolve NPC fence attack reach, multi-tile wandering clipping, and step-away desync

Enforces authentic 2006 RS2 melee clipping and entity positioning boundaries between players and NPCs across Revision 377 tile and object collision flags. Fixes a critical ray trace off-by-one bug in NPC combat line-of-sight that permitted melee attacks across fences and obstacles, and resolves multi-tile NPC wandering overlap and follow/step-away desynchronization.

### Core / System Architecture
- `Region.java`:
  - Updated `canReachNpcMelee(int playerX, int playerY, int height, int npcX, int npcY, int npcSize)` to perform bidirectional wall and fence collision validation.
  - Ensures both the player's tile (`playerX, playerY`) and the NPC's corresponding border tile (`npcX, playerY`, `npcMaxX, playerY`, etc.) are checked against directional wall bits (`0x8`, `0x80`, `0x2`, `0x20`), preventing attacks across one-sided or multi-sided boundary fences.
- `NpcData.java`:
  - Refactored `checkClip(Npc n)` to eliminate the broken Bresenham ray trace for melee attacks, which previously incremented coordinates to the destination tile before querying clipping flags.
  - Directly delegates melee reach checks to `Region.canReachNpcMelee()`, guaranteeing authentic path and fence blocking, and returns `false` immediately if the target is underneath the NPC (`inNpc`).
  - Preserves `PathFinder.isProjectilePathClear()` for ranged and magic combat, maintaining authentic safespots over low fences.

### Bug Fixes & Edge Cases
- `Npc.java`:
  - Rewrote `getNextWalkingDirection()` player and NPC collision detection from single-tile South-West corner comparison (`p.absX == nextX && p.absY == nextY`) to complete bounding-box footprint validation (`p.absX >= nextX && p.absX < nextX + mySize && p.absY >= nextY && p.absY < nextY + mySize`).
  - Completely prevents multi-tile NPCs (e.g. 2x2 Cows, Bears, 3x3 Demons) from randomly wandering onto and overlapping players.
- `NpcHandler.java`:
  - Made `stepAway()` and `followPlayer()` mutually exclusive during NPC retaliation processing: when `playerInside` is true, the NPC exclusively attempts to step away and cannot initiate attacks.
  - Replaced `getRandomAndHomeNPCWalking()` inside `followPlayer()` with `getNextNPCMovement()`, unifying collision-checked movement and eliminating duplicate coordinate increments and client-server direction desyncs.

* fix(feather-farmer): implement combat target locking and ground bone looting and burying

Resolved multi-target thrashing and missing bone prayer processing in the automated Chicken Feather Farmer script. The client engine now evaluates NPC interacting entity targets against the dynamic server-assigned player ID (unknownInt10) rather than the static local player array index constant, enabling accurate combat detection. Ground bones are now actively collected and sequentially buried within the coop radius while locking onto active combat targets until defeat.

### Script Combat Engine
- `ChickenFeatherFarmerScript.java`:
  - Added stateful target locking (`currentTargetNpcIndex`, `lastAttackTime`) preventing target swapping mid-combat.
  - Implemented `isEngagedWithTarget` to verify target vitality, proximity, and reciprocal interaction state before scanning for new enemies.
  - Prioritized active combat lock and retaliatory defense before ground looting to ensure engagements complete naturally.
  - Added ground bone looting for Item ID 526 ("Bones") and sequential inventory bone burying with 900ms cycle spacing.
  - Enhanced feather looting to bypass inventory full checks when stackable feathers are already in inventory.
  - Accurate chicken kill tracking upon target death detection rather than per-click dispatch.

### Plugin Context Infrastructure
- `PluginContext.java`:
  - Updated `NpcWrapper` to evaluate `isAttackingPlayer` and `isUnderAttackByOther` using `game.unknownInt10` and `game.myPlayerIndex`.
  - Added `getNpcByIndex(int index)` for direct entity inspection by index.
  - Fixed `getNpcAttackingPlayer()` and `findNearestAttackableNpc()` to properly recognise NPCs targeting the local player.
  - Extended death animation detection to cover both Chicken (5389) and Rooster (57) models.

* fix(spawns): adjust Farmer Groat chicken spawn out of stone wall boundary

Resolves an entity placement conflict where a Chicken (NPC 41) spawned directly inside the perimeter stone wall of Farmer Groat's chicken coop near Lumbridge. Revision 377 cache map data places an impassable stone wall (Object 1902) and wall buttress (Object 1838) at tile (3233, 3300), which blocked entity movement and melee attack pathing through the coop boundary. Relocating the spawn coordinates two tiles west inside the coop perimeter restores authentic movement wandering and melee attack reachability.

### Bug Fixes & Edge Cases
- `spawns.json`:
  - Adjusted Chicken spawn X coordinate from 3233 to 3231 at Y=3300 (height 0).
  - Cleared tile collision overlap with Revision 377 East stone wall (Object ID 1902, type 0, orientation 2) and corner buttress (Object ID 1838, type 5, orientation 2).
  - Resolved unreachable melee attack state ("I can't reach that.") caused by directional wall clipping flags (0x8 and 0x80) between pen interior and wall boundary.
  - Enabled proper 1-tile wandering radius within the pen interior bounds (X=3227..3232, Y=3296..3300).

* fix(combat): resolve NPC follow destination clipping and Fred chicken spawns

Resolves entity reachability failures and boundary clipping where Chicken (NPC 41) entities at Farmer Fred's farm wandered into the western stone wall (Object 979) at tile (3184, 3277) and players received "I can't reach that." errors during combat. Melee follow target selection in PlayerAssistant now verifies candidate tiles against solid object clipping flags and pathfinder accessibility, preventing the engine from attempting to path players onto impassable boundary wall or building tiles. Chicken spawn coordinates at Farmer Fred's pen are relocated inward from the boundary to keep wandering paths strictly within the pen interior.

### Combat & Pathfinding Infrastructure
- `PlayerAssistant.java`:
  - Updated `getFollowNpcLocation(Npc npc)` to filter out candidate attack tiles blocked by solid objects (`(getClipping(x, y, player.heightLevel) & 0x1280100) != 0`).
  - Added `PathFinder.accessible()` validation on candidate attack tiles, ensuring the selected destination is genuinely reachable from the player's current location before routing.
  - Prevents nearest-distance selection from picking impassable building or wall tiles (e.g. tile `(3184, 3276)`), eliminating erroneous "I can't reach that." combat lockouts.

### Bug Fixes & Edge Cases
- `spawns.json`:
  - Relocated duplicate chicken spawns at Farmer Fred's coop from `(3185, 3277)` to `(3186, 3277)` and `(3188, 3277)`.
  - Keeps the chickens' 1-tile wandering radius within `X = 3185..3189`, preventing entities from wandering onto the Revision 377 western stone wall line at `X = 3184`.

* fix(npcs): resolve asymmetric wandering bounds in random walking routine

Fixes a fundamental arithmetic and inequality defect in NpcHandler's random walking routine that skewed all 1-tile wandering NPCs into wandering up to two tiles South-West while completely preventing movement North and East. By correcting the proposed coordinate delta evaluation against the NPC's home spawn coordinates, entity wandering now adheres to authentic symmetric boundaries in all four directions.

### Core / System Architecture
- `NpcHandler.java`:
  - Fixed `MoveX == -1` boundary check from `absX - MoveX > makeX - 1` to `absX + MoveX >= makeX - 1`, eliminating double-negation that permitted NPCs to wander 2 tiles West of their home coordinate.
  - Fixed `MoveX == 1` boundary check from strict `<` to inclusive `<=` (`absX + MoveX <= makeX + 1`), restoring authentic Eastward wandering from spawn.
  - Symmetrically corrected `MoveY == -1` and `MoveY == 1` boundary checks, restoring authentic Northward wandering and restricting Southward movement to 1 tile.
  - Prevents pen-bound entities (e.g. Chickens at Farmer Fred's coop) from over-wandering their configured radius onto perimeter wall tiles.

* feat(plugins): implement RuneLite plugin and script hub, ground items, swapper, static IDs, and automation scripts

Introduces a high-performance, modular plugin and automation script framework for the Revision 377 client and Android platform. Implements full UI modals, config persistence, dynamic dex/jar loading, RuneLite-style overlays, static ID constants (ItemID, ObjectID, NpcID, SkillID), and tick-safe scripts for chicken feather farming and cow combat.

### Plugin & Script Infrastructure
- PluginManager.java, ClientPlugin.java, ClientScript.java
  * Core lifecycle management supporting enable/disable toggles, config change notifications, and background script tick processing.
  * Added external JAR/DEX loading capabilities through ExternalPluginLoader.java and Android SAF via PluginDocumentsProvider.java.
- PluginPanelUI.java
  * Complete interactive modal interface featuring tab switching ("Plugins", "Scripts", "Config"), scrolling viewport, toggle switches, and numeric stepper controls.
  * Adaptive orientation layouts for portrait and landscape mobile screens with non-overlapping descriptions and scroll bars.
- PluginContext.java & PluginGraphics.java
  * High-level client API exposing entity querying, spatial coordinate transforms, ground item manipulation, authentic menu injection, and hardware-accelerated overlay drawing.

### Built-in Plugins & Automation Scripts
- GroundItemsOverlayPlugin.java
  * RuneLite-style ground item labels, configurable price tiers (Low, Medium, High, Insane), tile collapsing, item highlights, and lootbeams.
  * Configurable label opacity and semi-transparent backgrounds with responsive touch menu actions.
- MenuEntrySwapperPlugin.java
  * Menu action prioritization for Bank, Pickpocket, Trade, and custom left-click overrides.
- ChickenFeatherFarmerScript.java & CowKillerScript.java
  * Tick-safe combat automation with target lock, retaliation, ground item looting (feathers, bones, cowhide, raw beef, raw chicken), and automatic bone burial for Prayer XP.
  * Smart gate and door approach navigation with state verification and cooldown prevention.

### Static ID & Game Definition APIs
- StaticItemList.java, StaticObjectList.java, StaticNpcList.java, SkillConstants.java
  * Ported 26,000+ server-side Revision 377 static ID constants directly into the client package.
- ItemID.java, ObjectID.java, NpcID.java, SkillID.java
  * Added RuneLite-compatible ID alias classes and skill identifier utilities eliminating magic numbers across all scripts.

### Bug Fixes & Edge Cases
- Gate Navigation & Prevention of Infinite Loops
  * Fixed PluginContext.interactObject action verification to prevent falling back to packet 502 ("Close") when "Open" is absent.
  * Added isOpenGateOrDoor to distinguish open gates (IDs 1552, 1556, 1560, 1561, 7051, 7052) from closed gates.
  * Reordered script loop priority so gate approach and opening precedes looting and combat targeting, eliminating fence path-blocking.
- Text & Stepper UI Overlaps
  * Resolved description truncation and button overlap across modal tabs and fixed numeric stepper value overflowing past increment buttons.

* fix(world): synchronize dynamic gate and door collision in region clipping

Implement bidirectional object collision manipulation in Region and synchronize dynamic gate and door state transitions to eliminate pathfinding desyncs. When wooden and metal gates or doors swing open or closed, directional wall and solid object collision flags are now updated accurately in the server's collision matrix to match client-side object transforms and prevent false unreachable path rejections during NPC combat.

### Core / System Architecture
- Region.java:
  - Implemented removeObject(int objectId, int x, int y, int height, int type, int direction) along with helper overloads accepting Objects and ID coordinates.
  - Implemented bitwise removeClipping and removeProjectileClipping routines (&= ~shift) mirroring addClipping to safely clear collision flags without wiping floor or tile metadata.
  - Implemented removeClippingForSolidObject, removeProjectileClippingForSolidObject, removeClippingForVariableObject, and removeProjectileClippingForVariableObject to accurately reverse collision flags across directional straight walls (type 0), diagonal walls (types 1 & 3), corner walls (type 2), and solid objects (types 9+).
  - Added object instance removal from realObjects list on object unregister.

### Bug Fixes & Edge Cases
- GateHandler.java:
  - Updated openSpecialGate, openSingleGate, and openMetalGateWalk to unclip closed gate objects in Region upon opening and dynamically add clipping for open gates.
  - Updated manual gate closing branches to remove open gate collision and restore closed gate collision.
  - Fixed "I can't reach that" false rejections in PlayerAssistant.followNpc() and PathFinder.accessible() when interacting across open cow pen and farm gates.
- ObjectManager.java:
  - Updated doubleGateTicks and singleGateTicks to dynamically remove open gate collision flags and restore closed gate collision flags in Region upon timer expiration.
- Doors.java & DoubleDoors.java:
  - Connected door opening and closing mechanics to Region.removeObject and Region.addObject to ensure single and double swinging doors maintain parity between visual placement and pathfinding collision.

* fix(pathfinding): resolve premature attack rejections, circular BFS buffers, and NPC wall leashing

Refactors RS2 pathfinding, projectile line of sight, and melee attack routing to authentic Revision 377 collision rules. Resolves premature 'I can't reach that' rejections across fences and gates by delegating inaccessible positions to follow route generation, and replaces LinkedList BFS queues with primitive circular buffers.

### Core / System Architecture
- `PathFinder.java`:
  - Replaced `LinkedList<Integer>` queues in `findRoute()` and `accessible()` with primitive `int[4096]` circular buffers using bitwise wrapping `(writePath + 1) & 4095`.
  - Converted BFS retrieval from O(N) pointer traversals to O(1) direct array index access, eliminating GC allocations during tile search.

### Bug Fixes & Edge Cases
- `ClickNPC.java`, `CombatAssistant.java`, and `PlayerAssistant.java`:
  - Removed premature rejection checks that aborted attacks on click when Chebyshev proximity was satisfied across an obstacle (e.g. pen fences and gates).
  - Maintained movement toward nearest accessible attack tile via `getFollowNpcLocation()`, only sending 'I can't reach that.' if no candidate attack tile is accessible.
- `PathFinder.java`:
  - Added early return when source and destination match to prevent division-by-zero (Double.NaN) in Bresenham delta calculations.
- `Npc.java` & `NpcHandler.java`:
  - Added `walkingHomeStuckTicks` counter to NPC state.
  - Implemented authentic RS2 leashing: if an NPC is blocked by walls/fences while walking home for 10 consecutive ticks, it teleports back to its original `(makeX, makeY)` spawn point and resets `walkingHome`.
- `PlayerAssistant.java`:
  - Pre-filtered follow candidate nodes by distance and clipping masks before invoking full BFS accessibility checks.
  - Enabled `moveNear = true` in `followPlayer()` so player following approaches adjacent reachable tiles when the target tile is blocked.

### Cleanups & Deprecations
- `PathFinder.java`:
  - Removed debug chatbox message `sendMessage("ERROR!")` when pathfinding to the player's current coordinate.

* fix(packets): add authentic pathfinding to item-on actions, ground pickup, and restore player movement clipping

Synchronizes packet interaction workflows with authentic Revision 377 movement and collision behavior. Item-on-object, item-on-npc, item-on-ground, and magic-on-object packets now route and follow until in interaction proximity rather than aborting prematurely, ground item pickups require standing directly on the item tile or line-of-contact across tables, and server-side player movement collision verification is restored in getNextWalkingDirection().

### Core / System Architecture
- `Player.java`:
  - Restored server-side step collision verification with `Region.canMove()` in `getNextWalkingDirection()`.
  - Position updates (`currentX`, `currentY`, `absX`, `absY`) are guarded so blocked steps immediately clear the walking queue without coordinate desynchronization.
- `ClickObject.java` & `ClickNPC.java`:
  - Exposed `onObjectReached()` and `handleNpcInteraction()` as static utilities for packet handlers.

### Bug Fixes & Edge Cases
- `ItemOnObject.java`:
  - Delegated item-on-object processing through `ClickObject.onObjectReached()`, enabling players to use items on furnaces, anvils, and ranges from a distance.
- `ItemOnNpc.java`:
  - Routed item-on-npc interactions through `ClickNPC.handleNpcInteraction()` so players approach NPCs (e.g. shearing sheep) before executing.
- `ItemOnPlayer.java` & `ItemOnGroundItem.java`:
  - Added approach cycle events that pathfind until line-of-contact is achieved before executing the item action.
- `PickupItem.java` & `Walking.java`:
  - Enforced exact tile positioning for ground items on traversable tiles, preventing pickup through fences and walls.
  - Enabled cardinal line-of-contact pickup for items situated on non-walkable objects (e.g. tables).
  - Cleared `player.walkingToItem` on walking packets to cancel stale pickup tasks.
- `MagicOnObject.java`:
  - Added approach routing and `PathFinder.isProjectilePathClear()` line-of-sight checks for spellcasting on world objects.

* feat(scripts): add collision reachability API, world-gated scripts, and gate-safe chicken/cow automation

Adds a collision-aware reachability and line-of-sight API to PluginContext, restricts automation scripts to World 1 while keeping plugins on both worlds, and fixes gate/door handling and "I can't reach that" loops in the Chicken Feather Farmer and Cow Killer scripts.

### Core Automation Architecture
* `PluginContext.java`:
  - Added directional collision masks and `getClipping`, `isTileWalkable`, and two-sided `canStep` validation (exit and entry wall flags, strict diagonal checks) backed by the client CollisionMap.
  - Added `canMeleeReach` mirroring server `Region.canReachNpcMelee` (cardinal adjacency for 1x1 NPCs, wall flags on both tiles).
  - Added `hasLineOfSight` raycasting (coordinates, NPCs, ground items) and bounded BFS `canReach` overloads for tiles, NPCs, ground items, and objects.
  - Added `randomDelay(minMs, maxMs)` producing bell-curve timing jitter.
  - Added `isAnyGateOpenNearby` and `isAnyGateOrDoorOpenNearby` using Revision 377 open gate IDs and "Close" actions.

### World Availability & Plugin Hub
* `PluginManager.java`:
  - Added `isScriptsAvailable()` (World 1 only); script lists, start, ticks, and event hooks are blocked on World 2, plugins remain active on both worlds.
  - `::scripts` redirects to the Plugins tab on World 2.
* `PluginPanelUI.java`:
  - Header and tab strip adapt per world (Plugins | Scripts | Config on World 1, Plugins | Config on World 2) and Scripts tab clicks redirect to Plugins on World 2.

### Script Intelligence
* `ChickenFeatherFarmerScript.java`:
  - Targets only "Gate" objects (house doors excluded) and never clicks a gate when any open gate is nearby, preventing open double gates from being toggled shut.
  - Opens gates only when the anchor or visible chickens are unreachable or lack line of sight.
  - Filters chickens and loot by `canReach` and `hasLineOfSight`; quick-loots feathers within one tile before retaliating.
  - Uses `randomDelay` for all loop delays.
* `CowKillerScript.java`:
  - Same gate guard, reachability, line-of-sight, quick-loot (cowhide), and humanized delay changes.

### Bug Fixes & Edge Cases
* Both scripts implement `onChatMessage` to drop the target lock when the server replies "I can't reach that.", preventing infinite attack retries through coop walls.

* Port Astraeus dialogue factory and migrate Al-Kharid guard

Add Astraeus's chainable dialogue factory alongside the legacy DialogueHandler, with player-owned dialogue state and packet/button routing. Preserve legacy dialogue behavior when no factory dialogue is active, and clear factory state when a dialogue ends.

Move the Al-Kharid border guard toll dialogue into the plugin system, including both toll choices, decline and insufficient-coins responses, and the completed Prince Ali path. Remove the obsolete button-action plugin and legacy handler cases.

Make guard first-click interactions require adjacent reach, and update Al-Kharid gate collision while open so the player can route through. Broadcast temporary gate object changes to nearby players and restore closed collision and visuals after crossing.

Compile the server and run git diff --check.

* Flatten plugin source directory layout

Move all plugin sources from plugins/plugin/<package> to plugins/<package>, removing the redundant directory level while leaving declared plugin.* packages and internal imports unchanged.

Update PluginService's path-to-class-name resolution to prepend the plugin package prefix for sources discovered beneath ./plugins. Keep recursive discovery working for nested Kotlin and Java plugins in the new layout.

Compile the server and run git diff --check.

* Extract NPC interaction routing service

Move shared NPC reach checks, route selection, and deferred interaction handling out of packet implementations into NpcInteraction. Delegate NPC option clicks and item-on-NPC actions to the shared service.

Replace stale queued walking commands and routes when an out-of-reach NPC is clicked so the interaction route survives player post-processing. Route Talk-to actions to an adjacent tile, including when the player starts inside the NPC footprint.

* fix(world): synchronize global object updates and replace per-player gate state with world-global tracking

Fix server-client desynchronization when crossing map regions around dynamic gates and replace legacy per-player gate state tracking with authentic 2006 RS2 world-global gate state. Previously, gates auto-closing while players were out of range left stale open-gate entries in `globalObjects`, causing returning players to see an open gate while server `Region` clipping blocked passage.

### World Object Synchronization
- `ObjectHandler.java`:
  - Moved `removeAllObjects(o)` and `globalObjects.add(o)` outside the 60-tile player broadcast loop in `placeObject(Objects)` so `globalObjects` always reflects world object state changes even when no player is nearby (such as gate auto-close ticks firing after a player leaves the region).
  - Updated `updateObjects(Player)` to filter against the player's loaded 104x104 map scene bounds (`0 <= localX, localY < 104`) instead of a 60-tile Euclidean radius, and send object spawns/removals via the 5-argument `PacketSender.object(...)` so objects in outer region corners are not skipped on region reload.

### Global Gate State & Timers
- `GateHandler.java`:
  - Replaced the per-player `gateStatus` field (`CLOSED`, `PARTIAL_OPEN`, `OPEN`) with a shared `ConcurrentHashMap` (`OPEN_GATES`) keyed by canonical gate coordinates `(x, y, height)` via `gateKey`, `isGateOpenAt`, `markGateOpen`, and `markGateClosed`.
  - Updated `openSingleGate`, `openSpecialGate`, and `openMetalGateWalk` to check global gate state (`isGateOpenAt` and `isOpenGate`) and cancel any active auto-close timer when a gate is closed manually.
- `ObjectManager.java`:
  - Refactored `singleGateTicks` and `doubleGateTicks` to bind their `CycleEvent` to the gate's global `timerOwner` object rather than an individual `Player`, checking `GateHandler.isGateOpenAt(...)` instead of `player.getGateHandler().gateStatus` or `player.disconnected` so world gates always close cleanly after their timer expires.

* fix(world): complete doubleGateTicks global gate state cleanup in ObjectManager

Stage the remaining hunk in `ObjectManager.doubleGateTicks` that was omitted in `de52bace`, resolving the compilation error where `player` was still referenced in `execute` and `stop`. This completes the transition of double-gate auto-close timers to world-global gate tracking without touching unrelated working-tree changes.

### Global Gate State & Timers
- `ObjectManager.java`:
  - Replaced `player.getGateHandler().gateStatus = player.getGateHandler().CLOSED` in `doubleGateTicks` with `GateHandler.markGateClosed(closedX1, closedY1, objectH)` and removed the stale `player` reference in `stop()`.

* feat(client): expand plugin/script API, SemVer, BFS pathing, and Al-Kharid banking

Expanded the client plugin and script engine across movement, banking/shops, combat/skilling primitives, lifecycle reliability, semantic versioning, and ScriptInterpreter parity while fixing Al-Kharid banking and toll-gate navigation in CowKillerScript.

### Core Infrastructure
- `PluginContext.java` & `PluginGraphics.java`:
  - Added run energy helpers (`isRunEnabled`, `setRunEnabled`, `ensureRunEnabled`), area/position helpers (`WorldArea`, `isInArea`, `isAt`), collision-aware BFS pathfinding (`findPath`, `walkToSmart`, `walkToSmartOrOpenDoors`), and multi-floor climbing (`climb`, `climbUp`, `climbDown`, `navigateToPlane`).
  - Added `Withdraw-X`/`Deposit-X` (`actionId 53` + packet `208`), `setWithdrawAsNote`, `depositAllExcept(String...)`, `selectDialogueOption(String)`, `getDialogueOptions`, and Shop/Make-X APIs (`buyItem`, `sellItem`, `makeCookingAmount`, `clickMakeOption`).
  - Added `useItemOnItem`, `useItemOnObject`, Equipment API (`getEquipment`, `isWearing`, `equipItem`, `unequipItem`), `setAttackStyle`, `toggleSpecialAttack`/`setSpecialAttack`, `Prayer` & `Spell` enums, `players()`/`PlayerQuery`, HP/food/emergency teleport helpers, and `drawPathOverlay`/`drawAreaOverlay`.
  - Fixed `canReach(SceneObjectWrapper)` adjacent-tile reachability and monotonic `walkPath` index tracking.
- `ClientScript.java`, `ClientPlugin.java`, `PluginManager.java`, `SemVer.java`, `ExternalPluginLoader.java`, `PluginPanelUI.java`, `ScriptInterpreter.java`:
  - Added `waitUntil`, stuck watchdog (`isStuck`, `resetWatchdog`), named timers (`markTimer`, `hasElapsed`), and `onLogin`/`onDisconnect`/`onPlayerDeath` hooks.
  - Added SemVer 2.0.0 parsing/constraint matching (`SemVer`), `@version`/`@minApi` metadata parsing, `API_VERSION = "2.0.0"` gating, version display in `PluginPanelUI`, load error reporting, varargs/enum reflection in `ScriptInterpreter`, and startup copying of `SampleTreeCutter.script`.

### Scripts & Bug Fixes
- `CowKillerScript.java` & `ChickenFeatherFarmerScript.java`:
  - Fixed Al-Kharid toll-gate dialogue handling, open main-road waypoints (`X = 3281`), `ItemID.COINS_995` retention/20gp top-up, `returnedToPastureGate` flag, and same-side Border Guard filtering.
  - Integrated `ensureRunEnabled`, `walkToSmart`/`walkToSmartOrOpenDoors`, `waitUntil`, `markTimer`/`hasElapsed`, `useSpecialAttack`, `onPlayerDeath`, and optional `showDebugOverlay`.

* feat(client): add online plugin repo, scrollable choice dropdown, F2P web walker, and script interpreter upgrades

Replaced the built-in automation scripts and sample resources with an online plugin/script repository client (`PluginRepoClient`), upgraded `ScriptInterpreter` to support full-featured `.script` files, and added `WorldWebWalker` + `ScriptLogger` for map-wide F2P pathing and action logging. Set the initial client plugin/script API baseline to `1.0.0` while preserving built-in QoL plugins (`MenuEntrySwapperPlugin`, `GroundItemsOverlayPlugin`).

### Online Plugin Repository & Hub UI
- `PluginRepoClient.java`: Added GitHub-backed repository client (`index.json` parser, SemVer install/update/uninstall status, and cache-busted `httpGet` with `no-cache` and `?t=` timestamp).
- `PluginPanelUI.java`: Replaced the config tab with the **Online Repo** tab (`Install` / `Update` / `Remove`), added `getVisibleConfigItems` for conditional `when:<key>` config visibility, and replaced the `< ... >` choice cycler with a 172px scrollable dropdown popup (`DROPDOWN_MAX_VISIBLE = 6`).
- `PluginConfigItem.java`: Added `visibleWhen` support (`setVisibleWhen` / `getVisibleWhen`).
- `ExternalPluginLoader.java`: Removed built-in sample script extraction and legacy sample cleanup.

### Script Interpreter, Commands & Logging
- `ScriptInterpreter.java`: Added `onConfigChanged` forwarding on `InterpretedPlugin`/`InterpretedScript`, `else if` chains, `while` loops (1,000-iteration safety cap), `+=`/`-=` compound assignments, integral arithmetic preservation, hex literals (`0x...`), `|min|max` and `|when:<key>` on `@config`, `// @command` metadata parsing, and static class/field/method access (`Math`, `System`, `RSColors`, `ItemID`, `SkillID`, `NpcID`, `ObjectID`, `PluginContext`).
- `ClientScript.java`: Added `getCommandNames()`, made `formatCompactNumber` and `clearWait` `public`, and wired `ScriptLogger` into lifecycle/status transitions.
- `PluginManager.java`: Set `API_VERSION = "1.0.0"`, removed built-in `ChickenFeatherFarmerScript` and `CowKillerScript` registrations and hardcoded `::feather`/`::cow` commands, and added dynamic script-defined `::` command dispatch gated by per-plugin/script `chatCommands` config.
- `MenuEntrySwapperPlugin.java` & `GroundItemsOverlayPlugin.java`: Added `chatCommands` toggle to config items.
- `ScriptLogger.java`: Added rotating file (`<cacheDir>/logs/scripts.log`, 1 MB cap) and `[ScriptLog]` stdout logging for script lifecycle, status changes, `walkTo`, and `menuAction`.

### Smart Pathing & World Web Walker
- `WorldWebWalker.java`: Added 59-node F2P overworld road/bridge graph (Lumbridge, Draynor, Port Sarim, Rimmington, Falador, Taverley, Barbarian Village, Edgeville, Varrock, and Al-Kharid via the free northern pass) with Dijkstra routing.
- `PluginContext.java`: Added `createArea`, `walkPathCoords`, partial BFS fallback (`findPath(..., allowPartial)` up to 55-tile radius / 9,500 iterations), expanded `canReach` (45-tile radius / 6,000 iterations), monotonic `activeWebRoute` tracking, committed-goal hysteresis, and `ScriptLogger` action hooks.

### Cleanups & Removals
- Removed `ChickenFeatherFarmerScript.java`, `CowKillerScript.java`, `SampleTreeCutter.script`, and `samples.txt` from the client bundle (migrated to `2006scape-plugins`).

* fix(combat): enforce cardinal-only melee, fix NPC corner-sticking, halberd reach, and PathFinder LoS

Align melee combat reach, multi-tile NPC following, halberd range, and projectile line-of-sight checks with authentic 2006 RS2 behavior. Removing the `npcSize > 1` diagonal corner melee bypass prevents large NPCs from fighting on corner tiles and visually clipping into players, while cardinal fallback pathing and symmetric Bresenham raycasting resolve stuck NPCs and steep-angle LoS inaccuracies.

### Melee Reach & Halberd Support
- `Region.java`:
  - Removed the `npcSize > 1` diagonal corner exceptions from `canReachNpcMelee(...)` so standard 1-tile melee is strictly cardinal-adjacent for all NPC sizes.
  - Added `canReachHalberd(...)` supporting 2-tile cardinal and diagonal halberd reach verified with `PathFinder.isProjectilePathClear(...)`, preserving strict 1-tile `canReachNpc` behavior for non-halberd interactions.
- `ClickNPC.java`, `PlayerAssistant.java`, `CombatAssistant.java`:
  - Removed `npcSize > 1` diagonal melee bypasses in melee range checks and `getFollowNpcLocation(...)`, routing players to cardinal edge tiles for standard melee.
  - Switched halberd reach checks to `Region.canReachHalberd(...)` and gated `attackPlayer(...)` `isProjectilePathClear(...)` on `player.isUsingProjectileCombat()`.

### NPC Movement & Overlap Escape
- `NpcHandler.java`:
  - Updated `followPlayer(...)` so 1-tile diagonal corner approaches and under-NPC escapes check `Region.canMove(...)` and fall back to the alternate cardinal axis when blocked, while farther diagonal approaches set both axes for `handleClipping(i)`.
- `Npc.java`:
  - Updated `getNextWalkingDirection()` to allow an NPC that is already overlapping a player (e.g. a `3x3`+ NPC with a player on its center tile) to step away instead of freezing in place, while still blocking any NPC from stepping onto non-overlapping players.

### Pathfinding & Line of Sight
- `PathFinder.java`:
  - Localized `destX` and `destY` in `findRoute(...)` before comparing against `player.getLocalX()` / `player.getLocalY()` so `!moveNear` same-tile early returns trigger accurately.
  - Added `0..103` bounds validation in `accessible(...)` to reject out-of-scene targets immediately without flooding the 104x104 grid.
  - Replaced the single-axis `isProjectilePathClear(...)` loop with a major-axis Bresenham/DDA raycast (`absDx >= absDy` vs `absDy > absDx`) so steep-slope LoS checks trace symmetrically.

* fix(npcs): initialize NPCDefinition before loading spawns so multi-tile NPCs retain their true size

Fix an initialization order bug in `NpcHandler()` where `loadSpawnList()` ran before `NPCDefinition.init()`, causing every spawned multi-tile NPC in the world to fall back to `size = 1`. Because `Npc.getSize()` cached that `1` permanently, multi-tile NPCs such as 2x2 Cows pathed and checked melee adjacency as 1x1 entities on the server while rendering as 2x2 on the client, clipping into players.

### NPC Initialization
- `NpcHandler.java`:
  - Moved `NPCDefinition.init()` ahead of `loadNPCList()` and `loadSpawnList()` in `NpcHandler()` so `new Npc(...)` resolves each NPC's true `size` from `npcDefinitions.json` at startup.

* perf(hd): optimize 117HD pipeline, add Hd117Plugin, and fix multi-plane depth/archway rendering

Optimizes CPU and GPU performance across the shared 117HD pipeline, converts 117HD into a configurable built-in client plugin, and resolves multi-story depth poke-through and open-air archway material artifacts. All changes are scoped to the 2006Scape Client with zero server modifications.

### Core Architecture & Performance
- WorldController.java:
  - Replaced O(R^3) concentric tile scan with an O(R^2) 4-edge ring perimeter walk via renderHdTileColumn.
  - Added horizontal cxCam frustum culling in isHdTileInFrustum to skip out-of-FOV tiles and models.
  - Tracked hdMaxPlane and HD117Pipeline.drawingPlane / drawingWall for multi-plane depth ordering.
- HdSceneUploader.java & Model.java:
  - Built static terrain into 4 GL_STATIC_DRAW buckets (0..3 by Ground.anInt1321) once per region load, eliminating per-frame terrain CPU work and VBO uploads.
  - Separated terrain, shadow-casting models/actors, and translucent geometry into distinct buffers.
  - Added an 8 MB hard-capped LRU Model geometry cache (MAX_CACHED_MODEL_FLOATS = 2000000) keyed by Model.hdCacheVersion and plane.
  - Removed per-tile WATER_NORMAL allocations and deduplicated shared-corner resolveGroundRgb lookups.

### Shaders, Rendering & Bug Fixes
- HD117Pipeline.java & DesktopHd117Renderer.java:
  - Switched shadow sampling from 9-tap manual PCF to 4-tap hardware sampler2DShadow PCF with GL_LINEAR and GL_COMPARE_REF_TO_TEXTURE, plus early-out for emissive and sun-backfacing fragments.
  - Added SCENE_FRAG_DIRECT for single-pass contrast tonemapping and BGRA swizzle without a post-process FBO.
  - Added plane-ordered depth bias (vPlane * 3.0) and SURF_WALL (4) in SCENE_VERT so ground-floor walls and lower-plane objects never poke through upper-plane floors.
- HdProceduralGenerator.java:
  - Replaced the roofNeighbors >= 2 indoor heuristic with isOpenAirPassThrough on plane 0 so open-air archways retain outdoor cobblestone instead of smooth indoor marble.

### New Plugin & Configurability
- Hd117Plugin.java, PluginManager.java, & Game.java:
  - Added built-in '117 HD' ClientPlugin with live configuration for Shadows, Shadow Resolution (512/1024/2048), Shadow Quality, Dynamic Lighting, Atmospheric Fog, Draw Distance, Ground Textures, Normal Mapping, HD Water Shader, Saturation, Brightness, and Contrast Tonemapping.

* feat(plugins): migrate Cook's Assistant, Dairy Cow, and Flour Mill to plugins with persistent plugin data

Migrate Cook's Assistant, Dairy Cow milking, and Flour Mill mechanics out of core Java handlers into modular Kotlin plugins backed by a namespaced per-player `PlayerPluginData` store. This decouples quest and world-object progression from hardcoded `Player` fields while preserving backwards-compatible character save migration and authentic 2006 RS2 behavior.

### Core Plugin Infrastructure
- `PlayerPluginData.java`, `Player.java`:
  - Added `PlayerPluginData` (`plugin-data.<plugin>.<key>`) on `Player` with typed getters/setters (`putString`, `putInt`, `putLong`, `putBoolean`, `getString`, `getInt`, `getLong`, `getBoolean`) and `KEY_PREFIX` validation.
- `PlayerLoadDataEvent.java`, `PlayerSaveDataEvent.java`, `PlayerSave.java`:
  - Added `PlayerLoadDataEvent` and `PlayerSaveDataEvent` hooks in `PlayerSave` to serialize/deserialize `plugin-data.*` entries and expose unmapped legacy keys (`legacyData`) for seamless quest migration.
- `PlayerObjectsLoadedEvent.java`, `ObjectManager.java`:
  - Dispatched `PlayerObjectsLoadedEvent` in `ObjectManager.loadCustomSpawns(Player)` so region-dependent plugin object spawns (such as a full flour bin) restore on login and region change.
- `QuestStatusEvent.java`, `QuestAssistant.java`, `DialogueFactory.java`:
  - Renamed `Quests.questStatus()` to `isImplemented()`, dispatched `QuestStatusEvent` in `QuestAssistant.sendStages(Player)`, and simplified `DialogueFactory.onNext()` to delegate directly to `execute()`.

### Migrated Quest & Object Plugins
- `plugins/quests/cooksassistant/` (`CooksAssistantNpcPlugin.kt`, `CooksAssistantJournalPlugin.kt`, `CooksAssistantQuestStatusPlugin.kt`, `CooksAssistantLoadDataPlugin.kt`):
  - Implemented Cook's Assistant dialogue, ingredient collection (`EGG`, `BUCKET_OF_MILK`, `POT_OF_FLOUR`), reward payout (`500` coins, `300` Cooking XP, `1` QP) with immediate `QuestAssistant.sendStages(player)` refresh, quest journal (`button 28165`), quest list color status (`string 7333`), and legacy `cookAss` save migration.
- `plugins/objects/dairycow/` (`DairyCowMilking.kt`, `DairyCowObjectPlugin.kt`, `DairyCowItemOnObjectPlugin.kt`):
  - Implemented dairy cow milking for both first-click and `BUCKET`-on-object interactions (returning `"Nothing interesting happens."` for other items), with a 7-tick `CycleEvent` and bucket re-validation before awarding `BUCKET_OF_MILK`.
- `plugins/objects/flourmill/` (`FlourMillActions.kt`, `FlourMillObjectPlugin.kt`, `FlourMillItemOnObjectPlugin.kt`, `FlourMillPluginState.kt`, `FlourMillRegionPlugin.kt`):
  - Implemented hopper grain loading (`GRAIN` up to `30`), hopper controls (`HOPPER_CONTROLS`) with `disconnected`/distance-guarded `CycleEvent`, `POT`-on-`FLOUR_BIN` and first-click flour collection, empty-bin (`1781`) message, and persistent `objects.flourmill` `grain`/`flour` state across logouts.

### Cleanups & Deprecations
- Removed legacy Java classes `CooksAssistant.java`, `MilkCow.java`, and `FlourMill.java`, along with their hardcoded fields (`cookAss`, `milking`, `flourAmount`, `grain`) in `Player.java` and switch cases in `QuestAssistant.java`, `QuestRewards.java`, `DialogueHandler.java`, `DialogueOptions.java`, `UseItem.java`, `NpcActions.java`, `ObjectsActions.java`, `PlayerSave.java`, and `ObjectManager.java`.

* feat(plugins): migrate combat style, autocast menu, spell select, and cancel buttons to plugins

Migrate all combat attack-style and autocast spell-selection button handling out of `ClickingButtons.java` and `Player.java` into modular Kotlin `ButtonActionEvent` plugins. This also adds support for the missing `7212` autocast cancel button and aligns autocast toggling, cancel preservation, and level/staff validation with authentic 2006 RS2 behavior.

### Migrated Combat & Autocast Plugins
- `plugins/buttons/combat/CombatStyleButtonsPlugin.kt`:
  - Mapped all weapon combat style buttons (`9125`–`48010`) to `fightMode` (`0`–`3`) via `STYLE_BY_BUTTON`, guarding on `player.isDead` and resetting active autocast when switching to a melee/ranged style.
- `plugins/buttons/combat/AutocastMenuButtonsPlugin.kt`:
  - Handled "Choose Spell" (`1097`) and "Attack with" (`1093`, `1094`) to open Modern (`1829`), Ancient (`1689` with Ancient staff `4675`), or Slayer (`12050` with Slayer's staff `4170`) spell selection, and toggle autocast between active (`config 108 = 3`) and paused (`config 108 = 2`, restoring `config 43 = fightMode`) when `autocastId >= 0`.
- `plugins/buttons/combat/AutocastSpellSelectPlugin.kt`:
  - Consolidated all autocast spell buttons across interfaces `1829`, `1689`, `12050`, and legacy `7038`–`47024` IDs, validating `player.isDead`, spellbook/staff requirements, and Magic level (`MagicData.MAGIC_SPELLS`) without requiring runes in inventory until cast.
- `plugins/buttons/combat/AutocastCancelButtonPlugin.kt`:
  - Handled autocast cancel buttons (`2004`, `6161`, `7212`, `12101`, `24017`) by refreshing the equipped weapon's combat tab (`sendWeapon`) and restoring `fightMode` highlight when not autocasting, preserving any previously selected autocast spell.

### Cleanups & Deprecations
- `ClickingButtons.java`, `Player.java`:
  - Removed hardcoded combat style switch cases, `1093`/`1094`/`1097` and `2004`–`24017` autocast handlers, and `isAutoButton`, `autocastIds`, and `assignAutocast` from `Player`.

* fix(combat): normalize poisoned arrow tiers/GFX and enforce authentic ranged/magic NPC combat distance

Fixes ammo recognition, bow-tier checks, and projectile/drawback graphics for poisoned arrow variants while aligning ranged and magic NPC combat pathing with authentic 2006 RS2 (Revision 377) mechanics. Players now stop cleanly at exact maximum attack range with clear line of sight instead of overshooting into melee range when running or attacking on cooldown.

### Poisoned Arrow Normalization
- `RangeData.java`:
  - Added `(p+)` (`5616`–`5621`) and `(p++)` / `(s)` (`5622`–`5627`) bronze through rune arrow IDs to `ARROWS`.
  - Added `getBaseArrowId(int)` to map `(p)`, `(p+)`, and `(p++)`/`(s)` variants back to their base arrow ID, and normalized `getRangeStartGFX` and `getRangeProjectileGFX` lookups.
  - Updated `correctBowAndArrows` for `MAGIC_LONGBOW` and `MAGIC_SHORTBOW` to return `RUNE_ARROW` (or `BROAD_ARROWS_4172` when equipped) so poisoned rune arrows pass bow-tier validation.
- `RangeMaxHit.java`:
  - Normalized the arrow ID in `getRangeStr(int)` via `RangeData.getBaseArrowId(int)` so poisoned arrows inherit their base arrow's ranged strength.
- `ClickNPC.java`, `AttackPlayer.java`, `CombatAssistant.java`:
  - Normalized `player.playerEquipment[player.playerArrows]` with `RangeData.getBaseArrowId(...)` in bow-arrow tier checks.

### Ranged & Magic NPC Combat Movement
- `ClickNPC.java`:
  - Set `player.followNpcId = player.npcIndex` immediately after validation in both `ATTACK_NPC` and `MAGE_NPC`, even when `player.attackTimer > 0`, preventing the client's walk-to-melee packet from continuing during attack cooldown.
  - Added `isInProjectileRangeWithLos(Player)` so `stopMovement()` on click only triggers when both within `getAttackDistance()` and with clear projectile line of sight (`PathFinder.isProjectilePathClear`).
- `Player.java`:
  - Updated `getNextWalkingDirection()` to stop walking (`resetWalkingQueue(); return -1;`) on any step where `npcIndex > 0` and projectile combat is already within `getAttackDistance()` with clear projectile line of sight, preventing running players (2 tiles/tick) from overshooting max range (e.g., 7/9 tiles for shortbows).
- `PlayerAssistant.java`, `CombatAssistant.java`:
  - Preserved `player.followNpcId` when stopping in range in `followNpc()`, `attackingNpcTick()`, and `attackNpc()` so players automatically re-follow NPCs that walk out of range or line of sight.

* feat(quests): add Druidic Ritual, Cook's range plugin, and native RS2 quest varp stages

Implement Druidic Ritual with authentic Taverley world interactions, convert
Cook's Assistant and the Lumbridge Cook's range to 2006 RS2 behaviour, and
refactor all 16 implemented quests to store and sync authentic RS2 varp
stage values natively with one-time character save migration.

### Druidic Ritual & Taverley World Fixes
- plugins/quests/druidicritual/DruidicRitualNpcPlugin.kt, DruidicRitualJournalPlugin.kt, DruidicRitualCauldronPlugin.kt, DruidicRitualQuestStatusPlugin.kt, DruidicRitualConstants.kt:
  - Implement full Druidic Ritual quest flow (Kaqemeex, Sanfew, Cauldron of Thunder, Herblore lesson dialogue, and 4 QP / 250 Herblore XP reward) using varp 80 (stages 0..4).
- plugins/quests/druidicritual/DruidicRitualPrisonDoorPlugin.kt:
  - Add Cauldron of Thunder prison door (2143/2144) handling with double-door swing animation and first-attempt level 19 Suit of armour (453) pedestal scenery swap/ambush, restoring scenery on death, timeout, or logout.
- data/cfg/spawns.json & src/.../Climbing.java:
  - Move Sanfew (454) upstairs to (2899, 3429, 1) and wire staircase 1738 at (2898, 3428) to climb upstairs.
- src/.../PlayerAssistant.java:
  - Remove the pre-quest level 3 / 175 Herblore XP grant on loginScreen().

### Cook's Assistant & Cook's Range Plugin
- plugins/quests/cooksassistant/CooksAssistantConstants.kt, CooksAssistantNpcPlugin.kt, CooksAssistantJournalPlugin.kt, CooksAssistantQuestStatusPlugin.kt, CooksAssistantLoadDataPlugin.kt:
  - Extract shared CooksAssistantConstants, add authentic 2006 RS2 Lumbridge ingredient directions, support one-by-one ingredient hand-in, and restore the 2006 reward (1 QP, 300 Cooking XP, Cook's range access).
- plugins/quests/cooksassistant/CooksRangePlugin.kt, ItemOnObject.java, Cooking.java:
  - Gate COOKING_RANGE (114) behind Cook's Assistant completion and apply the Lumbridge Cook's range reduced burn bonus.

### Native RS2 Quest Varp Refactor & Save Migration
- src/.../QuestAssistant.java, QuestRewards.java, DialogueHandler.java, NpcActions.java, ObjectsActions.java, NpcHandler.java, Barrows.java, ClickItem.java, ItemOnNpc.java, ItemAssistant.java, UseItem.java, CombatAssistant.java, PlayerAssistant.java, and quests/impl/*.java:
  - Refactor all implemented quests to use authentic RS2 varp stage values natively (varps 29, 31, 63, 67, 71, 80, 107, 122, 130, 144, 145, 147, 160, 178, 179, 180) and sync them via sendConfig.
- src/.../Player.java & PlayerSave.java:
  - Add questVarpVersion and migrateQuestStagesToVarp(player) to migrate pre-existing character saves once on load.

* feat(plugins): expose widget color and varps in PluginContext and refresh Plugin Hub index

Extend the external plugin API to support quest color/varp state detection
and ensure the Plugin Hub automatically refreshes stale repository indexes
without requiring a client restart.

### Plugin API Additions
- PluginContext.java:
  - Add getWidgetColor(int widgetId) to expose RSInterface.textColor for
    packet-122 colored quest entries.
  - Add getVarp(int varpId) to safely read game.variousSettings[varpId].

### Plugin Hub Repo Refresh
- PluginRepoClient.java:
  - Track lastFetchMs and re-fetch index.json in ensureLoaded() when more
    than 10 seconds have elapsed since the previous fetch.

* Added scrolling for scrollbars in client

# Conflicts:
#	2006Scape Client/src/main/java/Game.java

* Added comment for magic numbers

* Added some barrows fixes (#682)

- Set Ahrim the Blighted (2025) maxHit to 20 and Dharok the Wretched (2026) maxHit to 29 in npcDefinitions.json.
- Adjust Dharok spawn position at barrowsKillCount == 5 in Barrows.java to (c.getX()-1, c.getY()).
- Add named destination 'barrows' (3565, 3308, 0) to Teleport.kt.

* Fixed screenshots

DesktopHooks.takeScreenshot() cast the applet to Window, which threw a ClassCastException on every desktop screenshot. Capture the frame that contains the applet instead.

* Fixed client ignoring -dev and -ip server args

Game copies ClientSettings.SERVER_IP into Game.server in its constructor, which runs before ClientArgs.apply(), so the client always connected to the default server even though the title showed [Local].

* feat(commands): add extra named destinations and aliases to Teleport plugin

Expands the admin `::teleport` / `::tele` command plugin with additional common 2006 RS2 towns, minigames, and island destinations alongside alias resolution for both spellbook cities and custom named locations. Coordinates are sourced directly from existing server spawn and travel/teleport definitions.

### Command Infrastructure
- `plugins/commands/admin/Teleport.kt`:
  - Added 12 custom destinations to `NAMED_LOCATIONS` alongside `barrows` (`3565, 3308, 0`): `taverley` (`2896, 3428, 0`), `edgeville` (`3088, 3500, 0`), `al kharid` (`3293, 3174, 0`), `karamja` (`2911, 3152, 0`), `draynor` (`3103, 3249, 0`), `duel arena` (`3313, 3234, 0`), `castle wars` (`2441, 3090, 0`), `pest control` (`2659, 2676, 0`), `port sarim` (`3041, 3202, 0`), `rellekka` (`2620, 3686, 0`), `brimhaven` (`2772, 3234, 0`), and `entrana` (`2834, 3335, 0`).
  - Added `CITY_ALIASES` entries (`tav`, `taverly`, `edge`, `alkharid`, `duel`, `cw`, `castlewars`, `pc`, `pestcontrol`, `portsarim`, `sarim`, `relekka`) and resolved `CITY_ALIASES` prior to checking `NAMED_LOCATIONS` so aliases work uniformly across all destinations.
  - Updated `NAMED_LOCATIONS` teleport feedback to title-case multi-word destination names and updated `VALID_CITIES_MESSAGES` to list all supported destinations.

* feat(commands): migrate setlevel/level/skill command to developer plugin with skill name support

Moves the legacy `setlevel` / `level` / `skill` command out of `Commands.java` into a modular Kotlin developer command plugin (`DeveloperCommandEvent`) and adds skill name and abbreviation resolution alongside numeric skill IDs.

### Migrated Command Plugins
- `plugins/commands/developer/SetLevel.kt`:
  - Subscribes to `DeveloperCommandEvent` (`playerRights == 3`) for `setlevel`, `level`, and `skill`.
  - Supports numeric skill IDs (`0`–`20`) as well as full skill names and common abbreviations (e.g., `attack`/`att`/`atk`, `defence`/`defense`/`def`, `strength`/`str`, `hitpoints`/`hp`, `ranged`/`range`, `prayer`/`pray`, `magic`/`mage`, `woodcutting`/`wc`, `firemaking`/`fm`, `herblore`/`herb`, `runecrafting`/`runecraft`/`rc`), normalizing spaces, underscores, and hyphens.
  - Clamps target levels to `1..99`, updates skill XP/level via `PlayerAssistant.getXPForLevel` and `PlayerAssistant.getLevelForXP`, refreshes the skill, triggers `levelUp`, and sends a confirmation message.

### Cleanups & Deprecations
- `src/main/java/com/rs2/net/packets/impl/Commands.java`:
  - Removed the legacy `setlevel`, `level`, and `skill` switch cases from `adminCommands`.

* fix(quests): restore dark red journal titles and authentic Cook's Assistant completion text

Aligns the Cook's Assistant and Druidic Ritual quest journal scrolls (`interface 8134`) with authentic 2006 RS2 formatting. Restores the dark red (`@dre@`) quest title styling on line `8144` and updates the completed Cook's Assistant journal summary to list all quest rewards.

### Quest Journal Updates
- `plugins/quests/cooksassistant/CooksAssistantJournalPlugin.kt`:
  - Removed the per-stage overwrites of string `8144` so `@dre@Cook's Assistant` (dark red) persists across all stages.
  - Updated `STAGE_COMPLETE` text (`8147`–`8152`) to summarize helping the cook for the Duke of Lumbridge's birthday and list all rewards (`1 Quest Point`, `300 Cooking Experience`, `500 coins`, and access to the cook's range).
- `plugins/quests/druidicritual/DruidicRitualJournalPlugin.kt`:
  - Updated string `8144` to `@dre@Druidic Ritual` so the journal title renders in dark red.

* feat(plugins): split Online Repo into Plugins and Scripts sub-tabs

Separate external plugins and scripts into dedicated sub-tabs inside the
Plugin Hub Online Repo modal to match the local Plugins and Scripts tabs.

### Online Repo Sub-Tabs
- PluginPanelUI.java:
  - Add currentRepoSubTab state (0: Plugins, 1: Scripts) and
    getFilteredRepoEntries() filtering by entry.type.
  - Render Plugins and Scripts sub-tabs in the Online Repo header beside the
    Refresh button.
  - Update getContentHeight(), drawRepoList(), and handleModalClick() to
    use the active sub-tab's filtered list and reset scrollOffset on switch.

* feat(plugins): add passThroughDoors option to PluginContext.findPath

Allow visual pathfinders such as Quest Helper to route paths straight
through closed doors and gates without altering default script pathing.

### Pathfinding API
- PluginContext.java:
  - Add findPath(targetWorldX, targetWorldY, maxSearchRadius, allowPartial,
    passThroughDoors) overload while preserving default passThroughDoors=false
    on the 3-arg and 4-arg overloads.
  - Pre-scan local scene doors/gates with an Open action (excluding Pay-toll)
    and allow cardinal BFS transitions across those tiles when enabled.

* feat(client): add Plugin Hub search, Update All, SHA cache-busting, and ::hd plugin dispatch

Enhance the Plugin Hub UI, online repository client, command routing, and scene object interaction in the shared 2006Scape client.

### Core & Command Infrastructure
- `ClientPlugin.java` & `PluginManager.java`:
  - Added `handlesCommandsWhenDisabled()` (default `false`) so toggleable plugins can still receive chat commands when disabled.
  - Updated `PluginManager.onCommand(...)` to dispatch to plugins where `p.isEnabled() || p.handlesCommandsWhenDisabled()` while still respecting `isChatCommandsEnabled(p)`.
- `Hd117Plugin.java` & `Game.java`:
  - Moved `::hd` and `::117hd` out of `Game.java` into `Hd117Plugin.onCommand(...)` using `PluginManager.get().togglePlugin(this)`, keeping the Plugin Hub toggle, saved config, and `setHD117Enabled(...)` in sync.
- `Game.java`:
  - Intercepted `readChar(-796)` in `method73()` when `PluginPanelUI.isSearchFocused()` is `true` so keystrokes route to `PluginPanelUI.handleKeyChar(j)` instead of the chatbox.

### Plugin Hub UI & Online Repo
- `PluginPanelUI.java`:
  - Added search/filter bar (`searchQuery`, `searchFocused`, `isSearchFocused()`, `handleKeyChar(int ch)`, `drawSearchBar(...)`, `handleSearchBarClick(...)` with inline `"X"` clear button) across Plugins, Scripts, and Online Repo tabs.
  - Added `Update All` button, `Online Repo (N)` update count badge, `vOld -> vNew` version diff labels, and inline error banner.
- `PluginRepoClient.java`:
  - Centralized repository constants (`PLUGIN_REPO_SLUG`, `PLUGIN_REPO_BRANCH`, `PLUGIN_REPO_URL`, `PLUGIN_REPO_RAW_BASE`).
  - Added `resolveLatestMainSha()` (via `info/refs?service=git-upload-pack`) and `rewriteRawMainUrl(...)` to bypass Fastly CDN caching on `raw.githubusercontent.com` `/main/` URLs.

### Bug Fixes & Edge Cases
- `PluginContext.java`:
  - Updated `SceneObjectWrapper` to derive `localX`/`localY` (`worldX`/`worldY`) from the `uid` south-west anchor (`uid & 0x7f`, `(uid >> 7) & 0x7f`).
  - Deduplicated multi-tile objects by `uid` in `getSceneObjects(...)` and updated `interactObject(...)` to send the `uid` anchor coordinates to `invokeMenuAction(...)`.

* fix(woodcutting): prevent chopping trees that are already stumps

Validate the dynamic object manager state before starting or continuing a woodcutting action so players cannot chop a felled tree stump before it respawns.

### Bug Fixes & Edge Cases
- `Woodcutting.java`:
  - Added `GameEngine.objectManager.getObject(x, y, p.heightLevel)` check in `startWoodcutting(...)` to return early if the target tile currently holds `tree.getStump()` (or if `tree == null`).
  - Added the same stump check inside `WoodcuttingEvent.execute(...)` to stop the event if the tree was felled while chopping.

* fix(combat): reset autocastId when disabling autocast via combat menu button

Ensure clicking the autocast toggle button to disable magic completely clears autocast state so subsequent attacks use the selected melee combat style instead of re-enabling magic.

### Bug Fixes & Edge Cases
- `AutocastMenuButtonsPlugin.kt`:
  - Replaced manual `player.autocasting = false` + config `108 = 2` with `player.playerAssistant.resetAutocast()` (clearing `autocastId = -1`, `autocasting = false`, resetting config `108` to `0`, and restoring config `43` to `player.fightMode`).
  - Cleared `player.spellId = 0` and `player.usingMagic = false` to prevent lingering spell state on the next attack.

* fix(combat): set rangeItemUsed before triggering bow pullback GFX on NPC attacks

Ensure the bow pullback arrow graphic renders on the very first ranged attack against an NPC instead of reading an uninitialized `rangeItemUsed` value.

### Bug Fixes & Edge Cases
- `CombatAssistant.java`:
  - Moved `player.gfx100(RangeData.getRangeStartGFX(player));` in `attackNpc(...)` to after `player.rangeItemUsed` is assigned for crystal bows and regular arrows, matching `attackPlayer(...)`.

* fix(trade): allow trading stackable items into existing inventory stacks (#166)

Fix trade space validation on the first accept screen so stackable and noted items already present in the receiver's inventory do not require extra free slots, and align the status text with 2006 RS2.

### Bug Fixes & Edge Cases
- `ClickingButtons.java` (`case 13092`):
  - Count `requiredSlots` only for offered items that are not stackable/noted (`ItemDefinition.lookup(item.id).isStackable()`) or not already present in the receiver's inventory (`ot.getItemAssistant().playerHasItem(item.id)`).
  - Added `Integer.MAX_VALUE` stack-overflow check (`(long) ot.getItemAssistant().getItemAmount(item.id) + item.amount > Integer.MAX_VALUE`) before allowing stackable merges.
  - Updated trade interface `3431` messages to `"Other player doesn't have enough inventory space."` and `"You don't have enough inventory space."` and removed the custom chat messages.

* fix(objects): prevent ladder/trapdoor spam-click and Edgeville shed void teleports (#195)

Fix ladder and trapdoor climbing handlers so Edgeville shed trapdoor entries land cleanly inside Edgeville Dungeon and spam-clicking ladders or staircases cannot stack multiple teleports into the void.

### Bug Fixes & Edge Cases
- `ClimbOther.java`:
  - Fixed `useOther(...)` for the Edgeville shed trapdoor `(3097, 3468)` to teleport directly to `(3096, 9867)` instead of offsetting from `player.absX`/`player.absY + 6400`.
- `ObjectsActions.java`:
  - Added `break;` after matching `ClimbData` in `useOther(...)` so open trapdoors sharing ID `10698` are only handled once.
- `Climbing.java`:
  - Set `client.climbDelay` immediately when `handleClimbing(...)` is invoked (before scheduling the 1-tick `CycleEvent`) so multiple clicks in the same tick cannot queue duplicate climb events.
  - Added `client.absY < 6400` and `client.absY >= 6400` guards on `case 1733` and `case 1734`.
- `UseOther.java`:
  - Added `1200ms` `climbDelay` cooldown and `absY >= 6400` / `absY < 6400` direction guards to `useUp(...)` and `useDown(...)`.

* fix(doors): support Dark Warriors' Fortress double doors 14751/14752 (#292)

Fix Dark Warriors' Fortress entrance double doors at `(3021, 3632)` and `(3021, 3631)` so they open to `14753`/`14754` and close properly.

### Bug Fixes & Edge Cases
- `doubledoors.json`:
  - Replaced incorrect `1516`/`1519` IDs at `(3021, 3632, 0)` and `(3021, 3631, 0)` with the 377 cache IDs `14751` and `14752` (`face: 2`).
- `DoubleDoors.java`:
  - Imported `StaticObjectList.*` (`DOOR_14751`–`DOOR_14754`) and added `ADJACENT_PAIR_STEP`, `DEFAULT_PAIR_STEP`, `ADJACENT_OPEN_ID_STEP`, and `DEFAULT_OPEN_ID_STEP` constants.
  - Added `isAdjacentDoubleDoorId(...)` and `updateDoorId(...)` helpers so adjacent-ID double doors (`14751`/`14752` -> `14753`/`14754`) pair with `±1` offset and toggle with `±2` ID delta.

* fix(woodcutting): support chopping hollow trees for bark (#505)

Add hollow tree definitions to `Woodcutting.treeData` and fix `playerTrees(...)` so players can chop hollow trees (`2289` and `4060`) for bark (`3239`).

### Bug Fixes & Edge Cases
- `Woodcutting.java`:
  - Added `HOLLOW_SMALL` (`2289` -> stump `2310`) and `HOLLOW_LARGE` (`4060` -> stump `4061`) to `treeData` (level `45`, `83` XP, item `3239` Bark, `40` tick respawn, cut chance `8`).
  - Fixed `playerTrees(...)` swapped-index loop (`trees[i1][i]` capped at `6`) to check `treeData.getTree(tree) != null` and iterate all rows/elements of `trees`.

* fix(doors): pair 377 cache door IDs and register missing palace doors (#547)

Fix door ID toggling in `Doors.java`, register missing Al-Kharid Palace South and Varrock Palace doors in `doors.json`, and remove the legacy teleport workaround at Al-Kharid Palace South. All door IDs, faces, types, models, and recolors were validated against the Revision 377 cache (`loc.dat` and map region data) so doors toggle cleanly without changing appearance or becoming unclosable.

### Door Infrastructure
- `Doors.java` (`getToggledDoorId`):
  - Replaced naive `doorId + 1` / `doorId - 1` toggling with `getToggledDoorId(Doors d)` using `StaticObjectList.*` constants so non-adjacent 377 cache `Open` <-> `Close` pairs keep their exact model IDs and recolors.
  - Mapped `DOOR` (`3`) -> `DOOR_1531` (`1531`), `DOOR_59` (`59`) -> `DOOR_1534` (`1534`), and `DOOR_2556` (`2556`) -> `DOOR_1537` (`1537`), returning to `d.originalId` when closed.
  - Mapped `LARGE_DOOR_1508` (`1508`) <-> `LARGE_DOOR_1511` (`1511`) to avoid `null` object IDs `1509` and `1510`.
  - Mapped `LARGE_DOOR_1512` (`1512`) <-> `LARGE_DOOR_1515` (`1515`) and `LARGE_DOOR_1513` (`1513`) <-> `LARGE_DOOR_1514` (`1514`) based on matching 377 `loc.dat` models and recolors.

### Door Spawns & Cleanups
- `doors.json`:
  - Added Varrock Palace large door `(3223, 3491, 0)` (`id: 1512, face: 3, type: 0`).
  - Added Al-Kharid Palace South large doors `(3292, 3167, 0)` (`id: 1506, face: 3, type: 0`) and `(3293, 3167, 0)` (`id: 1508, face: 3, type: 0`).
- `ObjectsActions.java`:
  - Removed the `case 1506: case 1508:` `movePlayer` teleport hack at Al-Kharid Palace South (`y=3166`/`3167`) now that the doors open normally via `Doors.java`.

* feat(client,server): add WebSocket server support, 117HD chunked scenery, and TeaVM ScriptInterpreter compatibility

Updates shared 2006Scape Client rendering, plugin/script execution, and 2006Scape Server WebSocket transport to support the TeaVM Web client alongside Desktop and Android. Preserves Revision 377 protocol/cache behavior while fixing SD near-plane clipping and Web reflection edge cases.

### Shared Client Rendering & 117HD
- WorldController:
  - Bypassed Fixed-mode 512x334 frustum culling in Resizable mode and added per-triangle 3D near-plane clipping (NEAR_Z=48) with 64-bit backface cross-products.
- DesktopHd117Renderer, HD117Pipeline, HdSceneUploader:
  - Added 4x4 chunked static scenery VBO support and HD pipeline hooks.

### ScriptInterpreter & Plugin System
- ScriptInterpreter, PluginContext, PluginManager, PluginRepoClient:
  - Added direct dispatch for Math, System, String, List/Collection/Map, and Number/Boolean methods plus DesktopHooks.boxReflectValue wrapping for TeaVM.
  - Added public static PluginContext.hasAction, walkPath overlay updates, improved toggleSpecialAttack button matching, and UTF-8 localStorage-backed plugin config persistence.

### WebSocket Server Transport
- WebSocketFrameCodec, WebSocketJagGrabChannelInitializer, WebSocketServiceChannelInitializer, FileServer, Constants, docker-compose.yml:
  - Added WebSocket framing and service/JAGGRAB channel initializers for browser clients.
- ApolloHandler:
  - Filtered benign Linux Connection reset SocketException warnings in exceptionCaught.

* test(client): add JUnit 4.7 dependency and ScriptInterpreter unit tests

Adds JUnit 4.7 test support to the 2006Scape Client Maven build and introduces unit tests for ScriptInterpreter expression parsing, control flow, and execution.

### Test Infrastructure
- `2006Scape Client/pom.xml`:
  - Added `junit:junit:4.7` (`test` scope) dependency.
- `2006Scape Client/src/test/java/ScriptInterpreterTest.java`:
  - Added unit test suite covering `ScriptInterpreter` functionality (`3/3` tests passing via `mvn test`).

* refactor(client): rename 117HD pipeline, plugin, and renderer to 317HD

Renames all 117HD classes, settings, CLI flags, and renderer references in `2006Scape Client` to 317HD across the shared client and desktop rendering path.

### Core & Rendering Pipeline
- `HD317Pipeline.java`, `DesktopHd317Renderer.java`, `Hd317Plugin.java`:
  - Renamed from `HD117Pipeline.java`, `DesktopHd117Renderer.java`, and `Hd117Plugin.java` and updated all internal references.
- `ClientSettings.java`, `ClientArgs.java`, `Game.java`, `PluginManager.java`, `DesktopHooks.java`, `Model.java`, `WorldController.java`, `HdSceneUploader.java`, `HdProceduralGenerator.java`, `HdMaterial.java`, `HdGroundMaterial.java`:
  - Updated `HD_117` -> `HD_317`, `-117hd` -> `-317hd`, `setHD117Enabled`/`isHD117Enabled` -> `setHD317Enabled`/`isHD317Enabled`, and all plugin/UI/comment references to `317HD`.

* fix(317hd): render animated world objects (fires, torches) when static scenery is enabled

Fixes animated world objects (`Animable_Sub5` such as fires) disappearing in 317HD mode when static scenery VBOs are active across Desktop, Web, and Android clients.

### 317HD Rendering Pipeline
- `HD317Pipeline.java`:
  - Added `public static boolean drawingAnimatedObj` flag to distinguish non-`Model` animated `Animable` objects during per-frame rendering.
- `WorldController.java`:
  - Added `renderHdAnimable(...)` helper in `renderHdTile(...)` for `Object1`, `Object2`, `Object3`, and `Object5` draws, setting `HD317Pipeline.drawingAnimatedObj = !(animable instanceof Model)`.
- `HdSceneUploader.java`:
  - Updated `appendModel(...)` so `isStaticScenery` is `false` when `HD317Pipeline.drawingAnimatedObj` is `true`, ensuring animated objects skipped during static VBO baking are still uploaded and drawn each frame.

* fix(following): track previous tile and route non-combat following to enable follow dancing

Fixes non-combat player following so players trail behind moving targets and mutual follow dancing works authentically to 2006 RS2. Previously, `followPlayer()` always routed to the closest cardinal neighbor via `getFollowLocation()`, which caused two adjacent players following each other to pick their own current tiles and stand still.

### Player Movement & Following
- `Player.java`:
  - Added `prevX` and `prevY` fields to track each player's previous tile independently of `lastX`/`lastY` (which are used for random event returns and save fallbacks).
  - Updated `getNextWalkingDirection()` to record `prevX = absX; prevY = absY;` before each walking or running step.
  - Initialized `prevX` and `prevY` on login and teleport to `(absX, absY - 1)` when walkable via `Region.canMove`, falling back to `(absX, absY)` otherwise.
- `PlayerAssistant.java`:
  - Updated `followPlayer()` to route non-combat following (`playerIndex == 0`) to the target player's `(other.prevX, other.prevY)`, falling back to `getFollowLocation(otherX, otherY)` if the previous tile equals the target's current tile, is clipped, or is inaccessible.
  - Added an early `stopMovement()` return when already standing on `(targetX, targetY)` and reset following if the target changes `heightLevel`.
  - Preserved `getFollowLocation(otherX, otherY)` and range/line-of-sight checks for combat following (`playerIndex > 0`).

Closes 2006-Scape/2006Scape#582

* feat(npcs): add npcType-indexed NpcTickEvent and implement authentic Imp teleportation plugin

Introduces an `npcType`-indexed `NpcTickEvent` / `NpcTickSubscriber` dispatch pipeline for per-NPC tick plugins with zero allocation overhead on normal NPCs, and implements authentic 2006 RS2 Imp teleportation (`IMP` `708`, `IMP_709` `709`) as a Kotlin plugin. Also adds NPC teleport synchronization in `PlayerHandler` so multi-tile NPC teleports update cleanly on the client.

### Core Event & NPC Infrastructure
- `NpcTickEvent.java`, `NpcTickSubscriber.java`, `EventProvider.java`, `UniversalEventProvider.java`, `Player.java`:
  - Added `NpcTickEvent` (exposing `index`, `npc`, `cancelTick()`, and `isTickCancelled()`) and `NpcTickSubscriber` (`npcTypes()`).
  - Indexed `NpcTickSubscriber` plugins by `npcType` in `UniversalEventProvider.npcTickSubscribers`; `postNpcTick(int, Npc)` performs an O(1) lookup and returns `false` immediately without event allocation when no subscribers match.
- `NpcHandler.java`:
  - Dispatched `Player.postNpcTick(i, npcs[i])` inside `process()`, skipping retaliation and random-walk on that tick if `cancelTick()` is called.
- `Npc.java`, `PlayerHandler.java`:
  - Added `Npc.teleported` (cleared in `clearUpdateFlags()`) and updated `PlayerHandler.updateNPC` to remove and re-add teleported NPCs via `addNewNPC` so clients receive new coordinates and arrival graphics immediately.

### New NPC Plugins
- `plugins/npc/imp/ImpTeleportPlugin.kt`:
  - Subscribes to `NpcTickEvent` for `IMP` (`708`) and `IMP_709` (`709`).
  - Triggers a `1 in 10` teleport chance on non-lethal combat hits (`lastDamageTaken` edge detection while `HP > 0`, not dead, and not frozen).
  - Runs a per-Imp idle timer (`70` ticks on spawn, `50`–`200` ticks thereafter) with a `1 in 2` teleport chance when out of combat for more than `8` ticks (`4800ms`).
  - Selects a reachable, unclipped tile within `±20` tiles via `Region.getClipping` and `PathFinder.accessible`, plays smoke-puff graphics (`86`) on departure (`stillGfx`) and arrival (`gfx0`), resets NPC combat state and attacker targeting, and cancels the rest of that tick.

Closes 2006-Scape/2006Scape#591

* fix(client): fix web walker routing, door reachability, and special attack detection

Fix overworld road-graph edges in `WorldWebWalker.java` against Revision 377 map clipping, improve `PluginContext.java` pathing and closed-gate reachability, eliminate duplicate `walkTo` spam while moving, and fix special attack energy/active detection and button toggling for `2006Scape Server`.

### Web Walker & Overworld Routing
- `WorldWebWalker.java`:
  - Removed fence-crossing edges `{37, 38}` and `{35, 53}`, replacing them with `{37, 53}` so Al-Kharid routes around the north of the fenced field (`38 <-> 59 <-> 53 <-> 37`).
  - Removed river-crossing edges `{24, 55}`, `{27, 31}`, and `{30, 31}` where no 2006 RS2 bridge exists; moved node `31` (`Lumbridge Chicken Coop Outside`) to `{3238, 3288}` and connected `{34, 31}` so west-bank routes cross Lumbridge Bridge.
  - Added North Varrock Palace bypass nodes `56` (`{3162, 3470}`), `60` (`{3186, 3496}`), `61` (`{3215, 3508}`), `62` (`{3244, 3503}`), `63` (`{3243, 3473}`), and `64` (`{3246, 3443}`) connecting `55 <-> 56 <-> 60..64 <-> 50` (`Varrock East Bank`).
  - Widened `findRoute` reachable start-node search from `40` to `50` tiles (`canReach(..., 52, false)`).

### Pathfinding, Door Reachability & Walk Hysteresis
- `PluginContext.java`:
  - Widened `canReach` radius cap from `45` to `52` (full `104x104` scene) and scaled BFS iteration caps (`canReach` to `Math.max(6000, (rad * 2 + 1) * (rad * 2 + 1))`, `findPath` to `104 * 104`).
  - Added `isTollGate` (`"pay-toll"` substring match) so `"Pay-toll(10gp)"` gates are excluded from free `passThroughDoors` pathing and `openNearestClosedDoor`.
  - Added `isDoorReachable` so `openNearestClosedDoor` checks orthogonal neighbors instead of failing `canMeleeReach` across closed wall/gate clipping flags.
  - Updated `walkToSmartInternal` to invoke `WorldWebWalker` whenever `findPath(targetWorldX, targetWorldY, 50, false, openDoors).isEmpty()` (even at `dist <= 16` across fences/rivers), pass `openDoors` to local partial `findPath`, guard the `<= 16` partial fallback with `canReach`, and skip duplicate `walkTo` calls while `isPlayerMoving()` is making progress toward the same committed goal.

### Special Attack Detection & Toggling
- `PluginContext.java`:
  - Added `collectWidgetsByType` and `findSpecialBarTextWidget` to read filled segment widths (`anInt263 != 0` on `barId - 1 .. barId - 10`) in `getSpecialEnergy()` and `@yel@` text state in `isSpecialAttackActive()` when configs `300`/`301` are not sent by `2006Scape Server`.
  - Fixed `toggleSpecialAttack()` to check known special button IDs first (including `12311` for Abyssal whip instead of container `12323`) and exclude `type == 4` text labels from clickable button fallback.

* chore(client): update plugin repository slug to 2006-Scape/Client-Extensions

Point `PluginRepoClient` at the `2006-Scape/Client-Extensions` repository for downloading external plugins and scripts.

### Client Changes
- `PluginRepoClient.java`:
  - Updated `PLUGIN_REPO_SLUG` from `"Dark98/2006scape-plugins"` to `"2006-Scape/Client-Extensions"`.

* Fix remapped quest journal stages

Resolve duplicate stage conditions in the Pirate's Treasure and The Knight's Sword journals after quest stages were remapped. Use Hector's key to distinguish the two Pirate's Treasure objectives sharing stage 2, and place the chest and Falador objectives on separate journal lines. Remove the stale Knight's Sword stage 4 and stage 8 entries, show the sword return objective at stage 6 when the player has the blurite sword, and leave quest progression unchanged.

---------

Co-authored-by: ipkpjersi <ipkpjersi@gmail.com>
2026-12-01 03:21:56 +00:00
ipkpjersi 73732d3adf Fixed typo in comment (#671)
* Fixed typo in comment
2026-11-15 19:31:39 +00:00
Dark98 67147ef466 feat(commands): migrate item, npc, spellbook, and tele to plugins and add item/npc search
Migrate legacy hardcoded administrative and utility commands from Commands.java
to modular Kotlin event subscriber plugins, introduce dedicated item and NPC search
commands, and establish a permission-tiered command event hierarchy bounded by
Revision 377 cache specifications.

### Command Infrastructure
- CommandEvent.java:
  - Remove final modifier to allow permission-specific command event inheritance.
- ModeratorCommandEvent.java, AdminCommandEvent.java, DeveloperCommandEvent.java:
  - Add strongly typed event classes matching player permission tiers:
    Moderator (rights >= 1), Admin (rights >= 2), and Developer (rights == 3).
- Commands.java:
  - Dispatch permission-tiered command events across the event bus alongside switch handling.
  - Remove legacy switch implementations for ::item, ::npc, ::spellbook, and ::tele.

### Migrated Command Plugins
- SpawnItem.kt (::spawnitem, ::item):
  - Support both numeric IDs and fuzzy name resolution (exact, prefix, and substring).
  - Add quantity shorthand parsing for thousand (k), million (m), and billion (b) multipliers.
  - Support positional 'note' and 'noted' flags at the start or end of arguments; deprecate 'cert'.
  - Restrict valid IDs to Revision 377 cache bounds (0..7955).
  - Guard confirmation message against full inventory state when addItem() returns false.
- SpawnNpc.kt (::spawnnpc, ::npc):
  - Support both numeric IDs and fuzzy name resolution.
  - Validate against Revision 377 NPC ID range (0..3851), enabling ID 0 (Hans) spawning.
  - Calculate authentic combat, hitpoints, attack, and defence values with definitions fallback.
- Spellbook.kt (::spellbook):
  - Toggle between modern and ancient spellbooks when executed without arguments.
  - Support explicit 'modern'/'normal' and 'ancient'/'ancients' subcommands.
  - Cleanly reset autocast state via player.playerAssistant.resetAutocast().
- Teleport.kt (::teleport, ::tele):
  - Support coordinate teleportation with comma-tolerant token parsing (e.g. ::teleport 3222, 3218 0).
  - Add standard destination nicknames: lumby, fally, cammy, ardy, ape, and apeatoll.
  - Trigger authentic spell animations (modern 714/715, ancient 1979), graphics (308/392), and teleport sound effects.

### New Search Commands
- SearchItem.kt (::searchitem, ::itemsearch):
  - Search items by name or ID and render results on scrollable interface 8134.
  - Optimize interface clear range (8146..8195) to preserve title and subtitle lines without redundant packets.
  - Format output consistently in @bla@ with @dre@ noted tags and @blu@ ID labels.
  - Cap query scan at Revision 377 MAX_ITEM_ID (7955).
- SearchNpc.kt (::searchnpc, ::npcsearch):
  - Search NPCs by name or ID with scrollable interface 8134 display.
  - Format output in @bla@ with @yel@ combat levels and @blu@ ID labels.
  - Cap query scan at Revision 377 MAX_NPC_ID (3851).
2026-11-15 19:29:42 +00:00
Dark98 e4c6fb3ed8 Refactor GlobalDropsHandler: improve drop handling and remove unnecessary spawnedDrops set 2026-11-15 02:37:29 +00:00
Dark98 9b873cdac4 Update Discord integration to only set activity on world 1 2026-11-15 02:25:45 +00:00
Dark98 741a88cb19 Add RSA configuration parameters to ConfigLoader 2026-11-15 02:14:04 +00:00
Dark98 2bacdcc0f7 Refactor plugin loading: improve error handling and adjust debug logging 2026-11-15 00:44:05 +00:00
Dark98 8919731c63 Add Drops command plugin
credits to @ipkpjersi
2026-11-13 23:34:58 +00:00
Dark98 0790eaf4a3 Remove EverythingRS API integration and related dependencies 2026-11-13 01:19:45 +00:00
Dark98 e1efbb0fdf Website Integration Rewrite, Upgrades & Plugin Migration
- Remove synchronous website integration execution from the GameEngine 600ms tick loop
- Decouple website credentials and toggles from ConfigLoader, secrets.json, and Constants.WEBSITE_INTEGRATION
- Introduce modular "website" configuration group with independent toggles for players_online and registered_accounts
- Consolidate background tasks onto a single daemon ScheduledExecutorService with graceful lifecycle management via ServerStartupEvent and ServerShutdownEvent
- Optimize character directory counting with Java NIO streaming to prevent heap allocations
- Add UTF-8 URL encoding, User-Agent headers, safe stream handling, and network exception throttling
2026-11-13 01:12:15 +00:00
Dark98 622b3264e1 Add log4j configuration 2026-11-13 00:23:52 +00:00
Dark98 84c80a8960 ConfigLoader: cleanup settings loading and improve file reading 2026-11-13 00:23:18 +00:00
Dark98 d624ce0ca9 ConfigLoader: streamline configuration loading, improve error handling and remove fallback flat json handling 2026-11-13 00:07:19 +00:00
Dark98 58f8d7da53 ConfigLoader: use try for BufferedReader and BufferedWriter 2026-11-13 00:03:40 +00:00
Dark98 fbc3595da1 Discord Bot Rewrite, Upgrades & Plugin Migration
- Replace deprecated Core Javacord implementation with a modern JDA 5.x Kotlin plugin
- Introduce event-driven architecture via ServerConfigEvent, ServerStartupEvent, ServerShutdownEvent, and CommandEvent
- Implemented global event posting functionality in Player class.
- Refactored PluginService to handle potential ClassNotFoundException more gracefully.
- Improved CustomPrintStream to better identify the caller context in log messages.
- Refactor server configuration into modular groups ("core" and "discord") with backward compatibility for legacy flat keys
2026-11-12 23:56:07 +00:00
Dark98 87fece4854 Enhance socket management and improve android support
- Added proper socket closure and nullification in OnDemandFetcher to prevent resource leaks.
- Introduced touch target areas in RSApplet to streamline touch interactions.
- Made fullGameScreen public in RSApplet for external access.
- Implemented a master screen buffer and a locking mechanism in RSImageProducer for better synchronization.
- Reduced initial sleep duration in Signlink and added a close method for better resource management.
- Increased texture array sizes in Texture for improved rendering capabilities.
- Modified WorldController to optimize rendering logic based on platform (Android) and enhance performance.
2026-11-10 20:34:25 +00:00
Dark98 9570a35bae Rewrite Al-Kharid gate interactions and border guard dialogues closes (#661)
- Updated NpcFirstClickEvent to include npcIndex for better handling of NPC interactions.
- Enhanced Npc and NpcHandler classes to support new interaction logic and ensure NPCs face players correctly.
- Refined packet handling for NPC clicks and button actions to integrate new dialogue and interaction flows.
2026-11-10 02:52:33 +00:00
Dark98 099f2b6826 Set ServerConfig.json in runServer.sh by default 2026-11-08 19:37:05 +00:00
Dark98 8897c72bc5 Disable Android Client build flag and remove debugging comment 2026-11-08 19:33:17 +00:00
Dark98 729eb4237c Improve multi-tile NPC pathing, combat reach, and collision closes (#658)
- Implement O(1) AABB Chebyshev distance calculations in NpcData.goodDistanceNpc and inNpc.
- Enforce authentic 2006 RS2 1-tile melee rules: require cardinal alignment for 1x1 entities while permitting corner melee reach for multi-tile NPCs.
- Add multi-tile leading edge obstacle collision handling in NpcHandler.handleClipping.
- Prevent attacking from underneath NPC body and properly direct NPC step-off away from player.
- Clamp projectile LOS raycast checks to nearest perimeter tile on NPC bounding box.
- Update TzTok-Jad melee stance detection to use multi-tile perimeter reach.
- Update ClickNPC and PlayerAssistant to respect multi-tile bounds for interactions and following.
2026-11-08 00:48:08 +00:00
Dark98 ef9f8132e7 Fix dueling NPE in AttackPlayer and add bounds check in ChallengePlayer (closes #639) 2026-11-04 00:46:03 +00:00
Dark98 63fcbf29a5 Bump setup-java to v5 in maven workflow 2026-11-04 00:39:11 +00:00
Dark98 d02984e99e Do not recurse private submodules during Maven CI checkout 2026-11-04 00:38:07 +00:00
Dark98 758e2688f8 Update GitHub Actions workflow to use actions/upload-artifact@v4 and setup-java@v4 2026-11-04 00:36:59 +00:00
Dark98 fb2bc30305 Add Android client compatibility hooks and 2006Scape-Android submodule 2026-11-04 00:28:18 +00:00
360 changed files with 56684 additions and 5827 deletions

No files matched your search

-18
View File
@@ -1,18 +0,0 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/java
{
"name": "Java",
// Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile
"image": "maven:3.9.10-eclipse-temurin-8",
// Use 'forwardPorts' to make a list of ports inside the container available locally.
"forwardPorts": [43594, 43595, 8080],
// Configure tool-specific properties.
"customizations" : {
"jetbrains" : {
"backend" : "IntelliJ"
}
},
}
+11 -11
View File
@@ -13,9 +13,9 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up JDK 1.8
uses: actions/setup-java@v2
uses: actions/setup-java@v5
with:
distribution: 'zulu'
java-version: '8'
@@ -24,15 +24,15 @@ jobs:
id: build
run: |
mvn -B clean package
mkdir -p ~/artifacts
cp "2006Scape Client/target/client-1.0-jar-with-dependencies.jar" ~/artifacts/Client.jar
cp "2006Scape Server/target/server-1.0-jar-with-dependencies.jar" ~/artifacts/Server.jar
cp "2006Scape Server/ServerConfig.Sample.json" ~/artifacts/ServerConfig.json
cp SinglePlayer.bat ~/artifacts/
cp -r "2006Scape Server/plugins" ~/artifacts/
cp -r "2006Scape Server/data" ~/artifacts/
mkdir -p artifacts
cp "2006Scape Client/target/client-1.0-jar-with-dependencies.jar" artifacts/Client.jar
cp "2006Scape Server/target/server-1.0-jar-with-dependencies.jar" artifacts/Server.jar
cp "2006Scape Server/ServerConfig.Sample.json" artifacts/ServerConfig.json
cp SinglePlayer.bat artifacts/
cp -r "2006Scape Server/plugins" artifacts/
cp -r "2006Scape Server/data" artifacts/
- name: Publish build to GH Actions
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
path: ~/artifacts/*
name: 2006Scape-SinglePlayer
path: artifacts/
+5
View File
@@ -12,6 +12,11 @@
2006Scape Client/bin/
*.prefs
*.classpath
target/
**/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
+3
View File
@@ -0,0 +1,3 @@
[submodule "2006Scape-Android"]
path = 2006Scape-Android
url = https://github.com/2006-Scape/2006Scape-Android.git
+14
View File
@@ -13,6 +13,20 @@
<version>1.0</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
@@ -0,0 +1,70 @@
/**
* Desktop stub for AndroidHooks so that guarded code compiles cleanly under Maven.
* In the Android build, this file is replaced by the actual Android implementation.
*/
public final class AndroidHooks {
private AndroidHooks() {}
public static boolean isAppInBackground() {
return false;
}
public static void decodeImage(Sprite sprite, byte[] abyte0) {}
public static String getClipBoard() {
return "";
}
public static void takeScreenshot(Game game, boolean sendMessage, String... subfolders) {}
public static void showErrorScreen(Game game, boolean loadingError, boolean genericLoadingError, boolean rsAlreadyLoaded) {}
public static void playSound(byte[] buffer, int offset, int length, int level, int delay) {}
public static void setSoundVolume(int config) {}
public static String getCacheDir() {
return "";
}
public static void playMidi(String location, int midiVolume) {}
public static void stopMidi() {}
public static boolean setMidiVolume(int value) {
return false;
}
public static Object getMusicPlayer() {
return null;
}
public static void pauseMidi() {}
public static void resumeMidi() {}
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<ClientPlugin> plugins, java.util.List<ClientScript> 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) {}
}
}
+20 -16
View File
@@ -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];
+9 -8
View File
@@ -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;
}
@@ -15,4 +15,7 @@ abstract class Class56 {
abstract void method832(int i);
abstract void method833();
void setLoop(boolean loop, boolean restartIfStopped) {
}
}
@@ -1,7 +1,6 @@
/* Class56_Sub1_Sub1 - Decompiled by JODE
* Visit http://jode.sourceforge.net/
*/
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiMessage;
@@ -10,59 +9,170 @@ import javax.sound.midi.Receiver;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Soundbank;
import javax.sound.midi.Synthesizer;
final class Class56_Sub1_Sub1 extends Class56_Sub1 implements Receiver
{
private static final Object MIDI_LOCK = new Object();
private static final Object RECEIVER_LOCK = new Object();
private static Receiver aReceiver1850 = null;
private static Sequencer aSequencer1851 = null;
private static Synthesizer aSynthesizer = null;
final void method827(int i, byte[] is, int i_0_, boolean bool) {
if (aSequencer1851 != null) {
synchronized (MIDI_LOCK) {
if (aSequencer1851 != null && aSequencer1851.isOpen() && is != null && is.length > 0) {
try {
if (aSequencer1851.isRunning()) {
aSequencer1851.stop();
}
method838(-1L);
Sequence sequence = MidiSystem.getSequence(new ByteArrayInputStream(is));
aSequencer1851.setSequence(sequence);
aSequencer1851.setLoopCount(!bool ? 0 : -1);
method835(0, i, -1L);
aSequencer1851.setTickPosition(0);
aSequencer1851.setLoopCount(!bool ? 0 : Sequencer.LOOP_CONTINUOUSLY);
method840(i, -1L);
aSequencer1851.start();
} catch (Exception exception) {
/* empty */
System.err.println("MIDI playback error: " + exception.getMessage());
}
}
}
}
final void method833() {
if (aSequencer1851 != null) {
synchronized (MIDI_LOCK) {
if (aSequencer1851 != null && aSequencer1851.isOpen()) {
try {
if (aSequencer1851.isRunning()) {
aSequencer1851.stop();
}
method838(-1L);
} catch (Exception ignored) {
}
}
}
}
public final synchronized void send(MidiMessage midimessage, long l) {
@Override
final void setLoop(boolean loop, boolean restartIfStopped) {
synchronized (MIDI_LOCK) {
if (aSequencer1851 != null && aSequencer1851.isOpen()) {
aSequencer1851.setLoopCount(loop ? Sequencer.LOOP_CONTINUOUSLY : 0);
if (restartIfStopped && !aSequencer1851.isRunning() && aSequencer1851.getSequence() != null) {
aSequencer1851.setTickPosition(0);
aSequencer1851.start();
}
}
}
}
public final void send(MidiMessage midimessage, long l) {
synchronized (RECEIVER_LOCK) {
if (aReceiver1850 == null || midimessage == null) {
return;
}
byte[] is = midimessage.getMessage();
if (is.length < 3 || !method837(is[0], is[1], is[2], l))
if (is.length < 3 || !method837(is[0], is[1], is[2], l)) {
aReceiver1850.send(midimessage, l);
}
}
}
private static Soundbank loadCustomSoundbank() {
String cacheDir = Signlink.findcachedir();
String[] fileCandidates = {
cacheDir + "soundfont.sf2",
cacheDir + "TimGM6mb.sf2",
"soundfont.sf2",
"TimGM6mb.sf2"
};
for (String path : fileCandidates) {
File file = new File(path);
if (file.isFile() && file.canRead()) {
try {
return MidiSystem.getSoundbank(file);
} catch (Exception ignored) {
}
}
}
String[] resourceCandidates = {"/soundfont.sf2", "/TimGM6mb.sf2"};
for (String res : resourceCandidates) {
try (InputStream in = Class56_Sub1_Sub1.class.getResourceAsStream(res)) {
if (in != null) {
return MidiSystem.getSoundbank(in);
}
} catch (Exception ignored) {
}
}
return null;
}
Class56_Sub1_Sub1() {
synchronized (MIDI_LOCK) {
try {
Soundbank customBank = loadCustomSoundbank();
if (customBank != null) {
aSynthesizer = MidiSystem.getSynthesizer();
aSynthesizer.open();
if (aSynthesizer.isSoundbankSupported(customBank)) {
Soundbank def = aSynthesizer.getDefaultSoundbank();
if (def != null) {
aSynthesizer.unloadAllInstruments(def);
}
aSynthesizer.loadAllInstruments(customBank);
}
aReceiver1850 = aSynthesizer.getReceiver();
} else {
aReceiver1850 = MidiSystem.getReceiver();
}
aSequencer1851 = MidiSystem.getSequencer(false);
aSequencer1851.getTransmitter().setReceiver(this);
aSequencer1851.open();
method838(-1L);
} catch (Exception exception) {
closeResources();
Game.method790();
}
}
}
private static void closeResources() {
if (aSequencer1851 != null) {
try {
if (aSequencer1851.isRunning()) {
aSequencer1851.stop();
}
} catch (Exception ignored) {
}
try {
aSequencer1851.close();
} catch (Exception ignored) {
}
aSequencer1851 = null;
}
synchronized (RECEIVER_LOCK) {
if (aReceiver1850 != null) {
try {
aReceiver1850.close();
} catch (Exception ignored) {
}
aReceiver1850 = null;
}
if (aSynthesizer != null) {
try {
aSynthesizer.close();
} catch (Exception ignored) {
}
aSynthesizer = null;
}
}
}
final void method828() {
if (aSequencer1851 != null) {
aSequencer1851.close();
aSequencer1851 = null;
}
if (aReceiver1850 != null) {
aReceiver1850.close();
aReceiver1850 = null;
synchronized (MIDI_LOCK) {
closeResources();
}
}
@@ -71,18 +181,26 @@ final class Class56_Sub1_Sub1 extends Class56_Sub1 implements Receiver
}
final void method831(int i) {
if (aSequencer1851 != null) {
synchronized (MIDI_LOCK) {
if (aSequencer1851 != null && aReceiver1850 != null) {
method840(i, -1L);
}
}
}
final synchronized void method830(int i, int i_2_) {
if (aSequencer1851 != null) {
final void method830(int i, int i_2_) {
synchronized (MIDI_LOCK) {
if (aSequencer1851 != null && aReceiver1850 != null) {
method835(i_2_, i, -1L);
}
}
}
final void method836(int i, int i_5_, int i_6_, long l) {
synchronized (RECEIVER_LOCK) {
if (aReceiver1850 == null) {
return;
}
try {
ShortMessage shortmessage = new ShortMessage();
shortmessage.setMessage(i, i_5_, i_6_);
@@ -91,9 +209,11 @@ final class Class56_Sub1_Sub1 extends Class56_Sub1 implements Receiver
/* empty */
}
}
}
final void method832(int i) {
if (i > -90)
if (i > -90) {
method833();
}
}
}
@@ -29,6 +29,11 @@ final class Class56_Sub1_Sub2 extends Class56_Sub1 implements Runnable
}
}
@Override
final synchronized void setLoop(boolean loop, boolean restartIfStopped) {
aBoolean1854 = loop;
}
final void method836(int i, int i_4_, int i_5_, long l) {
method845(i, (int) l, i_4_, i_5_);
}
@@ -0,0 +1,160 @@
import java.util.ArrayList;
import java.util.List;
public final class ClientArgs {
private ClientArgs() {}
public static void apply(String rawArgs, Game game) {
if (rawArgs == null || rawArgs.trim().isEmpty()) {
return;
}
apply(splitArgs(rawArgs), game);
}
public static void apply(String[] args, Game game) {
if (args == null || args.length == 0) {
return;
}
for (int i = 0; i < args.length; i++) {
if (args[i] == null) continue;
String arg = args[i].trim().toLowerCase();
switch (arg) {
case "-dev":
case "-local":
case "-offline":
ClientSettings.SERVER_IP = "localhost";
ClientSettings.CHECK_CRC = false;
break;
case "-no-crc":
case "-no-cache-crc":
ClientSettings.CHECK_CRC = false;
break;
case "-crc":
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;
if (!ClientSettings.ANDROID) {
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;
break;
case "-no-snow":
case "-hide-snow":
case "-disable-snow":
ClientSettings.SNOW_FLOOR_ENABLED = false;
ClientSettings.SNOW_FLOOR_FORCE_ENABLED = false;
ClientSettings.SNOW_OVERLAY_FORCE_ENABLED = false;
ClientSettings.SNOW_OVERLAY_ENABLED = false;
break;
case "-no-roofs":
case "-hide-roofs":
case "-disable-roofs":
ClientSettings.HIDE_ROOFS = true;
break;
case "-roofs":
case "-show-roofs":
ClientSettings.HIDE_ROOFS = false;
break;
case "-show-zoom":
ClientSettings.SHOW_ZOOM_LEVEL_MESSAGES = true;
break;
case "-screenshots":
case "-enable-screenshots":
ClientSettings.SCREENSHOTS_ENABLED = true;
break;
case "-auto-screenshots":
case "-enable-auto-screenshots":
ClientSettings.AUTOMATIC_SCREENSHOTS_ENABLED = true;
break;
}
if (args[i].startsWith("-") && (i + 1) < args.length && !args[i + 1].startsWith("-")) {
String val = args[++i];
switch (arg) {
case "-s":
case "-server":
case "-ip":
ClientSettings.SERVER_IP = val;
break;
case "-w":
case "-world":
try {
ClientSettings.SERVER_WORLD = Integer.parseInt(val);
} catch (NumberFormatException ignored) {}
break;
case "-u":
case "-user":
case "-username":
if (game != null) {
game.myUsername = val;
}
break;
case "-p":
case "-pass":
case "-password":
if (game != null) {
game.myPassword = val;
}
break;
}
}
}
// 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) {
if (input == null || input.trim().isEmpty()) {
return new String[0];
}
List<String> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
boolean insideQuotes = false;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c == '"' || c == '\'') {
insideQuotes = !insideQuotes;
} else if (Character.isWhitespace(c) && !insideQuotes) {
if (sb.length() > 0) {
list.add(sb.toString());
sb.setLength(0);
}
} else {
sb.append(c);
}
}
if (sb.length() > 0) {
list.add(sb.toString());
}
return list.toArray(new String[0]);
}
}
@@ -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<PluginConfigItem> 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<MenuEntry> 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;
}
}
@@ -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<String, Long> 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<String> getCommandNames() {
return Collections.emptyList();
}
public List<PluginConfigItem> 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) {
}
}
@@ -7,6 +7,61 @@ import java.math.BigInteger;
*/
public class ClientSettings {
/**
* @Android
* Flag indicating Android build/environment.
*/
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.
*/
public static int VIEWPORT_WIDTH = 512;
public static int VIEWPORT_HEIGHT = 334;
/**
* @QoL
* Require control key to zoom the client
@@ -90,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
@@ -139,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");
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,577 @@
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
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;
Image image = Toolkit.getDefaultToolkit().createImage(abyte0);
if (comp != null) {
MediaTracker mediatracker = new MediaTracker(comp);
mediatracker.addImage(image, 0);
mediatracker.waitForAll();
sprite.width = image.getWidth(comp);
sprite.height = image.getHeight(comp);
} else {
Canvas canvas = new Canvas();
MediaTracker mediatracker = new MediaTracker(canvas);
mediatracker.addImage(image, 0);
mediatracker.waitForAll();
sprite.width = image.getWidth(canvas);
sprite.height = image.getHeight(canvas);
}
sprite.trimWidth = sprite.width;
sprite.trimHeight = sprite.height;
sprite.anInt1442 = 0;
sprite.anInt1443 = 0;
sprite.pixels = new int[sprite.width * sprite.height];
PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, sprite.width, sprite.height, sprite.pixels, 0, sprite.width);
pixelgrabber.grabPixels();
} catch (Exception _ex) {
System.out.println("Error converting jpg");
}
}
public static String getClipBoard() {
String myString = "";
try {
myString = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
} catch (Exception e) {
e.printStackTrace();
}
String output = "";
for (int i = 0; i < myString.length(); i++) {
int j = (int) myString.charAt(i);
if (j >= 32 && j <= 122) {
output += (char) j;
}
}
return output;
}
public static void takeScreenshot(Game game, boolean sendMessage, String... subfolders) {
try {
// 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();
int w = window.getWidth();
int h = window.getHeight();
Robot robot = new Robot(window.getGraphicsConfiguration().getDevice());
Rectangle captureSize = new Rectangle(x, y, w, h);
BufferedImage bufferedimage = robot.createScreenCapture(captureSize);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd-HH_mm_ss");
String dateTime = dateFormat.format(new Date());
String fileExtension = game.myUsername != null && !game.myUsername.isEmpty() ? game.myUsername : ClientSettings.SERVER_NAME;
String subfolderPath = String.join(File.separator, subfolders);
if (!subfolderPath.isEmpty()) {
subfolderPath += File.separator;
}
String screenshotDir = System.getProperty("user.home") + File.separatorChar + ClientSettings.SERVER_NAME + File.separatorChar + "screenshots" + File.separatorChar + subfolderPath;
File dir = new File(screenshotDir);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(screenshotDir, fileExtension + "_" + dateTime + ".png");
if (!file.exists()) {
ImageIO.write(bufferedimage, "png", file);
if (sendMessage) {
game.pushMessage("A picture has been saved in your screenshots folder.", 0, "");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void showErrorScreen(Game game, boolean loadingError, boolean genericLoadingError, boolean rsAlreadyLoaded) {
Component comp = game.getGameComponent();
if (comp == null) return;
Graphics g = comp.getGraphics();
if (g == null) return;
g.setColor(Color.black);
g.fillRect(0, 0, 765, 503);
game.method4(1);
if (loadingError) {
g.setFont(new Font("Helvetica", 1, 16));
g.setColor(Color.yellow);
int k = 35;
g.drawString("Sorry, an error has occured whilst loading " + ClientSettings.SERVER_NAME + "", 30, k);
k += 50;
g.setColor(Color.white);
g.drawString("To fix this try the following (in order):", 30, k);
k += 50;
g.setColor(Color.white);
g.setFont(new Font("Helvetica", 1, 12));
g.drawString("1: Try closing ALL open web-browser windows, and reloading", 30, k);
k += 30;
g.drawString("2: Try clearing your web-browsers cache from tools->internet options", 30, k);
k += 30;
g.drawString("3: Try using a different game-world", 30, k);
k += 30;
g.drawString("4: Try rebooting your computer", 30, k);
k += 30;
g.drawString("5: Try selecting a different version of Java from the play-game menu", 30, k);
}
if (genericLoadingError) {
g.setFont(new Font("Helvetica", 1, 20));
g.setColor(Color.white);
g.drawString("Error - unable to load game!", 50, 50);
g.drawString("To play " + ClientSettings.SERVER_NAME + " make sure you play from", 50, 100);
g.drawString("" + ClientSettings.SERVER_WEBSITE + "", 50, 150);
}
if (rsAlreadyLoaded) {
g.setColor(Color.yellow);
int l = 35;
g.drawString("Error a copy of " + ClientSettings.SERVER_NAME + " already appears to be loaded", 30, l);
l += 50;
g.setColor(Color.white);
g.drawString("To fix this try the following (in order):", 30, l);
l += 50;
g.setColor(Color.white);
g.setFont(new Font("Helvetica", 1, 12));
g.drawString("1: Try closing ALL open web-browser windows, and reloading", 30, l);
l += 30;
g.drawString("2: Try rebooting your computer, and reloading", 30, l);
}
}
public static void checkJavaVersion() {
if (!System.getProperty("sun.arch.data.model", "").contains("64")) {
JOptionPane.showMessageDialog(null, "You're running 32-bit java. This will definitely cause problems.\nYou can get the right Java 8 at AdoptOpenJDK.net", "You're running 32-bit Java!", JOptionPane.INFORMATION_MESSAGE);
System.out.println("Please upgrade to 64-bit java to avoid problems! (AdoptOpenJDK.net)");
}
try {
if (Double.parseDouble(System.getProperty("java.specification.version", "1.8")) >= 1.9) {
JOptionPane.showMessageDialog(null, "You're not running Java 8. If you're using Parabot, this will cause problems!\nYou can get Java 8 from AdoptOpenJDK.net", "You're not running Java 8!", JOptionPane.INFORMATION_MESSAGE);
System.out.println("Please downgrade to Java 8 to avoid problems! (AdoptOpenJDK.net)");
}
} catch (Exception ignored) {}
}
public static void playSound(byte[] buffer, int offset, int length, int level, int delay) {
new SoundPlayer(new ByteArrayInputStream(buffer, offset, length), level, delay);
}
public static void setSoundVolume(int config) {
SoundPlayer.setVolume(config);
}
public static String getParameter(String s) {
if (Signlink.mainapp instanceof java.applet.Applet) {
return ((java.applet.Applet) Signlink.mainapp).getParameter(s);
}
return "";
}
public static void showDocument(Object caller, String s) {
try {
if (caller instanceof java.applet.Applet) {
java.applet.Applet a = (java.applet.Applet) caller;
java.applet.AppletContext ctx = a.getAppletContext();
if (ctx != null && caller instanceof Game) {
ctx.showDocument(new URL(((Game) caller).getCodeBase(), "loaderror_" + s + ".html"));
}
}
} catch (Exception ignored) {}
}
// Midi support for Signlink
public static Sequencer music = null;
public static Synthesizer synthesizer = null;
public static Sequence sequence = null;
public static synchronized void playSignlinkMidi(String location, int midiVolume) {
stopSignlinkMidi();
File midiFile = new File(location);
try {
sequence = MidiSystem.getSequence(midiFile);
music = MidiSystem.getSequencer();
music.open();
music.setSequence(sequence);
} catch (Exception e) {
System.err.println("Problem loading MIDI file.");
e.printStackTrace();
return;
}
if (music instanceof Synthesizer) {
synthesizer = (Synthesizer) music;
} else {
try {
synthesizer = MidiSystem.getSynthesizer();
synthesizer.open();
if (synthesizer.getDefaultSoundbank() == null) {
music.getTransmitter().setReceiver(MidiSystem.getReceiver());
} else {
music.getTransmitter().setReceiver(synthesizer.getReceiver());
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
music.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
music.start();
setSignlinkVolume(midiVolume);
}
public static boolean setSignlinkVolume(int midiVolume) {
if (synthesizer == null) {
return false;
}
int CHANGE_VOLUME = 7;
if (synthesizer.getDefaultSoundbank() == null) {
try (javax.sound.midi.Receiver receiver = MidiSystem.getReceiver()) {
ShortMessage volumeMessage = new ShortMessage();
for (int i = 0; i < 16; i++) {
volumeMessage.setMessage(ShortMessage.CONTROL_CHANGE, i, CHANGE_VOLUME, midiVolume);
receiver.send(volumeMessage, -1);
volumeMessage.setMessage(ShortMessage.CONTROL_CHANGE, i, 39, midiVolume);
receiver.send(volumeMessage, -1);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
} else {
try {
MidiChannel[] channels = synthesizer.getChannels();
for (int c = 0; channels != null && c < channels.length; c++) {
channels[c].controlChange(CHANGE_VOLUME, midiVolume);
channels[c].controlChange(39, midiVolume);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
return true;
}
public static synchronized void stopSignlinkMidi() {
if (music != null) {
try {
if (music.isRunning()) {
music.stop();
}
music.close();
} catch (Exception ignored) {}
music = null;
}
if (synthesizer != null) {
try {
synthesizer.close();
} catch (Exception ignored) {}
synthesizer = null;
}
sequence = null;
}
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; }
}
@@ -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<ClientPlugin> plugins = new ArrayList<>();
public final List<ClientScript> scripts = new ArrayList<>();
public final List<String> 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<JarEntry> 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());
}
}
}
File diff suppressed because it is too large. Load diff
@@ -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;
}
}
}
@@ -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<PluginConfigItem> getConfigItems() {
List<PluginConfigItem> 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;
}
}
@@ -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;
}
}
@@ -0,0 +1,578 @@
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
final int layerBytes = size * size * 4;
for (int texId = 0; texId < 50; texId++) {
buildCacheTextureLayer(texId, rgbField, heightField, cutoutField);
writeLayerToBuffers(texId, texId * layerBytes, 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, matId * layerBytes, rgbField, heightField, cutoutField, get(matId).normalStrength, diffuseBuf, normalBuf);
}
((Buffer) diffuseBuf).position(0);
((Buffer) normalBuf).position(0);
}
/**
* Populates a single 128x128 RGBA8 diffuse+heightfield and Sobel normal+specular layer at offset 0.
* Useful on memory-constrained platforms (e.g., Android) to stream layers via glTexSubImage3D.
*/
public static void populateSingleLayer(int layerId, ByteBuffer diffuseLayerBuf, ByteBuffer normalLayerBuf) {
final int layerPixels = TEX_SIZE * TEX_SIZE;
float[] heightField = new float[layerPixels];
int[] rgbField = new int[layerPixels];
boolean[] cutoutField = new boolean[layerPixels];
if (layerId < 50) {
buildCacheTextureLayer(layerId, rgbField, heightField, cutoutField);
} else {
buildProceduralHdLayer(layerId, rgbField, heightField, cutoutField);
}
writeLayerToBuffers(layerId, 0, rgbField, heightField, cutoutField, get(layerId).normalStrength, diffuseLayerBuf, normalLayerBuf);
((Buffer) diffuseLayerBuf).position(0);
((Buffer) normalLayerBuf).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 baseOffset, int[] rgbField, float[] heightField, boolean[] cutoutField,
float normalStrength, ByteBuffer diffuseBuf, ByteBuffer normalBuf) {
final int size = TEX_SIZE;
final int mask = size - 1;
((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);
}
}
@@ -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++;
}
}
File diff suppressed because it is too large. Load diff
@@ -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 {
}
+1 -83
View File
@@ -13,90 +13,8 @@ public final class Main {
public static void main(String[] args) {
try {
// Process client arguments to connect to
for (int i = 0; i < args.length; i++) {
switch(args[i]) {
case "-dev" :
case "-local":
case "-offline":
ClientSettings.SERVER_IP = "localhost";
ClientSettings.CHECK_CRC = false;
break;
case "-no-crc":
case "-no-cache-crc":
ClientSettings.CHECK_CRC = false;
break;
case "-qol":
case "-fixes":
ClientSettings.CUSTOM_SETTINGS_TAB = true;
ClientSettings.BILINEAR_MINIMAP_FILTERING = true;
ClientSettings.FIX_TRANSPARENCY_OVERFLOW = true;
ClientSettings.FULL_512PX_VIEWPORT = true;
ClientSettings.CONTROL_KEY_ZOOMING = true;
break;
case "-no-nav":
case "-disable-nav":
ClientSettings.SHOW_NAVBAR = false;
break;
case"-no-snow":
case"-hide-snow":
case"-disable-snow":
ClientSettings.SNOW_FLOOR_ENABLED = false;
ClientSettings.SNOW_FLOOR_FORCE_ENABLED = false;
ClientSettings.SNOW_OVERLAY_FORCE_ENABLED = false;
ClientSettings.SNOW_OVERLAY_ENABLED = false;
break;
case"-no-roofs":
case"-hide-roofs":
case"-disable-roofs":
ClientSettings.HIDE_ROOFS = true;
break;
case"-show-zoom":
ClientSettings.SHOW_ZOOM_LEVEL_MESSAGES = true;
break;
case"-screenshots":
case"-enable-screenshots":
ClientSettings.SCREENSHOTS_ENABLED = true;
break;
case"-auto-screenshots":
case"-enable-auto-screenshots":
ClientSettings.AUTOMATIC_SCREENSHOTS_ENABLED = true;
break;
}
if (args[i].startsWith("-") && (i + 1) < args.length && !args[i + 1].startsWith("-")) {
switch(args[i]) {
case "-s":
case "-server":
case "-ip":
ClientSettings.SERVER_IP = args[++i];
break;
}
}
}
Game game = new Game();
// Process other arguments
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("-") && (i + 1) < args.length && !args[i + 1].startsWith("-")) {
switch(args[i]) {
case "-u":
case "-user":
case "-username":
game.myUsername = args[++i];
break;
case "-p":
case "-pass":
case "-password":
game.myPassword = args[++i];
break;
case "-w":
case "-world":
ClientSettings.SERVER_WORLD = Integer.parseInt(args[++i]);
break;
}
}
}
ClientArgs.apply(args, game);
Game.nodeID = 10;
Game.portOff = 0;
@@ -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);
}
}
+100 -27
View File
@@ -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;
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 <= 50 || k2 >= distance) {
}
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];
@@ -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;
}
}
@@ -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 {
}
@@ -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 {
}
@@ -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;
@@ -210,6 +210,14 @@ public final class OnDemandFetcher extends OnDemandFetcherParent implements Runn
public void disable() {
running = false;
try {
if (socket != null) {
socket.close();
}
} catch (Exception ignored) {}
socket = null;
inputStream = null;
outputStream = null;
}
public void method554(boolean flag) {
@@ -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 +
'}';
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,344 @@
/**
* 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};
}
/**
* Projects world coordinate to screen (viewport) coordinate as a 2-element List [x, y], or null if off-screen.
*/
public java.util.List<Integer> worldToScreenList(int worldX, int worldY, int heightOffset) {
int[] pos = worldToScreen(worldX, worldY, heightOffset);
if (pos == null) return null;
java.util.List<Integer> list = new java.util.ArrayList<>(2);
list.add(pos[0]);
list.add(pos[1]);
return list;
}
/**
* 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 pre-computed ground item tile batches in compiled Java, avoiding per-frame
* script loop and reflection overhead (critical for TeaVM/Web performance).
*/
@SuppressWarnings("unchecked")
public void drawTileLabelBatches(java.util.List<?> tiles, int boxOpacity, int textOpacity) {
if (tiles == null || tiles.isEmpty()) return;
for (int t = 0; t < tiles.size(); t++) {
Object tileObj = tiles.get(t);
if (!(tileObj instanceof java.util.Map)) continue;
java.util.Map<Object, Object> tile = (java.util.Map<Object, Object>) tileObj;
int tileX = toIntValue(tile.get("x"), 0);
int tileY = toIntValue(tile.get("y"), 0);
Object beamFlag = tile.get("hasBeam");
if (beamFlag instanceof Boolean && ((Boolean) beamFlag).booleanValue()) {
drawLootbeam(tileX, tileY, toIntValue(tile.get("beamColor"), 0xffffff));
}
int baseX;
int baseY;
if (game != null) {
int[] pos = worldToScreen(tileX, tileY, 20);
if (pos == null) continue;
baseX = pos[0];
baseY = pos[1];
} else {
java.util.List<Integer> screen = worldToScreenList(tileX, tileY, 20);
if (screen == null || screen.size() < 2) continue;
baseX = screen.get(0);
baseY = screen.get(1);
}
Object itemsObj = tile.get("items");
if (!(itemsObj instanceof java.util.List)) continue;
java.util.List<?> itemsOnTile = (java.util.List<?>) itemsObj;
for (int rowIdx = 0; rowIdx < itemsOnTile.size(); rowIdx++) {
Object itemObj = itemsOnTile.get(rowIdx);
if (!(itemObj instanceof java.util.Map)) continue;
java.util.Map<Object, Object> item = (java.util.Map<Object, Object>) itemObj;
int rowY = baseY - (rowIdx * 14);
int color = toIntValue(item.get("color"), 0xffffff);
int borderColor = toIntValue(item.get("borderColor"), -1);
Object labelObj = item.get("label");
String label = labelObj != null ? labelObj.toString() : "";
int textW = toIntValue(item.get("textW"), -1);
if (textW < 0) {
textW = getTextWidth(label);
item.put("textW", textW);
}
int halfW = textW / 2;
int boxX = baseX - halfW - 3;
int boxY = rowY - 11;
int boxW = textW + 6;
int boxH = 13;
if (boxOpacity > 0) {
fillRect(boxX, boxY, boxW, boxH, 0x000000, boxOpacity);
}
if (borderColor != -1) {
drawRect(boxX, boxY, boxW, boxH, borderColor);
}
drawCenteredString(label, baseX, rowY - 1, color, textOpacity);
}
}
}
private static int toIntValue(Object val, int fallback) {
if (val instanceof Number) {
return ((Number) val).intValue();
}
return fallback;
}
/**
* Renders a list of world {x, y} path tiles as step markers on screen.
*/
public void drawPathOverlay(java.util.List<int[]> 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);
}
}
}
@@ -0,0 +1,863 @@
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<ClientPlugin> plugins = new ArrayList<>();
private final List<ClientScript> scripts = new ArrayList<>();
private final List<String> lastLoadErrors = new ArrayList<>();
private final Set<String> reportedPluginErrors = new HashSet<>();
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<ClientPlugin> getPlugins() {
return Collections.unmodifiableList(plugins);
}
public static boolean isScriptsAvailable() {
return ClientSettings.SERVER_WORLD == 1;
}
public List<ClientScript> getScripts() {
if (!isScriptsAvailable()) {
return Collections.emptyList();
}
return Collections.unmodifiableList(scripts);
}
public List<ClientScript> getAllRegisteredScripts() {
return Collections.unmodifiableList(scripts);
}
public ClientScript getActiveScript() {
return activeScript;
}
// =========================================================================
// Registration & Loading
// =========================================================================
private void registerBuiltIns() {
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);
}
applyConfigToPlugin(plugin, true);
}
private void applyConfigToPlugin(ClientPlugin plugin, boolean startIfEnabled) {
String key = "plugin." + plugin.getName().replace(' ', '_') + ".enabled";
boolean wasEnabled = plugin.isEnabled();
boolean enabled = Boolean.parseBoolean(configProps.getProperty(key, String.valueOf(plugin.isEnabledByDefault())));
plugin.setEnabled(enabled);
for (PluginConfigItem item : plugin.getConfigItems()) {
String propKey = "config." + plugin.getName().replace(' ', '_') + "." + item.getKey();
if (configProps.containsKey(propKey)) {
applyConfigValue(plugin, item, configProps.getProperty(propKey));
}
}
if (enabled && (!wasEnabled || startIfEnabled)) {
try {
plugin.onStart(context);
} catch (Throwable t) {
System.err.println("Error starting plugin " + plugin.getName() + ": " + t.getMessage());
}
} else if (!enabled && wasEnabled) {
try {
plugin.onStop();
} catch (Throwable ignored) {}
}
}
public synchronized void reloadStorage() {
configProps.clear();
loadConfig();
for (int i = 0; i < plugins.size(); i++) {
ClientPlugin p = plugins.get(i);
if (!(p instanceof ScriptInterpreter.InterpretedPlugin)) {
applyConfigToPlugin(p, false);
}
}
reloadExternal();
}
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<String> 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() {
reportedPluginErrors.clear();
// Stop active external scripts/plugins first
if (activeScript != null) {
stopScript(activeScript);
}
Iterator<ClientPlugin> 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<ClientScript> 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;
}
// Seed web localStorage config on first boot so the Storage editor sees plugin_config.ini
saveConfig();
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) {
reportPluginError(p, "onGameTick", t);
}
}
}
// 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<MenuEntry> 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) {
reportPluginError(p, "onPreMenuRender", t);
}
}
}
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) {
reportPluginError(p, "onRenderOverlay", t);
}
}
}
if (isScriptsAvailable() && activeScript != null && activeScript.isRunning()) {
try {
activeScript.onRenderOverlay(graphics);
} catch (Throwable t) {
System.err.println("Script " + activeScript.getName() + " overlay error: " + t.getMessage());
}
}
}
private void reportPluginError(ClientPlugin p, String phase, Throwable t) {
String msg = t.getMessage() != null ? t.getMessage() : t.getClass().getSimpleName();
System.err.println("Plugin " + p.getName() + " " + phase + " error: " + msg);
String key = p.getName() + ":" + phase;
if (reportedPluginErrors.add(key) && context != null && context.isLoggedIn()) {
context.sendClientMessage("@red@[Plugin Error] " + p.getName() + " (" + phase + "): " + msg);
}
}
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<String> 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;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,500 @@
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 final String REPO_COMMIT_API_URL =
"https://api.github.com/repos/" + PLUGIN_REPO_SLUG + "/commits/" + PLUGIN_REPO_BRANCH;
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<RepoEntry> 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<RepoEntry> 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<RepoEntry> 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;
return;
}
}
} catch (Throwable ignored) {
}
// Browser fallback: GitHub REST API commits endpoint supports CORS without preflight
try {
String json = httpGetRaw(REPO_COMMIT_API_URL + "?t=" + System.currentTimeMillis());
int shaKey = json.indexOf("\"sha\"");
if (shaKey != -1) {
int q1 = json.indexOf('"', shaKey + 5);
int q2 = q1 != -1 ? json.indexOf('"', q1 + 1) : -1;
if (q1 != -1 && q2 - q1 - 1 == 40) {
String candidate = json.substring(q1 + 1, q2);
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<RepoEntry> parseIndexJson(String json) {
List<RepoEntry> 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<String, String> 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<String, String> parseFlatJsonObject(String body) {
Map<String, String> 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();
}
}
+148 -27
View File
@@ -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;
@@ -19,16 +19,39 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
private int mouseWheelY = 0;
public static boolean removeShiftDropOnMenuOpen;
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 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();
@@ -242,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);
}
@@ -258,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) {
@@ -385,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
@@ -397,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();
}
@@ -408,8 +439,18 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
int i = mouseevent.getX();
int j = mouseevent.getY();
idleTime = 0;
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;
@@ -462,9 +503,17 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
return;
}
idleTime = 0;
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) {
}
@@ -474,27 +523,35 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
int i = mouseevent.getX();
int j = mouseevent.getY();
idleTime = 0;
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) {}
@Override
public void keyPressed(KeyEvent keyevent) {
idleTime = 0;
int i = keyevent.getKeyCode();
int j = keyevent.getKeyChar();
switch (keyevent.getKeyCode())
{
case KeyEvent.VK_SHIFT:
shiftDown = true;
break;
case KeyEvent.VK_CONTROL:
ctrlDown = true;
break;
}
@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());
}
public void handleMouseWheel(int notches, boolean isControlDown) {}
public void handleKeyPressed(int i, int j, boolean isCtrl, boolean isShift) {
idleTime = 0;
if (isShift) shiftDown = true;
if (isCtrl) ctrlDown = true;
if (j < 30) {
j = 0;
}
@@ -543,12 +600,17 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
if (j > 0 && j < 128) {
keyArray[j] = 1;
}
if (j > 4) {
if (j > 4 || ((j == 1 || j == 2) && PluginPanelUI.isSearchFocused())) {
charQueue[writeIndex] = j;
writeIndex = writeIndex + 1 & 0x7f;
}
}
@Override
public void keyPressed(KeyEvent keyevent) {
handleKeyPressed(keyevent.getKeyCode(), keyevent.getKeyChar(), keyevent.isControlDown(), keyevent.isShiftDown());
}
@Override
public final void keyReleased(KeyEvent keyevent) {
idleTime = 0;
@@ -676,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;
}
@@ -698,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);
@@ -739,12 +860,12 @@ public class RSApplet extends Applet implements Runnable, MouseListener, MouseWh
int myWidth;
int myHeight;
Graphics graphics;
RSImageProducer fullGameScreen;
public RSImageProducer fullGameScreen;
RSFrame gameFrame;
private boolean shouldClearScreen;
boolean awtFocus;
int idleTime;
int clickMode2;
public int clickMode2;
public int mouseX;
public int mouseY;
private int clickMode1;
@@ -0,0 +1,17 @@
/**
* Platform-independent RGB/ARGB color constants for DrawingArea and RS2 rendering.
*/
public final class RSColors {
public static final int WHITE = 0xffffff;
public static final int BLACK = 0x000000;
public static final int YELLOW = 0xffff00;
public static final int GREEN = 0x00ff00;
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() {}
}
+8 -1
View File
@@ -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();
@@ -13,6 +13,9 @@ import java.awt.image.ImageProducer;
final class RSImageProducer implements ImageProducer, ImageObserver {
public static final int[] masterScreenBuffer = new int[765 * 503];
public static final Object masterBufferLock = new Object();
public RSImageProducer(int i, int j, Component component) {
anInt316 = i;
anInt317 = j;
@@ -34,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);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,84 @@
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Lightweight file + stdout logger for script lifecycle, status transitions, and game actions.
* Writes to &lt;cacheDir&gt;/logs/scripts.log with 1 MB rotation.
*/
public final class ScriptLogger {
private static final long MAX_LOG_BYTES = 1024L * 1024L;
private static final SimpleDateFormat TIME_FMT = new SimpleDateFormat("HH:mm:ss.SSS");
private static volatile boolean enabled = true;
private static File logFileOverride = null;
private ScriptLogger() {
}
public static void setEnabled(boolean value) {
enabled = value;
}
public static boolean isEnabled() {
return enabled;
}
public static void setLogFileOverride(File file) {
logFileOverride = file;
}
public static File getLogFile() {
if (logFileOverride != null) {
return logFileOverride;
}
try {
String base = Signlink.findcachedir();
if (base != null && !base.isEmpty()) {
return new File(new File(base, "logs"), "scripts.log");
}
} catch (Throwable ignored) {
}
return null;
}
public static synchronized void log(String scriptName, String message) {
if (!enabled || message == null) return;
String name = (scriptName != null && !scriptName.isEmpty()) ? scriptName : "Script";
String ts;
synchronized (TIME_FMT) {
ts = TIME_FMT.format(new Date());
}
String line = "[" + ts + "] [" + name + "] " + message;
System.out.println("[ScriptLog] " + line);
File logFile = getLogFile();
if (logFile == null) return;
try {
File parent = logFile.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
if (logFile.exists() && logFile.length() > MAX_LOG_BYTES) {
File backup = new File(parent, logFile.getName() + ".1");
if (backup.exists()) backup.delete();
logFile.renameTo(backup);
}
try (PrintWriter out = new PrintWriter(new FileWriter(logFile, true))) {
out.println(line);
}
} catch (IOException ignored) {
}
}
public static void logActiveAction(String actionMessage) {
PluginManager pm = PluginManager.get();
if (pm == null) return;
ClientScript active = pm.getActiveScript();
if (active == null || !active.isRunning()) return;
log(active.getName(), "ACTION: " + actionMessage);
}
}
+153
View File
@@ -0,0 +1,153 @@
/**
* Semantic Versioning 2.0.0 parser, comparator, and constraint matcher.
* Supports formats like "1.2.3", "v1.2.3", "1.2" (normalized to 1.2.0),
* and pre-release/build suffixes ("1.2.3-alpha.1+001").
*/
public final class SemVer implements Comparable<SemVer> {
public final int major;
public final int minor;
public final int patch;
public final String preRelease;
public SemVer(int major, int minor, int patch, String preRelease) {
this.major = Math.max(0, major);
this.minor = Math.max(0, minor);
this.patch = Math.max(0, patch);
this.preRelease = (preRelease != null && !preRelease.isEmpty()) ? preRelease : "";
}
public SemVer(int major, int minor, int patch) {
this(major, minor, patch, "");
}
public static SemVer parse(String raw) {
if (raw == null) return new SemVer(0, 0, 0);
String s = raw.trim();
if (s.startsWith("v") || s.startsWith("V")) {
s = s.substring(1).trim();
}
int plusIdx = s.indexOf('+');
if (plusIdx >= 0) {
s = s.substring(0, plusIdx);
}
String pre = "";
int dashIdx = s.indexOf('-');
if (dashIdx >= 0) {
pre = s.substring(dashIdx + 1).trim();
s = s.substring(0, dashIdx);
}
String[] parts = s.split("\\.");
int maj = parts.length > 0 ? parseIntSafe(parts[0]) : 0;
int min = parts.length > 1 ? parseIntSafe(parts[1]) : 0;
int pat = parts.length > 2 ? parseIntSafe(parts[2]) : 0;
return new SemVer(maj, min, pat, pre);
}
private static int parseIntSafe(String part) {
try {
return Integer.parseInt(part.trim());
} catch (NumberFormatException e) {
return 0;
}
}
public boolean isNewerThan(SemVer other) {
return other == null || compareTo(other) > 0;
}
public boolean satisfies(String constraint) {
if (constraint == null || constraint.trim().isEmpty()) return true;
String c = constraint.trim();
if (c.startsWith(">=")) {
return compareTo(parse(c.substring(2))) >= 0;
}
if (c.startsWith("<=")) {
return compareTo(parse(c.substring(2))) <= 0;
}
if (c.startsWith(">")) {
return compareTo(parse(c.substring(1))) > 0;
}
if (c.startsWith("<")) {
return compareTo(parse(c.substring(1))) < 0;
}
if (c.startsWith("^")) {
SemVer base = parse(c.substring(1));
if (compareTo(base) < 0) return false;
if (base.major > 0) {
return compareTo(new SemVer(base.major + 1, 0, 0)) < 0;
}
if (base.minor > 0) {
return compareTo(new SemVer(0, base.minor + 1, 0)) < 0;
}
return compareTo(new SemVer(0, 0, base.patch + 1)) < 0;
}
if (c.startsWith("~")) {
SemVer base = parse(c.substring(1));
return compareTo(base) >= 0
&& compareTo(new SemVer(base.major, base.minor + 1, 0)) < 0;
}
if (c.startsWith("=")) {
return compareTo(parse(c.substring(1))) == 0;
}
return compareTo(parse(c)) == 0;
}
@Override
public int compareTo(SemVer other) {
if (other == null) return 1;
if (this.major != other.major) return Integer.compare(this.major, other.major);
if (this.minor != other.minor) return Integer.compare(this.minor, other.minor);
if (this.patch != other.patch) return Integer.compare(this.patch, other.patch);
boolean thisPre = !this.preRelease.isEmpty();
boolean otherPre = !other.preRelease.isEmpty();
if (!thisPre && !otherPre) return 0;
if (!thisPre) return 1;
if (!otherPre) return -1;
String[] a = this.preRelease.split("\\.");
String[] b = other.preRelease.split("\\.");
int len = Math.min(a.length, b.length);
for (int i = 0; i < len; i++) {
boolean aNum = isNumeric(a[i]);
boolean bNum = isNumeric(b[i]);
if (aNum && bNum) {
int cmp = Integer.compare(Integer.parseInt(a[i]), Integer.parseInt(b[i]));
if (cmp != 0) return cmp;
} else if (aNum != bNum) {
return aNum ? -1 : 1;
} else {
int cmp = a[i].compareTo(b[i]);
if (cmp != 0) return cmp;
}
}
return Integer.compare(a.length, b.length);
}
private static boolean isNumeric(String s) {
if (s.isEmpty()) return false;
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) return false;
}
return true;
}
@Override
public String toString() {
String base = major + "." + minor + "." + patch;
return preRelease.isEmpty() ? base : (base + "-" + preRelease);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof SemVer)) return false;
return compareTo((SemVer) obj) == 0;
}
@Override
public int hashCode() {
return toString().hashCode();
}
}
+65 -142
View File
@@ -1,4 +1,3 @@
import java.applet.Applet;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
@@ -8,31 +7,16 @@ import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Synthesizer;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public final class Signlink implements Runnable {
public static final void startpriv(InetAddress inetaddress) {
threadliveid = (int) (Math.random() * 99999999D);
if (active) {
try {
Thread.sleep(500L);
Thread.sleep(100L);
} catch (Exception _ex) {
}
active = false;
close();
}
socketreq = 0;
threadreq = null;
@@ -40,6 +24,7 @@ public final class Signlink implements Runnable {
saveReq = null;
urlreq = null;
socketip = inetaddress;
reporterror = true;
Thread thread = new Thread(new Signlink());
thread.setDaemon(true);
thread.start();
@@ -51,6 +36,32 @@ public final class Signlink implements Runnable {
}
}
public static synchronized void close() {
active = false;
threadliveid = 0;
reporterror = true;
try {
if (cache_dat != null) {
cache_dat.close();
cache_dat = null;
}
} catch (Exception ignored) {}
for (int j = 0; j < 5; j++) {
try {
if (cache_idx[j] != null) {
cache_idx[j].close();
cache_idx[j] = null;
}
} catch (Exception ignored) {}
}
try {
if (socket != null) {
socket.close();
socket = null;
}
} catch (Exception ignored) {}
}
enum Position {
LEFT, RIGHT, NORMAL
};
@@ -60,15 +71,22 @@ public final class Signlink implements Runnable {
@Override
public void run() {
active = true;
String s = findcachedir();
try {
if (cache_dat != null) {
try { cache_dat.close(); } catch (Exception ignored) {}
}
cache_dat = new RandomAccessFile(s + "main_file_cache.dat", "rw");
for (int j = 0; j < 5; j++)
for (int j = 0; j < 5; j++) {
if (cache_idx[j] != null) {
try { cache_idx[j].close(); } catch (Exception ignored) {}
}
cache_idx[j] = new RandomAccessFile(s + "main_file_cache.idx" + j, "rw");
}
} catch (Exception exception) {
exception.printStackTrace();
}
active = true;
for (int i = threadliveid; threadliveid == i;) {
if (socketreq != 0) {
try {
@@ -101,60 +119,19 @@ public final class Signlink implements Runnable {
if (waveplay) {
String wave = s + saveReq;
waveplay = false;
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(new File(wave));
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
return;
} catch (IOException e1) {
e1.printStackTrace();
return;
}
AudioFormat format = audioInputStream.getFormat();
SourceDataLine auline = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
} catch (LineUnavailableException e) {
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
if (auline.isControlSupported(FloatControl.Type.PAN)) {
FloatControl pan = (FloatControl) auline.getControl(FloatControl.Type.PAN);
if (curPosition == Position.RIGHT)
pan.setValue(1.0f);
else if (curPosition == Position.LEFT)
pan.setValue(-1.0f);
}
auline.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
try {
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0,
abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
auline.drain();
auline.close();
if (ClientSettings.ANDROID) {
AndroidHooks.playSound(savebuf, 0, savelen, wavevol, 0);
} else {
DesktopHooks.playSound(savebuf, 0, savelen, wavevol, 0);
}
}
if (play) {
midi = s + saveReq;
try {
if (music != null) {
music.stop();
music.close();
if (ClientSettings.ANDROID) {
AndroidHooks.stopMidi();
} else {
DesktopHooks.stopSignlinkMidi();
}
playMidi(midi);
} catch (Exception ex) {
@@ -166,7 +143,7 @@ public final class Signlink implements Runnable {
} else if (urlreq != null) {
try {
System.out.println("urlstream");
urlstream = new DataInputStream((new URL(mainapp.getCodeBase(), urlreq)).openStream());
urlstream = new DataInputStream((new URL(new URL("http://127.0.0.1"), urlreq)).openStream());
} catch (Exception _ex) {
urlstream = null;
}
@@ -184,39 +161,11 @@ public final class Signlink implements Runnable {
* @param location
*/
private void playMidi(String location) {
music = null;
synthesizer = null;
sequence = null;
File midiFile = new File(location);
try {
sequence = MidiSystem.getSequence(midiFile);
music = MidiSystem.getSequencer();
music.open();
music.setSequence(sequence);
} catch (Exception e) {
System.err.println("Problem loading MIDI file.");
e.printStackTrace();
return;
}
if (music instanceof Synthesizer) {
synthesizer = (Synthesizer) music;
if (ClientSettings.ANDROID) {
AndroidHooks.playMidi(location, midiVolume);
} else {
try {
synthesizer = MidiSystem.getSynthesizer();
synthesizer.open();
if (synthesizer.getDefaultSoundbank() == null) {
music.getTransmitter().setReceiver(MidiSystem.getReceiver());
} else {
music.getTransmitter().setReceiver(synthesizer.getReceiver());
DesktopHooks.playSignlinkMidi(location, midiVolume);
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
music.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
music.start();
setVolume(midiVolume);
}
/**
@@ -224,36 +173,12 @@ public final class Signlink implements Runnable {
* @param value
*/
public static boolean setVolume(int value) {
if (synthesizer == null) {
return false;
}
int CHANGE_VOLUME = 7;
midiVolume = value;
if (synthesizer.getDefaultSoundbank() == null) {
try {
ShortMessage volumeMessage = new ShortMessage();
for (int i = 0; i < 16; i++) {
volumeMessage.setMessage(ShortMessage.CONTROL_CHANGE, i, CHANGE_VOLUME, midiVolume);
volumeMessage.setMessage(ShortMessage.CONTROL_CHANGE, i, 39, midiVolume);
MidiSystem.getReceiver().send(volumeMessage, -1);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
if (ClientSettings.ANDROID) {
return AndroidHooks.setMidiVolume(value);
} else {
try {
MidiChannel[] channels = synthesizer.getChannels();
for (int c = 0; channels != null && c < channels.length; c++) {
channels[c].controlChange(CHANGE_VOLUME, midiVolume);
channels[c].controlChange(39, midiVolume);
return DesktopHooks.setSignlinkVolume(value);
}
} catch (Exception e){
e.printStackTrace();
return false;
}
}
return true;
}
/**
@@ -261,23 +186,21 @@ public final class Signlink implements Runnable {
* Stops the current midi playing.
*/
public static void fadeOut() {
if (music == null) {
return;
}
int volume = midiVolume;
if (music.isRunning()) {
for (int index = midiVolume; index > 0 && volume > 0; index--) {
volume--;
setVolume(volume);
}
if (ClientSettings.ANDROID) {
AndroidHooks.stopMidi();
} else {
DesktopHooks.stopSignlinkMidi();
}
}
public static Sequencer music = null;
public static Sequence sequence = null;
public static Synthesizer synthesizer = null;
public static Object music = null;
public static Object sequence = null;
public static Object synthesizer = null;
public static String findcachedir() {
if (ClientSettings.ANDROID) {
return AndroidHooks.getCacheDir();
}
String path = System.getProperty("user.home") + "/.2006Scape_file_system/";
File file = new File(path);
if (!file.exists()) {
@@ -389,7 +312,7 @@ public final class Signlink implements Runnable {
public static RandomAccessFile cache_dat = null;
public static final RandomAccessFile[] cache_idx = new RandomAccessFile[5];
public static boolean sunjava;
public static Applet mainapp = null;
public static Object mainapp = null;
private static boolean active;
private static int threadliveid;
private static InetAddress socketip;
@@ -403,7 +326,7 @@ public final class Signlink implements Runnable {
private static DataInputStream urlstream = null;
public static boolean reporterror = true;
public static String errorname = "";
public static Midi midii = new Midi();
public static Object midii = null;
private static int savelen;
private static String saveReq = null;
private static byte savebuf[] = null;
@@ -0,0 +1,32 @@
/**
* SkillConstants.java
* @author Andrew (Mr Extremez)
*/
public enum SkillConstants {
ATTACK(true), DEFENCE(true), STRENGTH(true), HITPOINTS(true), RANGE(true),
PRAYER(true), MAGIC(true), COOKING(true), WOODCUTTING(true), FLETCHING(true),
FISHING(true), FIREMAKING(true), CRAFTING(true), SMITHING(true), MINING(true),
HERBLORE(true), AGILITY(true), THIEVING(true), SLAYER(true), FARMING(true), RUNECRAFTING(true);
private SkillConstants(boolean skillEnabled) {
this.skillEnabled = skillEnabled;
}
private boolean skillEnabled;
public static boolean getEnabled(int id) {
for (final SkillConstants skillConstants : SkillConstants.values()) {
if (skillConstants.ordinal() == id && skillConstants.skillEnabled == true) {
return true;
}
}
return false;
}
public static String getName(SkillConstants skillConstants) {
return "The " + skillConstants.name().toLowerCase() + " skill is currently disabled";
}
}
@@ -0,0 +1,48 @@
/**
* Skill ID constants for the 2006Scape Client Plugin & Script API.
*/
public final class SkillID {
public static final int ATTACK = 0;
public static final int DEFENCE = 1;
public static final int STRENGTH = 2;
public static final int HITPOINTS = 3;
public static final int RANGED = 4;
public static final int PRAYER = 5;
public static final int MAGIC = 6;
public static final int COOKING = 7;
public static final int WOODCUTTING = 8;
public static final int FLETCHING = 9;
public static final int FISHING = 10;
public static final int FIREMAKING = 11;
public static final int CRAFTING = 12;
public static final int SMITHING = 13;
public static final int MINING = 14;
public static final int HERBLORE = 15;
public static final int AGILITY = 16;
public static final int THIEVING = 17;
public static final int SLAYER = 18;
public static final int FARMING = 19;
public static final int RUNECRAFTING = 20;
public static final String[] SKILL_NAMES = {
"Attack", "Defence", "Strength", "Hitpoints", "Ranged",
"Prayer", "Magic", "Cooking", "Woodcutting", "Fletching",
"Fishing", "Firemaking", "Crafting", "Smithing", "Mining",
"Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecrafting"
};
public static String getSkillName(int id) {
if (id >= 0 && id < SKILL_NAMES.length) {
return SKILL_NAMES[id];
}
return "Unknown";
}
public static boolean isCombatSkill(int id) {
return id == ATTACK || id == DEFENCE || id == STRENGTH
|| id == HITPOINTS || id == RANGED || id == MAGIC;
}
private SkillID() {}
}
+58 -45
View File
@@ -1,77 +1,91 @@
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import javax.sound.sampled.*;
public class SoundPlayer implements Runnable {
private AudioInputStream stream;
private DataLine.Info info;
private SourceDataLine sound;
private static final int BUFFER_SIZE = 4096;
private static final ExecutorService SOUND_EXECUTOR = Executors.newFixedThreadPool(4, new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
Thread t = new Thread(runnable, "SoundEffectPlayer");
t.setDaemon(true);
return t;
}
});
private InputStream soundStream;
private Thread player;
private int delay;
private int soundLevel;
public static int volume;
private final InputStream soundStream;
private final int delay;
private final int soundLevel;
public static volatile int volume;
/**
* Initializes the sound player.
* Initializes and schedules the sound player.
* @param stream
* @param level
* @param delay
*/
public SoundPlayer(InputStream stream, int level, int delay) {
if (level == 0 || volume == 4 || level - volume <= 0) {
if (stream == null || level <= 0 || volume >= 4 || level - volume <= 0) {
if (stream != null) {
try {
stream.close();
} catch (IOException ignored) {
}
}
this.soundStream = null;
this.soundLevel = 0;
this.delay = 0;
return;
}
this.soundStream = stream;
this.soundLevel = level;
this.delay = delay;
player = new Thread(this);
player.start();
SOUND_EXECUTOR.execute(this);
}
/**
* Plays the sound.
*/
@Override
public void run() {
try {
stream = AudioSystem.getAudioInputStream(soundStream);
if (soundStream == null) {
return;
}
try (AudioInputStream stream = AudioSystem.getAudioInputStream(soundStream)) {
AudioFormat format = stream.getFormat();
info = new DataLine.Info(SourceDataLine.class, format);
sound = (SourceDataLine) AudioSystem.getLine(info);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try (SourceDataLine sound = (SourceDataLine) AudioSystem.getLine(info)) {
sound.open(format);
FloatControl volume = (FloatControl) sound.getControl(FloatControl.Type.MASTER_GAIN);
volume.setValue(getDecibels(soundLevel - getVolume()));
if (sound.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
FloatControl gainControl = (FloatControl) sound.getControl(FloatControl.Type.MASTER_GAIN);
float db = getDecibels(soundLevel - getVolume());
db = Math.max(gainControl.getMinimum(), Math.min(gainControl.getMaximum(), db));
gainControl.setValue(db);
}
if (delay > 0) {
Thread.sleep(delay);
}
sound.start();
int nBytesRead = 0;
int EXTERNAL_BUFFER_SIZE = 524288;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
try {
while (nBytesRead != -1) {
nBytesRead = stream.read(abData, 0, abData.length);
if (nBytesRead >= 0) {
sound.write(abData, 0, nBytesRead);
byte[] buffer = new byte[BUFFER_SIZE];
int nBytesRead;
while ((nBytesRead = stream.read(buffer, 0, buffer.length)) != -1) {
if (nBytesRead > 0) {
sound.write(buffer, 0, nBytesRead);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
sound.drain();
sound.close();
}
stream.close();
player.interrupt();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
player.interrupt();
e.printStackTrace();
}
}
@@ -97,19 +111,18 @@ public class SoundPlayer implements Runnable {
* @return
*/
public float getDecibels(int level) {
if (level <= 0) {
return -1.0f;
}
switch (level) {
case 0: // 4 in player options
return (float) -1.0f;
case 1: // 3
return (float) -5.0f;
case 1: // 3 in player options
return -5.0f;
case 2: // 2
return (float) -10.0f;
return -10.0f;
case 3: // 1
return (float) -15.0f;
case 4: // off
return (float) -100.0f;
default:
return (float) 0.0f;
return -15.0f;
default: // 4+ (muted/off)
return -100.0f;
}
}
}
+11 -27
View File
@@ -2,12 +2,6 @@
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
import java.awt.Component;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.image.PixelGrabber;
public final class Sprite extends DrawingArea {
public Sprite(int i, int j) {
@@ -17,25 +11,15 @@ public final class Sprite extends DrawingArea {
anInt1442 = anInt1443 = 0;
}
public Sprite(byte abyte0[], Component component) {
try {
// Image image =
// Toolkit.getDefaultToolkit().getImage(signlink.findcachedir()+"mopar.jpg");
Image image = Toolkit.getDefaultToolkit().createImage(abyte0);
MediaTracker mediatracker = new MediaTracker(component);
mediatracker.addImage(image, 0);
mediatracker.waitForAll();
width = image.getWidth(component);
height = image.getHeight(component);
trimWidth = width;
trimHeight = height;
anInt1442 = 0;
anInt1443 = 0;
pixels = new int[width * height];
PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
pixelgrabber.grabPixels();
} catch (Exception _ex) {
System.out.println("Error converting jpg");
public Sprite(byte abyte0[]) {
this(abyte0, null);
}
public Sprite(byte abyte0[], Object component) {
if (ClientSettings.ANDROID) {
AndroidHooks.decodeImage(this, abyte0);
} else {
DesktopHooks.decodeImage(this, abyte0, component);
}
}
@@ -533,8 +517,8 @@ public final class Sprite extends DrawingArea {
public int pixels[];
public int width;
public int height;
private int anInt1442;
private int anInt1443;
int anInt1442;
int anInt1443;
public int trimWidth;
public int trimHeight;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -83,6 +83,40 @@ public final class TextDrawingArea extends DrawingArea {
textLeft(i, s, k, l - method384(s) / 2);
}
public void textLeftAlpha(int _color, String s, int _y, int _x, int alpha, boolean _shadow) {
if (s == null) {
return;
}
_y -= anInt1497;
int shadowAlpha = (alpha * 192) / 256;
for (int i1 = 0; i1 < s.length(); i1++) {
if (s.charAt(i1) == '@' && i1 + 4 < s.length() && s.charAt(i1 + 4) == '@') {
int j1 = getColorByName(s.substring(i1 + 1, i1 + 4));
if (j1 != -1) {
_color = j1;
}
i1 += 4;
} else {
char c = s.charAt(i1);
if (c != ' ') {
if (_shadow && shadowAlpha > 0) {
method394(shadowAlpha, _x + anIntArray1494[c] + 1, aByteArrayArray1491[c], anIntArray1492[c], _y + anIntArray1495[c] + 1, anIntArray1493[c], 0);
}
if (alpha >= 255) {
method392(aByteArrayArray1491[c], _x + anIntArray1494[c], _y + anIntArray1495[c], anIntArray1492[c], anIntArray1493[c], _color);
} else {
method394(alpha, _x + anIntArray1494[c], aByteArrayArray1491[c], anIntArray1492[c], _y + anIntArray1495[c], anIntArray1493[c], _color);
}
}
_x += anIntArray1496[c];
}
}
}
public void textCenterAlpha(int _color, String s, int _y, int _x, int alpha, boolean _shadow) {
textLeftAlpha(_color, s, _y, _x - getTextWidth(s) / 2, alpha, _shadow);
}
public void textCenterShadow(int _color, int _x, String s, int _y, boolean _shadow) {
textLeftShadow(_shadow, _x - getTextWidth(s) / 2, _color, s, _y);
}
@@ -309,6 +343,9 @@ public final class TextDrawingArea extends DrawingArea {
}
private void method392(byte abyte0[], int i, int j, int k, int l, int i1) {
if (i1 == 0) {
i1 = 1;
}
int j1 = i + j * DrawingArea.width;
int k1 = DrawingArea.width - k;
int l1 = 0;
@@ -385,6 +422,9 @@ public final class TextDrawingArea extends DrawingArea {
}
private void method394(int i, int j, byte abyte0[], int k, int l, int i1, int j1) {
if (j1 == 0) {
j1 = 1;
}
int k1 = j + l * DrawingArea.width;
int l1 = DrawingArea.width - k;
int i2 = 0;
+5 -5
View File
@@ -111,7 +111,7 @@ final class Texture extends DrawingArea {
anIntArrayArray1479[i] = null;
}
private static int[] method371(int i) {
public static int[] method371(int i) {
anIntArray1480[i] = anInt1481++;
if (anIntArrayArray1479[i] != null) {
return anIntArrayArray1479[i];
@@ -2094,18 +2094,18 @@ final class Texture extends DrawingArea {
private static int[] anIntArray1476 = new int[50];
private static int anInt1477;
private static int[][] anIntArrayArray1478;
private static int[][] anIntArrayArray1479 = new int[50][];
public static int[][] anIntArrayArray1479 = new int[50][];
public static int anIntArray1480[] = new int[50];
public static int anInt1481;
public static int anIntArray1482[] = new int[0x10000];
private static int[][] anIntArrayArray1483 = new int[50][];
public static int[][] anIntArrayArray1483 = new int[50][];
static {
anIntArray1468 = new int[512];
anIntArray1468 = new int[2048];
anIntArray1469 = new int[2048];
anIntArray1470 = new int[2048];
anIntArray1471 = new int[2048];
for (int i = 1; i < 512; i++) {
for (int i = 1; i < 2048; i++) {
anIntArray1468[i] = 32768 / i;
}
@@ -2,7 +2,7 @@
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
final class WorldController {
public final class WorldController {
public static int drawDistance = 25;
public WorldController(int ai[][][]) {
@@ -132,6 +132,7 @@ final class WorldController {
}
if (l == 1) {
Class43 class43_1 = new Class43(k3, l3, i4, j4, j1, l4, k1 == l1 && k1 == i2 && k1 == j2);
class43_1.isOverlay = true;
for (int j5 = i; j5 >= 0; j5--) {
if (groundArray[j5][j][k] == null) {
groundArray[j5][j][k] = new Ground(j5, j, k);
@@ -142,6 +143,7 @@ final class WorldController {
return;
}
Class40 class40 = new Class40(k, k3, j3, i2, j1, i4, i1, k2, k4, i3, j2, l1, k1, l, j4, l3, l2, j, l4);
class40.plane = i;
for (int k5 = i; k5 >= 0; k5--) {
if (groundArray[k5][j][k] == null) {
groundArray[k5][j][k] = new Ground(k5, j, k);
@@ -218,6 +220,7 @@ final class WorldController {
}
groundArray[k1][l][k].obj1 = object1;
HD317Pipeline.invalidateStaticChunk(l, k);
}
public void method283(int i, int j, int k, int i1, int j1, int k1, Animable class30_sub2_sub4, int l1, byte byte0, int i2, int j2) {
@@ -240,6 +243,7 @@ final class WorldController {
}
groundArray[i1][l1][j].obj2 = class26;
HD317Pipeline.invalidateStaticChunk(l1, j);
}
public boolean method284(int i, byte byte0, int j, int k, Animable class30_sub2_sub4, int l, int i1, int j1, int k1, int l1) {
@@ -248,7 +252,11 @@ final class WorldController {
} else {
int i2 = l1 * 128 + 64 * l;
int j2 = k1 * 128 + 64 * k;
return method287(i1, l1, k1, l, k, i2, j2, j, class30_sub2_sub4, j1, false, i, byte0);
boolean added = method287(i1, l1, k1, l, k, i2, j2, j, class30_sub2_sub4, j1, false, i, byte0);
if (added) {
HD317Pipeline.invalidateStaticChunk(l1, k1);
}
return added;
}
}
@@ -410,6 +418,7 @@ final class WorldController {
}
if (class30_sub3 != null) {
class30_sub3.obj1 = null;
HD317Pipeline.invalidateStaticChunk(i, k);
}
}
@@ -417,6 +426,7 @@ final class WorldController {
Ground class30_sub3 = groundArray[k][l][j];
if (class30_sub3 != null) {
class30_sub3.obj2 = null;
HD317Pipeline.invalidateStaticChunk(l, j);
}
}
@@ -429,6 +439,7 @@ final class WorldController {
Object5 class28 = class30_sub3.obj5Array[j1];
if ((class28.uid >> 29 & 3) == 2 && class28.anInt523 == k && class28.anInt525 == l) {
method289(class28);
HD317Pipeline.invalidateStaticChunk(k, l);
return;
}
}
@@ -441,6 +452,7 @@ final class WorldController {
return;
}
class30_sub3.obj3 = null;
HD317Pipeline.invalidateStaticChunk(k, j);
}
public void method295(int i, int j, int k) {
@@ -794,7 +806,7 @@ final class WorldController {
anInt497 = k;
anInt498 = l;
anInt493 = k / 2;
anInt494 = l / 2;
anInt494 = (ClientSettings.ANDROID && ClientSettings.RESIZABLE && k < l) ? (int) (l * 0.38f) : (l / 2);
boolean aflag[][][][] = new boolean[9][32][256][256];
for (int i1 = 128; i1 <= 384; i1 += 32) {
for (int j1 = 0; j1 < 2048; j1 += 64) {
@@ -905,19 +917,24 @@ final class WorldController {
anInt453 = i / 128;
anInt454 = j / 128;
anInt447 = i1;
anInt449 = anInt453 - drawDistance;
hdMaxPlane = Math.max(0, Math.min(3, i1));
boolean hdGpu = ClientSettings.HD_317 && HD317Pipeline.isGpuActive();
int maxDist = hdGpu ? 60 : 38;
effectiveDrawDist = (ClientSettings.ANDROID || hdGpu)
? Math.min(maxDist, drawDistance + (hdCamDistToPlayer >> 7) + 10) : drawDistance;
anInt449 = anInt453 - effectiveDrawDist;
if (anInt449 < 0) {
anInt449 = 0;
}
anInt451 = anInt454 - drawDistance;
anInt451 = anInt454 - effectiveDrawDist;
if (anInt451 < 0) {
anInt451 = 0;
}
anInt450 = anInt453 + drawDistance;
anInt450 = anInt453 + effectiveDrawDist;
if (anInt450 > anInt438) {
anInt450 = anInt438;
}
anInt452 = anInt454 + drawDistance;
anInt452 = anInt454 + effectiveDrawDist;
if (anInt452 > anInt439) {
anInt452 = anInt439;
}
@@ -929,7 +946,7 @@ final class WorldController {
for (int k2 = anInt451; k2 < anInt452; k2++) {
Ground class30_sub3 = aclass30_sub3[i2][k2];
if (class30_sub3 != null) {
if (class30_sub3.anInt1321 > i1 || !aBooleanArrayArray492[i2 - anInt453 + drawDistance][k2 - anInt454 + drawDistance] && anIntArrayArrayArray440[k1][i2][k2] - l < 50) {
if (class30_sub3.anInt1321 > i1 || (!ClientSettings.ANDROID && !ClientSettings.RESIZABLE && !hdGpu && !aBooleanArrayArray492[i2 - anInt453 + drawDistance][k2 - anInt454 + drawDistance]) && anIntArrayArrayArray440[k1][i2][k2] - l < 50) {
class30_sub3.aBoolean1322 = false;
class30_sub3.aBoolean1323 = false;
class30_sub3.anInt1325 = 0;
@@ -946,13 +963,60 @@ final class WorldController {
}
if (hdGpu) {
int cx = anInt453;
int cz = anInt454;
int maxR = effectiveDrawDist;
if (cx >= anInt449 && cx < anInt450 && cz >= anInt451 && cz < anInt452) {
renderHdTileColumn(cx, cz);
}
for (int r = 1; r <= maxR; r++) {
int minX = Math.max(anInt449, cx - r);
int maxX = Math.min(anInt450 - 1, cx + r);
int minZ = Math.max(anInt451, cz - r);
int maxZ = Math.min(anInt452 - 1, cz + r);
int northZ = cz - r;
if (northZ >= anInt451 && northZ < anInt452) {
for (int tx = minX; tx <= maxX; tx++) {
renderHdTileColumn(tx, northZ);
}
}
int southZ = cz + r;
if (southZ >= anInt451 && southZ < anInt452) {
for (int tx = minX; tx <= maxX; tx++) {
renderHdTileColumn(tx, southZ);
}
}
int innerMinZ = Math.max(minZ, cz - r + 1);
int innerMaxZ = Math.min(maxZ, cz + r - 1);
int westX = cx - r;
if (westX >= anInt449 && westX < anInt450) {
for (int tz = innerMinZ; tz <= innerMaxZ; tz++) {
renderHdTileColumn(westX, tz);
}
}
int eastX = cx + r;
if (eastX >= anInt449 && eastX < anInt450) {
for (int tz = innerMinZ; tz <= innerMaxZ; tz++) {
renderHdTileColumn(eastX, tz);
}
}
}
aBoolean467 = false;
return;
}
int loopDist = (ClientSettings.HD_317 && HD317Pipeline.isGpuActive())
? Math.max(drawDistance, 104) : (ClientSettings.ANDROID ? effectiveDrawDist : drawDistance);
for (int l1 = anInt442; l1 < anInt437; l1++) {
Ground aclass30_sub3_1[][] = groundArray[l1];
for (int l2 = -drawDistance; l2 <= 0; l2++) {
for (int l2 = -loopDist; l2 <= 0; l2++) {
int i3 = anInt453 + l2;
int k3 = anInt453 - l2;
if (i3 >= anInt449 || k3 < anInt450) {
for (int i4 = -drawDistance; i4 <= 0; i4++) {
for (int i4 = -loopDist; i4 <= 0; i4++) {
int k4 = anInt454 + i4;
int i5 = anInt454 - i4;
if (i3 >= anInt449) {
@@ -996,11 +1060,11 @@ final class WorldController {
for (int j2 = anInt442; j2 < anInt437; j2++) {
Ground aclass30_sub3_2[][] = groundArray[j2];
for (int j3 = -drawDistance; j3 <= 0; j3++) {
for (int j3 = -loopDist; j3 <= 0; j3++) {
int l3 = anInt453 + j3;
int j4 = anInt453 - j3;
if (l3 >= anInt449 || j4 < anInt450) {
for (int l4 = -drawDistance; l4 <= 0; l4++) {
for (int l4 = -loopDist; l4 <= 0; l4++) {
int j5 = anInt454 + l4;
int k5 = anInt454 - l4;
if (l3 >= anInt449) {
@@ -1045,6 +1109,157 @@ final class WorldController {
aBoolean467 = false;
}
public static int hdPlayerTileX = 52;
public static int hdPlayerTileZ = 52;
public static int hdCamDistToPlayer = 1200;
public static int effectiveDrawDist = 25;
public static int hdMaxPlane = 3;
private boolean isHdTileInFrustum(int tx, int tz) {
int wx = (tx << 7) + 64 - anInt455;
int wz = (tz << 7) + 64 - anInt457;
int wy = anIntArrayArrayArray440[0][tx][tz] - anInt456;
int cz0 = wz * anInt461 - wx * anInt460 >> 16;
int cz = wy * anInt458 + cz0 * anInt459 >> 16;
// Keep a 10-tile margin behind camera for nearby shadow casters and large multi-tile objects
if (cz < -1280) {
return false;
}
int maxCamDepth = (drawDistance + (hdCamDistToPlayer >> 7) + 16) * 256;
if (cz > maxCamDepth) {
return false;
}
int cxCam = wz * anInt460 + wx * anInt461 >> 16;
if (cz > 256 && Math.abs(cxCam) > cz + 768) {
return false;
}
return true;
}
private void renderHdTileColumn(int tx, int tz) {
if (!isHdTileInFrustum(tx, tz)) {
return;
}
for (int plane = anInt442; plane < anInt437; plane++) {
Ground ground = groundArray[plane][tx][tz];
if (ground != null && ground.aBoolean1322) {
renderHdTile(ground);
}
}
}
private void renderHdAnimable(Animable animable, int orientation, int relX, int relY, int relZ, int uid) {
boolean prevAnimated = HD317Pipeline.drawingAnimatedObj;
HD317Pipeline.drawingAnimatedObj = !(animable instanceof Model);
try {
animable.method443(orientation, anInt458, anInt459, anInt460, anInt461, relX, relY, relZ, uid);
} finally {
HD317Pipeline.drawingAnimatedObj = prevAnimated;
}
}
private void renderHdTile(Ground class30_sub3_1) {
int i = class30_sub3_1.anInt1308;
int j = class30_sub3_1.anInt1309;
int l = class30_sub3_1.anInt1310;
class30_sub3_1.aBoolean1322 = false;
class30_sub3_1.aBoolean1323 = false;
if (class30_sub3_1.aClass30_Sub3_1329 != null) {
Ground class30_sub3_7 = class30_sub3_1.aClass30_Sub3_1329;
HD317Pipeline.drawingPlane = 0;
if (class30_sub3_7.aClass43_1311 != null) {
method315(class30_sub3_7.aClass43_1311, 0, anInt458, anInt459, anInt460, anInt461, i, j);
} else if (class30_sub3_7.aClass40_1312 != null) {
method316(i, anInt458, anInt460, class30_sub3_7.aClass40_1312, anInt459, j, anInt461);
}
Object1 class10 = class30_sub3_7.obj1;
if (class10 != null) {
HD317Pipeline.drawingWall = true;
if (class10.aClass30_Sub2_Sub4_278 != null) {
renderHdAnimable(class10.aClass30_Sub2_Sub4_278, 0, class10.anInt274 - anInt455, class10.anInt273 - anInt456, class10.anInt275 - anInt457, class10.uid);
}
if (class10.aClass30_Sub2_Sub4_279 != null) {
renderHdAnimable(class10.aClass30_Sub2_Sub4_279, 0, class10.anInt274 - anInt455, class10.anInt273 - anInt456, class10.anInt275 - anInt457, class10.uid);
}
HD317Pipeline.drawingWall = false;
}
for (int i2 = 0; i2 < class30_sub3_7.anInt1317; i2++) {
Object5 class28 = class30_sub3_7.obj5Array[i2];
if (class28 != null && class28.aClass30_Sub2_Sub4_521 != null) {
renderHdAnimable(class28.aClass30_Sub2_Sub4_521, class28.anInt522, class28.anInt519 - anInt455, class28.anInt518 - anInt456, class28.anInt520 - anInt457, class28.uid);
}
}
}
HD317Pipeline.drawingPlane = l;
if (class30_sub3_1.aClass43_1311 != null) {
method315(class30_sub3_1.aClass43_1311, l, anInt458, anInt459, anInt460, anInt461, i, j);
} else if (class30_sub3_1.aClass40_1312 != null) {
method316(i, anInt458, anInt460, class30_sub3_1.aClass40_1312, anInt459, j, anInt461);
}
Object1 class10_3 = class30_sub3_1.obj1;
if (class10_3 != null) {
HD317Pipeline.drawingWall = true;
if (class10_3.aClass30_Sub2_Sub4_278 != null) {
renderHdAnimable(class10_3.aClass30_Sub2_Sub4_278, 0, class10_3.anInt274 - anInt455, class10_3.anInt273 - anInt456, class10_3.anInt275 - anInt457, class10_3.uid);
}
if (class10_3.aClass30_Sub2_Sub4_279 != null) {
renderHdAnimable(class10_3.aClass30_Sub2_Sub4_279, 0, class10_3.anInt274 - anInt455, class10_3.anInt273 - anInt456, class10_3.anInt275 - anInt457, class10_3.uid);
}
HD317Pipeline.drawingWall = false;
}
Object2 class26 = class30_sub3_1.obj2;
if (class26 != null && class26.aClass30_Sub2_Sub4_504 != null) {
if ((class26.anInt502 & 0x300) != 0) {
int j4 = class26.anInt500 - anInt455;
int l5 = class26.anInt499 - anInt456;
int k6 = class26.anInt501 - anInt457;
int i8 = class26.anInt503;
if ((class26.anInt502 & 0x100) != 0) {
int i11 = j4 + anIntArray463[i8];
int k11 = k6 + anIntArray464[i8];
renderHdAnimable(class26.aClass30_Sub2_Sub4_504, i8 * 512 + 256, i11, l5, k11, class26.uid);
}
if ((class26.anInt502 & 0x200) != 0) {
int j11 = j4 + anIntArray465[i8];
int l11 = k6 + anIntArray466[i8];
renderHdAnimable(class26.aClass30_Sub2_Sub4_504, i8 * 512 + 1280 & 0x7ff, j11, l5, l11, class26.uid);
}
} else {
renderHdAnimable(class26.aClass30_Sub2_Sub4_504, class26.anInt503, class26.anInt500 - anInt455, class26.anInt499 - anInt456, class26.anInt501 - anInt457, class26.uid);
}
}
Object3 class49 = class30_sub3_1.obj3;
if (class49 != null && class49.aClass30_Sub2_Sub4_814 != null) {
renderHdAnimable(class49.aClass30_Sub2_Sub4_814, 0, class49.anInt812 - anInt455, class49.anInt811 - anInt456, class49.anInt813 - anInt457, class49.uid);
}
Object4 object4 = class30_sub3_1.obj4;
if (object4 != null) {
if (object4.aClass30_Sub2_Sub4_49 != null) {
object4.aClass30_Sub2_Sub4_49.method443(0, anInt458, anInt459, anInt460, anInt461, object4.anInt46 - anInt455, object4.anInt45 - anInt456 - object4.anInt52, object4.anInt47 - anInt457, object4.uid);
}
if (object4.aClass30_Sub2_Sub4_50 != null) {
object4.aClass30_Sub2_Sub4_50.method443(0, anInt458, anInt459, anInt460, anInt461, object4.anInt46 - anInt455, object4.anInt45 - anInt456 - object4.anInt52, object4.anInt47 - anInt457, object4.uid);
}
if (object4.aClass30_Sub2_Sub4_48 != null) {
object4.aClass30_Sub2_Sub4_48.method443(0, anInt458, anInt459, anInt460, anInt461, object4.anInt46 - anInt455, object4.anInt45 - anInt456 - object4.anInt52, object4.anInt47 - anInt457, object4.uid);
}
}
for (int k2 = 0; k2 < class30_sub3_1.anInt1317; k2++) {
Object5 class28 = class30_sub3_1.obj5Array[k2];
if (class28 != null && class28.anInt528 != anInt448 && class28.aClass30_Sub2_Sub4_521 != null) {
class28.anInt528 = anInt448;
renderHdAnimable(class28.aClass30_Sub2_Sub4_521, class28.anInt522, class28.anInt519 - anInt455, class28.anInt518 - anInt456, class28.anInt520 - anInt457, class28.uid);
}
}
}
private void method314(Ground class30_sub3, boolean flag) {
aClass19_477.insertHead(class30_sub3);
do {
@@ -1118,6 +1333,7 @@ final class WorldController {
}
boolean flag1 = false;
HD317Pipeline.drawingPlane = l;
if (class30_sub3_1.aClass43_1311 != null) {
if (!method320(l, i, j)) {
flag1 = true;
@@ -1495,6 +1711,8 @@ final class WorldController {
}
private void method315(Class43 class43, int i, int j, int k, int l, int i1, int j1, int k1) {
if (ClientSettings.HD_317 && HD317Pipeline.isGpuActive()) {
if (aBoolean467) {
int l1;
int i2 = l1 = (j1 << 7) - anInt455;
int j2;
@@ -1513,34 +1731,107 @@ final class WorldController {
l4 = l3 * k - k2 * j >> 16;
k2 = l3 * j + k2 * k >> 16;
l3 = l4;
if (k2 < 50) {
return;
}
l4 = j2 * l + i3 * i1 >> 16;
j2 = j2 * i1 - i3 * l >> 16;
i3 = l4;
l4 = i4 * k - j2 * j >> 16;
j2 = i4 * j + j2 * k >> 16;
i4 = l4;
if (j2 < 50) {
return;
}
l4 = k3 * l + l2 * i1 >> 16;
k3 = k3 * i1 - l2 * l >> 16;
l2 = l4;
l4 = j4 * k - k3 * j >> 16;
k3 = j4 * j + k3 * k >> 16;
j4 = l4;
if (k3 < 50) {
return;
}
l4 = j3 * l + l1 * i1 >> 16;
j3 = j3 * i1 - l1 * l >> 16;
l1 = l4;
l4 = k4 * k - j3 * j >> 16;
j3 = k4 * j + j3 * k >> 16;
k4 = l4;
if (j3 < 50) {
if (k2 >= 50 && j2 >= 50 && k3 >= 50 && j3 >= 50) {
int i5 = Texture.textureInt1 + (i2 << 9) / k2;
int j5 = Texture.textureInt2 + (l3 << 9) / k2;
int k5 = Texture.textureInt1 + (i3 << 9) / j2;
int l5 = Texture.textureInt2 + (i4 << 9) / j2;
int i6 = Texture.textureInt1 + (l2 << 9) / k3;
int j6 = Texture.textureInt2 + (j4 << 9) / k3;
int k6 = Texture.textureInt1 + (l1 << 9) / j3;
int l6 = Texture.textureInt2 + (k4 << 9) / j3;
if ((i6 - k6) * (l5 - l6) - (j6 - l6) * (k5 - k6) > 0 && method318(anInt468, anInt469, j6, l6, l5, i6, k6, k5)) {
anInt470 = j1;
anInt471 = k1;
}
if ((i5 - k5) * (l6 - l5) - (j5 - l5) * (k6 - k5) > 0 && method318(anInt468, anInt469, j5, l5, l6, i5, k5, k6)) {
anInt470 = j1;
anInt471 = k1;
}
}
}
HD317Pipeline.drawSimpleTile(class43, i, j1, k1);
return;
}
int l1;
int i2 = l1 = (j1 << 7) - anInt455;
int j2;
int k2 = j2 = (k1 << 7) - anInt457;
int l2;
int i3 = l2 = i2 + 128;
int j3;
int k3 = j3 = k2 + 128;
int l3 = anIntArrayArrayArray440[i][j1][k1] - anInt456;
int i4 = anIntArrayArrayArray440[i][j1 + 1][k1] - anInt456;
int j4 = anIntArrayArrayArray440[i][j1 + 1][k1 + 1] - anInt456;
int k4 = anIntArrayArrayArray440[i][j1][k1 + 1] - anInt456;
int l4 = k2 * l + i2 * i1 >> 16;
k2 = k2 * i1 - i2 * l >> 16;
i2 = l4;
l4 = l3 * k - k2 * j >> 16;
k2 = l3 * j + k2 * k >> 16;
l3 = l4;
l4 = j2 * l + i3 * i1 >> 16;
j2 = j2 * i1 - i3 * l >> 16;
i3 = l4;
l4 = i4 * k - j2 * j >> 16;
j2 = i4 * j + j2 * k >> 16;
i4 = l4;
l4 = k3 * l + l2 * i1 >> 16;
k3 = k3 * i1 - l2 * l >> 16;
l2 = l4;
l4 = j4 * k - k3 * j >> 16;
k3 = j4 * j + k3 * k >> 16;
j4 = l4;
l4 = j3 * l + l1 * i1 >> 16;
j3 = j3 * i1 - l1 * l >> 16;
l1 = l4;
l4 = k4 * k - j3 * j >> 16;
j3 = k4 * j + j3 * k >> 16;
k4 = l4;
if (k2 < 48 && j2 < 48 && k3 < 48 && j3 < 48) {
return;
}
if (k2 < 48 || j2 < 48 || k3 < 48 || j3 < 48) {
Texture.anInt1465 = 0;
int texId = class43.anInt720;
if (texId == -1) {
if (class43.anInt718 != 0xbc614e) {
emitClippedTileTriangle(l2, j4, k3, class43.anInt718, l1, k4, j3, class43.anInt719, i3, i4, j2, class43.anInt717, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
if (class43.anInt716 != 0xbc614e) {
emitClippedTileTriangle(i2, l3, k2, class43.anInt716, i3, i4, j2, class43.anInt717, l1, k4, j3, class43.anInt719, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
} else if (!lowMem) {
if (class43.aBoolean721) {
emitClippedTileTriangle(l2, j4, k3, class43.anInt718, l1, k4, j3, class43.anInt719, i3, i4, j2, class43.anInt717, texId, i2, i3, l1, l3, i4, k4, k2, j2, j3);
} else {
emitClippedTileTriangle(l2, j4, k3, class43.anInt718, l1, k4, j3, class43.anInt719, i3, i4, j2, class43.anInt717, texId, l2, l1, i3, j4, k4, i4, k3, j3, j2);
}
emitClippedTileTriangle(i2, l3, k2, class43.anInt716, i3, i4, j2, class43.anInt717, l1, k4, j3, class43.anInt719, texId, i2, i3, l1, l3, i4, k4, k2, j2, j3);
} else {
int i7 = anIntArray485[texId];
emitClippedTileTriangle(l2, j4, k3, method317(i7, class43.anInt718), l1, k4, j3, method317(i7, class43.anInt719), i3, i4, j2, method317(i7, class43.anInt717), -1, 0, 0, 0, 0, 0, 0, 0, 0, 0);
emitClippedTileTriangle(i2, l3, k2, method317(i7, class43.anInt716), i3, i4, j2, method317(i7, class43.anInt717), l1, k4, j3, method317(i7, class43.anInt719), -1, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
return;
}
int i5 = Texture.textureInt1 + (i2 << 9) / k2;
@@ -1552,7 +1843,7 @@ final class WorldController {
int k6 = Texture.textureInt1 + (l1 << 9) / j3;
int l6 = Texture.textureInt2 + (k4 << 9) / j3;
Texture.anInt1465 = 0;
if ((i6 - k6) * (l5 - l6) - (j6 - l6) * (k5 - k6) > 0) {
if ((long) (i6 - k6) * (l5 - l6) - (long) (j6 - l6) * (k5 - k6) > 0) {
Texture.aBoolean1462 = i6 < 0 || k6 < 0 || k5 < 0 || i6 > DrawingArea.centerX || k6 > DrawingArea.centerX || k5 > DrawingArea.centerX;
if (aBoolean467 && method318(anInt468, anInt469, j6, l6, l5, i6, k6, k5)) {
anInt470 = j1;
@@ -1573,7 +1864,7 @@ final class WorldController {
Texture.method374(j6, l6, l5, i6, k6, k5, method317(i7, class43.anInt718), method317(i7, class43.anInt719), method317(i7, class43.anInt717));
}
}
if ((i5 - k5) * (l6 - l5) - (j5 - l5) * (k6 - k5) > 0) {
if ((long) (i5 - k5) * (l6 - l5) - (long) (j5 - l5) * (k6 - k5) > 0) {
Texture.aBoolean1462 = i5 < 0 || k5 < 0 || k6 < 0 || i5 > DrawingArea.centerX || k5 > DrawingArea.centerX || k6 > DrawingArea.centerX;
if (aBoolean467 && method318(anInt468, anInt469, j5, l5, l6, i5, k5, k6)) {
anInt470 = j1;
@@ -1595,7 +1886,10 @@ final class WorldController {
}
private void method316(int i, int j, int k, Class40 class40, int l, int i1, int j1) {
if (ClientSettings.HD_317 && HD317Pipeline.isGpuActive()) {
if (aBoolean467) {
int k1 = class40.anIntArray673.length;
boolean allBehind = true;
for (int l1 = 0; l1 < k1; l1++) {
int i2 = class40.anIntArray673[l1] - anInt455;
int k2 = class40.anIntArray674[l1] - anInt456;
@@ -1606,17 +1900,102 @@ final class WorldController {
k3 = k2 * l - i3 * j >> 16;
i3 = k2 * j + i3 * l >> 16;
k2 = k3;
if (i3 < 50) {
if (i3 >= 50) {
allBehind = false;
Class40.anIntArray688[l1] = Texture.textureInt1 + (i2 << 9) / i3;
Class40.anIntArray689[l1] = Texture.textureInt2 + (k2 << 9) / i3;
} else {
Class40.anIntArray688[l1] = -5000;
Class40.anIntArray689[l1] = -5000;
}
}
if (!allBehind) {
k1 = class40.anIntArray679.length;
for (int j2 = 0; j2 < k1; j2++) {
int l2 = class40.anIntArray679[j2];
int j3 = class40.anIntArray680[j2];
int l3 = class40.anIntArray681[j2];
int i4 = Class40.anIntArray688[l2];
int j4 = Class40.anIntArray688[j3];
int k4 = Class40.anIntArray688[l3];
int l4 = Class40.anIntArray689[l2];
int i5 = Class40.anIntArray689[j3];
int j5 = Class40.anIntArray689[l3];
if (i4 != -5000 && j4 != -5000 && k4 != -5000) {
if ((i4 - j4) * (j5 - i5) - (l4 - i5) * (k4 - j4) > 0 && method318(anInt468, anInt469, l4, i5, j5, i4, j4, k4)) {
anInt470 = i;
anInt471 = i1;
}
}
}
}
}
HD317Pipeline.drawShapedTile(class40, class40.plane, i, i1);
return;
}
int k1 = class40.anIntArray673.length;
int[] vx = new int[k1];
int[] vy = new int[k1];
int[] vz = new int[k1];
boolean anyVisible = false;
boolean anyNear = false;
for (int l1 = 0; l1 < k1; l1++) {
int i2 = class40.anIntArray673[l1] - anInt455;
int k2 = class40.anIntArray674[l1] - anInt456;
int i3 = class40.anIntArray675[l1] - anInt457;
int k3 = i3 * k + i2 * j1 >> 16;
i3 = i3 * j1 - i2 * k >> 16;
i2 = k3;
k3 = k2 * l - i3 * j >> 16;
i3 = k2 * j + i3 * l >> 16;
k2 = k3;
vx[l1] = i2;
vy[l1] = k2;
vz[l1] = i3;
if (i3 >= 48) {
anyVisible = true;
} else {
anyNear = true;
}
if (class40.anIntArray682 != null) {
Class40.anIntArray690[l1] = i2;
Class40.anIntArray691[l1] = k2;
Class40.anIntArray692[l1] = i3;
}
if (i3 >= 48) {
Class40.anIntArray688[l1] = Texture.textureInt1 + (i2 << 9) / i3;
Class40.anIntArray689[l1] = Texture.textureInt2 + (k2 << 9) / i3;
}
}
if (!anyVisible) {
return;
}
if (anyNear) {
Texture.anInt1465 = 0;
int triCount = class40.anIntArray679.length;
for (int j2 = 0; j2 < triCount; j2++) {
int v0 = class40.anIntArray679[j2];
int v1 = class40.anIntArray680[j2];
int v2 = class40.anIntArray681[j2];
int texId = (class40.anIntArray682 != null) ? class40.anIntArray682[j2] : -1;
if (texId == -1) {
if (class40.anIntArray676[j2] != 0xbc614e) {
emitClippedTileTriangle(vx[v0], vy[v0], vz[v0], class40.anIntArray676[j2], vx[v1], vy[v1], vz[v1], class40.anIntArray677[j2], vx[v2], vy[v2], vz[v2], class40.anIntArray678[j2], -1, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
} else if (!lowMem) {
if (class40.aBoolean683) {
emitClippedTileTriangle(vx[v0], vy[v0], vz[v0], class40.anIntArray676[j2], vx[v1], vy[v1], vz[v1], class40.anIntArray677[j2], vx[v2], vy[v2], vz[v2], class40.anIntArray678[j2], texId, vx[0], vx[1], vx[3], vy[0], vy[1], vy[3], vz[0], vz[1], vz[3]);
} else {
emitClippedTileTriangle(vx[v0], vy[v0], vz[v0], class40.anIntArray676[j2], vx[v1], vy[v1], vz[v1], class40.anIntArray677[j2], vx[v2], vy[v2], vz[v2], class40.anIntArray678[j2], texId, vx[v0], vx[v1], vx[v2], vy[v0], vy[v1], vy[v2], vz[v0], vz[v1], vz[v2]);
}
} else {
int k5 = anIntArray485[texId];
emitClippedTileTriangle(vx[v0], vy[v0], vz[v0], method317(k5, class40.anIntArray676[j2]), vx[v1], vy[v1], vz[v1], method317(k5, class40.anIntArray677[j2]), vx[v2], vy[v2], vz[v2], method317(k5, class40.anIntArray678[j2]), -1, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
}
return;
}
Texture.anInt1465 = 0;
k1 = class40.anIntArray679.length;
@@ -1630,7 +2009,7 @@ final class WorldController {
int l4 = Class40.anIntArray689[l2];
int i5 = Class40.anIntArray689[j3];
int j5 = Class40.anIntArray689[l3];
if ((i4 - j4) * (j5 - i5) - (l4 - i5) * (k4 - j4) > 0) {
if ((long) (i4 - j4) * (j5 - i5) - (long) (l4 - i5) * (k4 - j4) > 0) {
Texture.aBoolean1462 = i4 < 0 || j4 < 0 || k4 < 0 || i4 > DrawingArea.centerX || j4 > DrawingArea.centerX || k4 > DrawingArea.centerX;
if (aBoolean467 && method318(anInt468, anInt469, l4, i5, j5, i4, j4, k4)) {
anInt470 = i;
@@ -1655,6 +2034,70 @@ final class WorldController {
}
private void emitClippedTileTriangle(
int x0, int y0, int z0, int c0,
int x1, int y1, int z1, int c1,
int x2, int y2, int z2, int c2,
int texId,
int tx0, int tx1, int tx2,
int ty0, int ty1, int ty2,
int tz0, int tz1, int tz2) {
final int NEAR_Z = 48;
int[] px = { x0, x1, x2 };
int[] py = { y0, y1, y2 };
int[] pz = { z0, z1, z2 };
int[] pc = { c0, c1, c2 };
int[] rx = new int[4];
int[] ry = new int[4];
int[] rz = new int[4];
int[] rc = new int[4];
int count = 0;
for (int i = 0; i < 3; i++) {
int j = (i + 1) % 3;
boolean inA = pz[i] >= NEAR_Z;
boolean inB = pz[j] >= NEAR_Z;
if (inA) {
rx[count] = px[i];
ry[count] = py[i];
rz[count] = pz[i];
rc[count] = pc[i];
count++;
}
if (inA != inB) {
int dz = pz[j] - pz[i];
rx[count] = px[i] + (int) (((long) (px[j] - px[i]) * (NEAR_Z - pz[i])) / dz);
ry[count] = py[i] + (int) (((long) (py[j] - py[i]) * (NEAR_Z - pz[i])) / dz);
rz[count] = NEAR_Z;
rc[count] = pc[i];
count++;
}
}
if (count < 3) return;
int[] sx = new int[count];
int[] sy = new int[count];
for (int i = 0; i < count; i++) {
sx[i] = Texture.textureInt1 + (rx[i] << 9) / rz[i];
sy[i] = Texture.textureInt2 + (ry[i] << 9) / rz[i];
}
for (int i = 1; i < count - 1; i++) {
int ax = sx[0], ay = sy[0], ac = rc[0];
int bx = sx[i], by = sy[i], bc = rc[i];
int cx = sx[i + 1], cy = sy[i + 1], cc = rc[i + 1];
if (ax < -16000 || ax > 16000 || bx < -16000 || bx > 16000 || cx < -16000 || cx > 16000
|| ay < -16000 || ay > 16000 || by < -16000 || by > 16000 || cy < -16000 || cy > 16000) {
continue;
}
if ((long) (ax - bx) * (cy - by) - (long) (ay - by) * (cx - bx) > 0) {
Texture.aBoolean1462 = ax < 0 || bx < 0 || cx < 0 || ax > DrawingArea.centerX || bx > DrawingArea.centerX || cx > DrawingArea.centerX;
if (texId == -1) {
Texture.method374(ay, by, cy, ax, bx, cx, ac, bc, cc);
} else {
Texture.method378(ay, by, cy, ax, bx, cx, ac, bc, cc, tx0, tx1, tx2, ty0, ty1, ty2, Math.max(NEAR_Z, tz0), Math.max(NEAR_Z, tz1), Math.max(NEAR_Z, tz2), texId);
}
}
}
}
private int method317(int j, int k) {
k = 127 - k;
k = k * (j & 0x7f) / 160;
@@ -1686,14 +2129,19 @@ final class WorldController {
}
private void method319() {
if (ClientSettings.HD_317 && HD317Pipeline.isGpuActive()) {
anInt475 = 0;
return;
}
int j = anIntArray473[anInt447];
Class47 aclass47[] = aClass47ArrayArray474[anInt447];
anInt475 = 0;
int maxGrid = ClientSettings.ANDROID ? (drawDistance * 2) : 50;
for (int k = 0; k < j; k++) {
Class47 class47 = aclass47[k];
if (class47.anInt791 == 1) {
int l = class47.anInt787 - anInt453 + drawDistance;
if (l < 0 || l > 50) {
if (l < 0 || l > maxGrid) {
continue;
}
int k1 = class47.anInt789 - anInt454 + drawDistance;
@@ -1701,12 +2149,12 @@ final class WorldController {
k1 = 0;
}
int j2 = class47.anInt790 - anInt454 + drawDistance;
if (j2 > 50) {
j2 = 50;
if (j2 > maxGrid) {
j2 = maxGrid;
}
boolean flag = false;
while (k1 <= j2) {
if (aBooleanArrayArray492[l][k1++]) {
if (ClientSettings.ANDROID || aBooleanArrayArray492[l][k1++]) {
flag = true;
break;
}
@@ -1733,7 +2181,7 @@ final class WorldController {
}
if (class47.anInt791 == 2) {
int i1 = class47.anInt789 - anInt454 + drawDistance;
if (i1 < 0 || i1 > 50) {
if (i1 < 0 || i1 > maxGrid) {
continue;
}
int l1 = class47.anInt787 - anInt453 + drawDistance;
@@ -1741,12 +2189,12 @@ final class WorldController {
l1 = 0;
}
int k2 = class47.anInt788 - anInt453 + drawDistance;
if (k2 > 50) {
k2 = 50;
if (k2 > maxGrid) {
k2 = maxGrid;
}
boolean flag1 = false;
while (l1 <= k2) {
if (aBooleanArrayArray492[l1++][i1]) {
if (ClientSettings.ANDROID || aBooleanArrayArray492[l1++][i1]) {
flag1 = true;
break;
}
@@ -1777,8 +2225,8 @@ final class WorldController {
i2 = 0;
}
int l2 = class47.anInt790 - anInt454 + drawDistance;
if (l2 > 50) {
l2 = 50;
if (l2 > maxGrid) {
l2 = maxGrid;
}
if (i2 <= l2) {
int i3 = class47.anInt787 - anInt453 + drawDistance;
@@ -1786,13 +2234,13 @@ final class WorldController {
i3 = 0;
}
int l3 = class47.anInt788 - anInt453 + drawDistance;
if (l3 > 50) {
l3 = 50;
if (l3 > maxGrid) {
l3 = maxGrid;
}
boolean flag2 = false;
label0 : for (int i4 = i3; i4 <= l3; i4++) {
for (int j4 = i2; j4 <= l2; j4++) {
if (!aBooleanArrayArray492[i4][j4]) {
if (!ClientSettings.ANDROID && !aBooleanArrayArray492[i4][j4]) {
continue;
}
flag2 = true;
@@ -2053,12 +2501,12 @@ final class WorldController {
private final int anInt437;
private final int anInt438;
private final int anInt439;
private final int[][][] anIntArrayArrayArray440;
private final Ground[][][] groundArray;
private int anInt442;
public final int[][][] anIntArrayArrayArray440;
public final Ground[][][] groundArray;
public int anInt442;
private int obj5CacheCurrPos;
private final Object5[] obj5Cache;
private final int[][][] anIntArrayArrayArray445;
public final int[][][] anIntArrayArrayArray445;
private static int anInt446;
private static int anInt447;
private static int anInt448;
@@ -2068,13 +2516,13 @@ final class WorldController {
private static int anInt452;
private static int anInt453;
private static int anInt454;
private static int anInt455;
private static int anInt456;
private static int anInt457;
private static int anInt458;
private static int anInt459;
private static int anInt460;
private static int anInt461;
public static int anInt455;
public static int anInt456;
public static int anInt457;
public static int anInt458;
public static int anInt459;
public static int anInt460;
public static int anInt461;
private static Object5[] aClass28Array462 = new Object5[100];
private static final int[] anIntArray463 = {53, -53, -53, 53};
private static final int[] anIntArray464 = {-53, -53, 53, 53};
@@ -0,0 +1,193 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Lightweight F2P overworld road/bridge graph for long-distance smart walking.
* Connects major towns, bridges, banks, and crossroads without crossing locked/paid gates.
*/
public final class WorldWebWalker {
private WorldWebWalker() {
}
public static final int[][] NODES = {
// Draynor & Port Sarim & Rimmington (0-7)
{3092, 3243}, // 0: Draynor Bank
{3080, 3250}, // 1: Draynor Market
{3108, 3295}, // 2: Draynor Crossroads
{3145, 3265}, // 3: Draynor-Lumbridge Road
{3065, 3275}, // 4: Draynor West Road
{3045, 3255}, // 5: Port Sarim North
{3028, 3217}, // 6: Port Sarim Docks
{3005, 3215}, // 7: Port Sarim West
// Rimmington & Falador (8-17)
{2965, 3225}, // 8: Rimmington North
{2957, 3214}, // 9: Rimmington Center
{3007, 3275}, // 10: Port Sarim-Falador Road
{3007, 3315}, // 11: Falador South Crossroads
{3007, 3328}, // 12: Falador South Gate
{3013, 3355}, // 13: Falador East Bank
{2965, 3380}, // 14: Falador Square
{2946, 3368}, // 15: Falador West Bank
{2965, 3405}, // 16: Falador North Gate
{2925, 3380}, // 17: Falador West Gate
// Taverley & Barbarian Village & Edgeville (18-24)
{2905, 3420}, // 18: Taverley Road
{2895, 3440}, // 19: Taverley Center
{3010, 3420}, // 20: Falador-Barbarian Road
{3085, 3355}, // 21: Draynor-Barbarian Road
{3080, 3420}, // 22: Barbarian Village
{3088, 3465}, // 23: Edgeville South
{3094, 3492}, // 24: Edgeville Bank
// Lumbridge (25-36)
{3185, 3245}, // 25: Lumbridge West Road
{3195, 3275}, // 26: Lumbridge Farm South
{3205, 3295}, // 27: Lumbridge Wheat North
{3222, 3218}, // 28: Lumbridge Castle
{3218, 3238}, // 29: Lumbridge North Gate
{3224, 3262}, // 30: Lumbridge Mid-West Road
{3238, 3288}, // 31: Lumbridge Chicken Coop Outside
{3229, 3226}, // 32: Lumbridge Bridge West
{3236, 3226}, // 33: Lumbridge Bridge East
{3250, 3255}, // 34: Lumbridge Cow Pasture South
{3250, 3267}, // 35: Lumbridge Cow Pasture Gate
{3218, 3190}, // 36: Lumbridge Swamp Road
// Al-Kharid via free northern pass (37-42)
{3240, 3305}, // 37: North of Lumbridge Coop
{3288, 3302}, // 38: Al-Kharid North Pass
{3302, 3275}, // 39: Al-Kharid North Entrance
{3300, 3240}, // 40: Al-Kharid Mine Road
{3293, 3200}, // 41: Al-Kharid East Road
{3270, 3167}, // 42: Al-Kharid Bank
// Varrock (43-52)
{3100, 3420}, // 43: Barbarian Bridge
{3145, 3420}, // 44: Varrock West Road
{3170, 3428}, // 45: Varrock West Gate
{3185, 3436}, // 46: Varrock West Bank
{3212, 3428}, // 47: Varrock Square
{3212, 3380}, // 48: Varrock South Gate
{3235, 3335}, // 49: Varrock South Road
{3253, 3420}, // 50: Varrock East Bank
{3273, 3428}, // 51: Varrock East Gate
{3285, 3370}, // 52: Varrock South-East Mine
{3254, 3322}, // 53: North of Cow Pasture / Fenced Field (east of River Lum)
{3292, 3335}, // 54: Al-Kharid - Varrock SE Mine Road
{3115, 3482}, // 55: Edgeville River East Bank
{3162, 3470}, // 56: Varrock NW / North of City Wall
{3155, 3295}, // 57: Fred's Farm / Windmill Road
{3145, 3215}, // 58: Draynor - Lumbridge Swamp Road
{3277, 3328}, // 59: Al-Kharid North-East Pass (above fenced field)
{3186, 3496}, // 60: Varrock Palace NW
{3215, 3508}, // 61: Varrock Palace North
{3244, 3503}, // 62: Varrock Palace NE
{3243, 3473}, // 63: Varrock East North Road
{3246, 3443} // 64: Varrock East Bank North Road
};
public static final int[][] EDGES = {
// Draynor / Port Sarim / Rimmington
{0, 1}, {0, 2}, {0, 3}, {0, 58}, {58, 36}, {1, 4}, {2, 3}, {2, 4}, {2, 57}, {57, 27},
{4, 5}, {5, 6}, {6, 7},
{7, 8}, {8, 9}, {5, 10}, {10, 11},
// Falador / Taverley
{11, 12}, {12, 13}, {13, 14}, {14, 15}, {14, 16}, {14, 17},
{17, 18}, {18, 19}, {16, 20}, {20, 22},
// Barbarian Village / Edgeville
{2, 21}, {21, 22}, {22, 23}, {23, 24}, {55, 56}, {56, 60}, {60, 61}, {61, 62}, {62, 63}, {63, 64}, {64, 50},
// Lumbridge
{3, 25}, {25, 26}, {25, 28}, {26, 27},
{28, 29}, {28, 32}, {28, 36}, {29, 30},
{32, 33}, {33, 34}, {34, 35}, {34, 31},
// Al-Kharid free northern pass
{31, 37}, {37, 53}, {53, 59}, {59, 38}, {38, 39}, {39, 40}, {40, 41}, {41, 42},
{38, 54}, {54, 52},
// Varrock
{22, 43}, {43, 44}, {44, 45}, {45, 46}, {46, 47},
{31, 49}, {49, 48}, {48, 47},
{47, 50}, {50, 51}, {51, 52}
};
/**
* Computes a shortest road-node route between (startX, startY) and (targetX, targetY).
*/
public static List<int[]> findRoute(PluginContext ctx, int startX, int startY, int targetX, int targetY) {
int n = NODES.length;
int startIdx = -1;
int bestReachDist = Integer.MAX_VALUE;
int fallbackIdx = -1;
int bestFallbackDist = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int d = Math.max(Math.abs(NODES[i][0] - startX), Math.abs(NODES[i][1] - startY));
if (ctx != null && d <= 50 && ctx.canReach(NODES[i][0], NODES[i][1], 52, false)) {
if (d < bestReachDist) {
bestReachDist = d;
startIdx = i;
}
}
if (d < bestFallbackDist) {
bestFallbackDist = d;
fallbackIdx = i;
}
}
if (startIdx == -1) {
if (bestFallbackDist > 80) return Collections.emptyList();
startIdx = fallbackIdx;
}
int endIdx = -1;
int bestEndDist = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int d = Math.max(Math.abs(NODES[i][0] - targetX), Math.abs(NODES[i][1] - targetY));
if (d < bestEndDist) {
bestEndDist = d;
endIdx = i;
}
}
if (endIdx == -1 || bestEndDist > 80 || startIdx == endIdx) {
return Collections.emptyList();
}
double[] dist = new double[n];
int[] prev = new int[n];
boolean[] used = new boolean[n];
Arrays.fill(dist, Double.MAX_VALUE);
Arrays.fill(prev, -1);
dist[startIdx] = 0;
for (int iter = 0; iter < n; iter++) {
int u = -1;
for (int i = 0; i < n; i++) {
if (!used[i] && (u == -1 || dist[i] < dist[u])) {
u = i;
}
}
if (u == -1 || dist[u] == Double.MAX_VALUE || u == endIdx) break;
used[u] = true;
for (int[] e : EDGES) {
int v = (e[0] == u) ? e[1] : (e[1] == u ? e[0] : -1);
if (v == -1 || used[v]) continue;
double w = Math.hypot(NODES[u][0] - NODES[v][0], NODES[u][1] - NODES[v][1]);
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
prev[v] = u;
}
}
}
if (prev[endIdx] == -1) return Collections.emptyList();
List<int[]> route = new ArrayList<>();
for (int cur = endIdx; cur != -1; cur = prev[cur]) {
route.add(NODES[cur]);
}
Collections.reverse(route);
return route;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1,186 @@
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
public class ScriptInterpreterTest {
@Test
public void parsesMetadataAndConfigItems() {
String src =
"// @name Test Script\n" +
"// @author Tester\n" +
"// @version 1.2.3\n" +
"// @minApi 1.0.0\n" +
"// @command test,tst\n" +
"// @config attackCows|Attack Cows|bool|true\n" +
"// @config maxRadius|Max Radius|int|18|5|35\n" +
"// @config style|Style|choice|Aggressive|Accurate,Aggressive,Defensive\n" +
"void onStart(ctx) {}\n";
ScriptInterpreter.ScriptMetadata meta = ScriptInterpreter.parseMetadata(src);
assertEquals("Test Script", meta.name);
assertEquals("Tester", meta.author);
assertEquals("1.2.3", meta.version);
assertEquals("1.0.0", meta.minApiVersion);
assertEquals(2, meta.commands.size());
assertEquals("test", meta.commands.get(0));
assertTrue(meta.configItems.size() >= 3);
}
@Test
public void evaluatesControlFlowMathAndStringDispatch() {
String src =
"int total = 0;\n" +
"String lastMsg = \"\";\n" +
"int compute(int a, int b) {\n" +
" int i = 0;\n" +
" while (i < 3) {\n" +
" total += a + b;\n" +
" i++;\n" +
" }\n" +
" return Math.max(total, 10);\n" +
"}\n" +
"boolean checkChat(String msg) {\n" +
" lastMsg = msg.trim().toLowerCase();\n" +
" return lastMsg.contains(\"can't reach\") && lastMsg.length() > 5;\n" +
"}\n";
ScriptInterpreter.Environment env = ScriptInterpreter.compile(src);
Object res = env.invoke("compute", 2, 3);
assertEquals(15, ((Number) res).intValue());
assertEquals(15, ((Number) env.getVariable("total")).intValue());
Object matched = env.invoke("checkChat", " I Can't Reach That! ");
assertEquals(Boolean.TRUE, matched);
assertEquals("i can't reach that!", env.getVariable("lastMsg"));
}
@Test
public void evaluatesCollectionsNumbersAndStaticMethods() {
String src =
"int radius = 18;\n" +
"void onConfigChanged(String key, Object value) {\n" +
" if (key == \"radius\") {\n" +
" radius = value.intValue();\n" +
" }\n" +
"}\n" +
"int sumList(Object list) {\n" +
" int acc = 0;\n" +
" int i = 0;\n" +
" while (i < list.size()) {\n" +
" acc += list.get(i);\n" +
" i++;\n" +
" }\n" +
" return acc;\n" +
"}\n" +
"String mapLookup(Object m, String k) {\n" +
" if (m.containsKey(k)) { return m.get(k); }\n" +
" return \"none\";\n" +
"}\n" +
"boolean checkHasAction(Object arr, String act) {\n" +
" return PluginContext.hasAction(arr, act);\n" +
"}\n";
ScriptInterpreter.Environment env = ScriptInterpreter.compile(src);
env.invoke("onConfigChanged", "radius", Integer.valueOf(30));
assertEquals(30, ((Number) env.getVariable("radius")).intValue());
List<Integer> nums = new ArrayList<>();
nums.add(4);
nums.add(6);
nums.add(10);
assertEquals(20, ((Number) env.invoke("sumList", nums)).intValue());
String[] actions = new String[] { "Talk-to", "Attack", null };
assertEquals(Boolean.TRUE, env.invoke("checkHasAction", actions, "Attack"));
assertEquals(Boolean.FALSE, env.invoke("checkHasAction", actions, "Trade"));
Map<String, String> map = new HashMap<>();
map.put("cow", "hide");
assertTrue(map.containsKey("cow"));
assertEquals("hide", env.invoke("mapLookup", map, "cow"));
}
@Test
public void evaluatesTernaryModuloConstructorsAndIndexing() {
String src =
"int runCalc(int x) {\n" +
" int val = x > 5 ? x * 2 : x + 10;\n" +
" val *= 2;\n" +
" val /= 4;\n" +
" val %= 7;\n" +
" return val;\n" +
"}\n" +
"String testContainersAndIndexing() {\n" +
" List items = [10, 20, 30];\n" +
" items[1] = 25;\n" +
" Map m = new HashMap();\n" +
" m[\"key\"] = \"hello\";\n" +
" StringBuilder sb = new StringBuilder();\n" +
" sb.append(m[\"key\"]).append(\" (\").append(items[1]).append(\")-\").append(17 % 5);\n" +
" return sb.toString();\n" +
"}\n";
ScriptInterpreter.Environment env = ScriptInterpreter.compile(src);
// x = 6 -> 12 * 2 = 24 / 4 = 6 % 7 = 6
assertEquals(6, ((Number) env.invoke("runCalc", 6)).intValue());
// x = 3 -> 13 * 2 = 26 / 4 = 6 % 7 = 6
assertEquals(6, ((Number) env.invoke("runCalc", 3)).intValue());
assertEquals("hello (25)-2", env.invoke("testContainersAndIndexing"));
}
@Test
public void evaluatesForLoopsBreakContinueBracelessAndSwitch() {
String src =
"int sumForAndBreakContinue() {\n" +
" int sum = 0;\n" +
" for (int i = 0; i < 10; i++) {\n" +
" if (i % 2 == 0) continue;\n" +
" if (i > 7) break;\n" +
" sum += i;\n" +
" }\n" +
" return sum;\n" +
"}\n" +
"int sumForEach(List items) {\n" +
" int total = 0;\n" +
" for (Object item : items) total += item;\n" +
" return total;\n" +
"}\n" +
"String testSwitchAndBracelessIf(int v) {\n" +
" if (v < 0) return \"neg\";\n" +
" String res = \"\";\n" +
" switch (v) {\n" +
" case 1:\n" +
" case 2:\n" +
" res = \"low\";\n" +
" break;\n" +
" case 3:\n" +
" res = \"three\";\n" +
" break;\n" +
" default:\n" +
" res = \"other\";\n" +
" }\n" +
" return res;\n" +
"}\n" +
"String testMenuEntryFastPath() {\n" +
" MenuEntry me = new MenuEntry(\"Take @lre@Coins\", 234, 995, 10, 10);\n" +
" return me.matches(\"Take\", \"Coins\") ? MenuEntry.stripColorTags(me.getTarget()) : \"no\";\n" +
"}\n";
ScriptInterpreter.Environment env = ScriptInterpreter.compile(src);
// 1 + 3 + 5 + 7 = 16
assertEquals(16, ((Number) env.invoke("sumForAndBreakContinue")).intValue());
assertEquals(60, ((Number) env.invoke("sumForEach", java.util.Arrays.asList(10, 20, 30))).intValue());
assertEquals("neg", env.invoke("testSwitchAndBracelessIf", -1));
assertEquals("low", env.invoke("testSwitchAndBracelessIf", 1));
assertEquals("low", env.invoke("testSwitchAndBracelessIf", 2));
assertEquals("three", env.invoke("testSwitchAndBracelessIf", 3));
assertEquals("other", env.invoke("testSwitchAndBracelessIf", 99));
assertEquals("Coins", env.invoke("testMenuEntryFastPath"));
}
}
+16 -2
View File
@@ -1,4 +1,5 @@
{
"core": {
"server_name": "2006Scape",
"server_test_version": 2.3,
"gui_enabled": false,
@@ -23,7 +24,20 @@
"timeout": 60,
"item_requirements": true,
"max_players": 200,
"website_integration": false,
"cycle_logging": true,
"cycle_logging_tick": 10
"cycle_logging_tick": 10,
"rsa_exponent": "",
"rsa_modulus": ""
},
"discord": {
"token": "",
"welcome_channel_id": "655143683083206667",
"log_channel_id": "1083146780507656294",
"player_count": false
},
"website": {
"password": "",
"players_online": false,
"registered_accounts": false
}
}
@@ -44556,7 +44556,7 @@
"respawn": 10,
"combat": 98,
"hitpoints": 100,
"maxHit": 0,
"maxHit": 20,
"size": 1,
"attackSpeed": 4000,
"attackAnim": 429,
@@ -44578,7 +44578,7 @@
"respawn": 10,
"combat": 115,
"hitpoints": 100,
"maxHit": 0,
"maxHit": 29,
"size": 1,
"attackSpeed": 4000,
"attackAnim": 2067,
+6 -6
View File
@@ -22973,7 +22973,7 @@
"maxHit": 3,
"strength": 10,
"attack": 10,
"x": 3233,
"x": 3231,
"y": 3300,
"id": 41,
"walk": 1,
@@ -23113,7 +23113,7 @@
"maxHit": 3,
"strength": 10,
"attack": 10,
"x": 3185,
"x": 3186,
"y": 3277,
"id": 41,
"walk": 1,
@@ -23123,7 +23123,7 @@
"maxHit": 3,
"strength": 10,
"attack": 10,
"x": 3185,
"x": 3188,
"y": 3277,
"id": 41,
"walk": 1,
@@ -23737,11 +23737,11 @@
"maxHit": 0,
"strength": 0,
"attack": 0,
"x": 2896,
"y": 3428,
"x": 2899,
"y": 3429,
"id": 454,
"walk": 1,
"height": 0
"height": 1
},
{
"maxHit": 3,
+29
View File
@@ -174,6 +174,11 @@
"x": 3209,
"y": 3490,
"height": 0
},
{
"x": 3223,
"y": 3491,
"height": 0
}
],
"id": 1512,
@@ -275,6 +280,30 @@
"id": 1508,
"type": 0
},
{
"face": 3,
"locations": [
{
"x": 3292,
"y": 3167,
"height": 0
}
],
"id": 1506,
"type": 0
},
{
"face": 3,
"locations": [
{
"x": 3293,
"y": 3167,
"height": 0
}
],
"id": 1508,
"type": 0
},
{
"face": 0,
"locations": [
+2 -2
View File
@@ -1757,7 +1757,7 @@
"height": 0
}
],
"id": 1516
"id": 14751
},
{
"face": 2,
@@ -1768,7 +1768,7 @@
"height": 0
}
],
"id": 1519
"id": 14752
},
{
"face": 0,
Binary file not shown.
@@ -0,0 +1,30 @@
package plugin.area.alkharid
import com.rs2.event.EventContext
import com.rs2.event.EventSubscriber
import com.rs2.event.SubscribesTo
import com.rs2.event.impl.ObjectFirstClickEvent
import com.rs2.game.players.Player
import plugin.area.alkharid.AlKharidGateUtil.GATE_NORTH
import plugin.area.alkharid.AlKharidGateUtil.GATE_SOUTH
import plugin.area.alkharid.AlKharidGateUtil.hasCompletedPrinceAli
import plugin.area.alkharid.AlKharidGateUtil.passThroughGate
@SubscribesTo(ObjectFirstClickEvent::class)
class AlKharidGateFirstClick : EventSubscriber<ObjectFirstClickEvent> {
override fun subscribe(context: EventContext, player: Player, event: ObjectFirstClickEvent) {
val objectId = event.gameObject
if (objectId != GATE_NORTH && objectId != GATE_SOUTH) {
return
}
if (player.hasCompletedPrinceAli()) {
player.packetSender.sendMessage("The guards recognize you as a friend of Al-Kharid and let you pass.")
passThroughGate(player)
return
}
player.packetSender.sendMessage("You need to talk to the border guard.")
}
}
@@ -0,0 +1,135 @@
package plugin.area.alkharid
import com.rs2.event.CycleEvent
import com.rs2.event.CycleEventContainer
import com.rs2.event.CycleEventHandler
import com.rs2.GameEngine
import com.rs2.game.content.StaticItemList
import com.rs2.game.content.StaticNpcList
import com.rs2.game.content.StaticObjectList
import com.rs2.game.content.music.sound.SoundList
import com.rs2.game.objects.Objects
import com.rs2.game.players.Player
import com.rs2.world.clip.PathFinder
import com.rs2.world.clip.Region
object AlKharidGateUtil {
const val GATE_SOUTH = StaticObjectList.GATE_2882
const val GATE_NORTH = StaticObjectList.GATE_2883
const val BORDER_GUARD_1 = StaticNpcList.BORDER_GUARD
const val BORDER_GUARD_2 = StaticNpcList.BORDER_GUARD_926
const val TOLL_COINS = 10
const val COINS_ID = StaticItemList.COINS_995
fun Player.hasCompletedPrinceAli(): Boolean = this.princeAli >= 1
fun Player.hasTollCoins(): Boolean = this.itemAssistant.playerHasItem(COINS_ID, TOLL_COINS)
fun Player.payToll(): Boolean {
if (!hasTollCoins()) return false
this.itemAssistant.deleteItem(COINS_ID, this.itemAssistant.getItemSlot(COINS_ID), TOLL_COINS)
return true
}
fun isNearGate(player: Player): Boolean {
return (player.absX in 3266..3269) && (player.absY in 3225..3230)
}
fun buildPathToGate(player: Player, movingEast: Boolean): List<Pair<Int, Int>> {
val gateY = if (player.absY >= 3228) 3228 else 3227
val entranceX = if (movingEast) 3267 else 3268
val exitX = if (movingEast) 3268 else 3267
val bypassX = if (movingEast) 3266 else 3269
val steps = mutableListOf<Pair<Int, Int>>()
var curX = player.absX
var curY = player.absY
// 1. If player is directly behind a guard on the sentry line (X = 3267 or 3268, Y >= 3229 or Y <= 3226),
// step outward to the bypass column first so we don't walk straight through the guard
if (curX == entranceX && (curY >= 3229 || curY <= 3226)) {
curX = bypassX
steps.add(Pair(curX, curY))
}
// 2. Align Y onto the road (3227 or 3228)
while (curY != gateY) {
curY += if (gateY > curY) 1 else -1
steps.add(Pair(curX, curY))
}
// 3. Align X to the gate entrance tile
while (curX != entranceX) {
curX += if (entranceX > curX) 1 else -1
steps.add(Pair(curX, curY))
}
// 4. Step through the gate
steps.add(Pair(exitX, gateY))
return steps
}
fun passThroughGate(player: Player) {
if (System.currentTimeMillis() - player.doorDelay < 1200) {
return
}
player.doorDelay = System.currentTimeMillis()
player.packetSender.closeAllWindows()
val movingEast = player.absX <= 3267
val steps = buildPathToGate(player, movingEast)
// Play gate opening sound
player.packetSender.sendSound(SoundList.OPEN_GATE, 100, 0)
// Open both gates for this player's scene and remove their server-side
// clipping too, so the route can actually cross the gate line.
Region.removeObject(GATE_SOUTH, 3268, 3227, player.heightLevel, 0, 0)
Region.removeObject(GATE_NORTH, 3268, 3228, player.heightLevel, 0, 0)
Region.addObject(GATE_SOUTH, 3268, 3227, player.heightLevel, 0, 3, false)
Region.addObject(GATE_NORTH, 3268, 3228, player.heightLevel, 0, 1, false)
GameEngine.objectHandler.placeObject(Objects(GATE_SOUTH, 3268, 3227, player.heightLevel, 3, 0, 0))
GameEngine.objectHandler.placeObject(Objects(GATE_NORTH, 3268, 3228, player.heightLevel, 1, 0, 0))
// Prevent client click packets from disrupting the transit.
player.stopPlayer = true
val targetX = steps.last().first
val targetY = steps.last().second
val routeFound = PathFinder.getPathFinder().findRoute(player, targetX, targetY, false, 1, 1)
if (!routeFound) {
closeGateForPlayer(player)
player.stopPlayer = false
return
}
var ticks = 0
CycleEventHandler.getSingleton().addEvent(player, object : CycleEvent() {
override fun execute(container: CycleEventContainer) {
ticks++
val crossedGate = player.absX == targetX && player.absY == targetY
// Keep the open state visible long enough for the client to
// render the swing, even when the player is already at the exit tile.
if ((crossedGate && ticks >= 3) || ticks >= 8) {
closeGateForPlayer(player)
container.stop()
}
}
override fun stop() {
player.stopPlayer = false
}
}, 1)
}
private fun closeGateForPlayer(player: Player) {
Region.removeObject(GATE_SOUTH, 3268, 3227, player.heightLevel, 0, 3)
Region.removeObject(GATE_NORTH, 3268, 3228, player.heightLevel, 0, 1)
Region.addObject(GATE_SOUTH, 3268, 3227, player.heightLevel, 0, 0, false)
Region.addObject(GATE_NORTH, 3268, 3228, player.heightLevel, 0, 0, false)
GameEngine.objectHandler.placeObject(Objects(GATE_SOUTH, 3268, 3227, player.heightLevel, 0, 0, 0))
GameEngine.objectHandler.placeObject(Objects(GATE_NORTH, 3268, 3228, player.heightLevel, 0, 0, 0))
}
}
@@ -0,0 +1,76 @@
package plugin.area.alkharid
import com.rs2.event.EventContext
import com.rs2.event.EventSubscriber
import com.rs2.event.SubscribesTo
import com.rs2.event.impl.NpcFirstClickEvent
import com.rs2.game.players.Player
import plugin.area.alkharid.AlKharidGateUtil.BORDER_GUARD_1
import plugin.area.alkharid.AlKharidGateUtil.BORDER_GUARD_2
import plugin.area.alkharid.AlKharidGateUtil.hasCompletedPrinceAli
import plugin.area.alkharid.AlKharidGateUtil.isNearGate
import plugin.area.alkharid.AlKharidGateUtil.passThroughGate
import plugin.area.alkharid.AlKharidGateUtil.payToll
@SubscribesTo(NpcFirstClickEvent::class)
class BorderGuardFirstClick : EventSubscriber<NpcFirstClickEvent> {
override fun subscribe(context: EventContext, player: Player, event: NpcFirstClickEvent) {
val npcId = event.npc
if (npcId != BORDER_GUARD_1 && npcId != BORDER_GUARD_2) {
return
}
if (player.hasCompletedPrinceAli()) {
player.talkingNpc = npcId
player.dialogueFactory.clear()
player.dialogueFactory
.sendPlayerChat("Can I come through this gate?")
.sendNpcChat(npcId, "You may pass, friend of Al-Kharid.")
.execute()
} else {
startTollDialogue(player, npcId)
}
}
private fun startTollDialogue(player: Player, npcId: Int) {
val dialogue = player.dialogueFactory
dialogue.clear()
player.talkingNpc = npcId
dialogue.sendPlayerChat("Can I come through this gate?")
.sendNpcChat(npcId, "You must pay a toll of 10 gold coins to pass.")
.sendOption(
"Okay, I'll pay.", { payToll(player, npcId) },
"Who does my money go to?", {
dialogue.sendPlayerChat("Who does my money go to?")
.sendNpcChat(npcId, "The money goes to the city of Al-Kharid.", "Will you pay the toll?")
.sendOption(
"Okay, I'll pay.", { payToll(player, npcId) },
"No thanks, I'll walk around.", { declineToll(player, npcId) }
)
},
"No thanks, I'll walk around.", { declineToll(player, npcId) }
)
.execute()
}
private fun payToll(player: Player, npcId: Int) {
if (!isNearGate(player)) {
player.packetSender.sendMessage("You need to be closer to the gate to use it.")
player.packetSender.closeAllWindows()
return
}
if (player.payToll()) {
player.packetSender.sendMessage("You pay the border guard 10 coins.")
passThroughGate(player)
} else {
player.dialogueFactory.sendPlayerChat("I haven't got that much.")
.sendNpcChat(npcId, "Well, you can't come through here then.")
}
}
private fun declineToll(player: Player, npcId: Int) {
player.dialogueFactory.sendPlayerChat("No thanks, I'll walk around.")
.sendNpcChat(npcId, "Ok suit yourself.")
}
}
@@ -0,0 +1,31 @@
package plugin.buttons.combat
import com.rs2.event.EventContext
import com.rs2.event.EventSubscriber
import com.rs2.event.SubscribesTo
import com.rs2.event.impl.ButtonActionEvent
import com.rs2.game.players.Player
import org.apollo.cache.def.ItemDefinition
@SubscribesTo(ButtonActionEvent::class)
class AutocastCancelButtonPlugin : EventSubscriber<ButtonActionEvent> {
override fun test(event: ButtonActionEvent) = event.button in CANCEL_BUTTONS
override fun subscribe(context: EventContext, player: Player, event: ButtonActionEvent) {
if (player.isDead) return
val weaponId = player.playerEquipment[player.playerWeapon]
val weaponName = if (weaponId == -1) {
"Unarmed"
} else {
ItemDefinition.lookup(weaponId)?.name ?: "Unarmed"
}
player.itemAssistant.sendWeapon(weaponId, weaponName)
if (!player.autocasting) {
player.packetSender.sendFrame36(43, player.fightMode)
}
}
private companion object {
val CANCEL_BUTTONS = setOf(2004, 6161, 7212, 12101, 24017)
}
}
@@ -0,0 +1,58 @@
package plugin.buttons.combat
import com.rs2.event.EventContext
import com.rs2.event.EventSubscriber
import com.rs2.event.SubscribesTo
import com.rs2.event.impl.ButtonActionEvent
import com.rs2.game.content.combat.magic.MagicData
import com.rs2.game.players.Player
@SubscribesTo(ButtonActionEvent::class)
class AutocastMenuButtonsPlugin : EventSubscriber<ButtonActionEvent> {
override fun test(event: ButtonActionEvent) =
event.button == CHOOSE_SPELL_BUTTON || event.button == ATTACK_WITH_BUTTON_1 || event.button == ATTACK_WITH_BUTTON_2
override fun subscribe(context: EventContext, player: Player, event: ButtonActionEvent) {
if (player.isDead) return
if (event.button == CHOOSE_SPELL_BUTTON) {
openSpellSelect(player)
return
}
if (player.autocastId >= 0) {
if (player.autocasting) {
player.playerAssistant.resetAutocast()
player.spellId = 0
player.usingMagic = false
} else {
player.autocasting = true
player.packetSender.sendConfig(108, 3)
player.packetSender.sendConfig(43, -1)
player.packetSender.sendString(MagicData.getSpellName(player.autocastId), 352, true)
}
} else {
openSpellSelect(player)
}
}
private fun openSpellSelect(player: Player) {
val weapon = player.playerEquipment[player.playerWeapon]
if (player.playerMagicBook == 1) {
if (weapon == ANCIENT_STAFF) {
player.packetSender.setSidebarInterface(0, 1689)
} else {
player.packetSender.sendMessage("You can't autocast ancients without an ancient staff.")
}
} else if (player.playerMagicBook == 0) {
player.packetSender.setSidebarInterface(0, if (weapon == SLAYERS_STAFF) 12050 else 1829)
}
}
private companion object {
const val CHOOSE_SPELL_BUTTON = 1097
const val ATTACK_WITH_BUTTON_1 = 1093
const val ATTACK_WITH_BUTTON_2 = 1094
const val ANCIENT_STAFF = 4675
const val SLAYERS_STAFF = 4170
}
}
@@ -0,0 +1,82 @@
package plugin.buttons.combat
import com.rs2.Constants
import com.rs2.event.EventContext
import com.rs2.event.EventSubscriber
import com.rs2.event.SubscribesTo
import com.rs2.event.impl.ButtonActionEvent
import com.rs2.game.content.combat.magic.MagicData
import com.rs2.game.players.Player
@SubscribesTo(ButtonActionEvent::class)
class AutocastSpellSelectPlugin : EventSubscriber<ButtonActionEvent> {
override fun test(event: ButtonActionEvent) = SPELL_BY_BUTTON.containsKey(event.button)
override fun subscribe(context: EventContext, player: Player, event: ButtonActionEvent) {
if (player.isDead) return
val spellIndex = SPELL_BY_BUTTON.getValue(event.button)
val weapon = player.playerEquipment[player.playerWeapon]
if (spellIndex in 32..47) {
if (player.playerMagicBook != 1 || weapon != ANCIENT_STAFF) {
player.packetSender.sendMessage("You can't autocast ancients without an ancient staff.")
return
}
} else {
if (player.playerMagicBook != 0) {
return
}
if ((spellIndex == 27 || spellIndex == 25) && weapon != SLAYERS_STAFF) {
return
}
}
val requiredLevel = MagicData.MAGIC_SPELLS[spellIndex][1]
if (player.playerLevel[Constants.MAGIC] < requiredLevel) {
player.packetSender.sendMessage("You need a Magic level of $requiredLevel to cast this spell.")
return
}
player.autocasting = true
player.autocastId = spellIndex
player.packetSender.sendConfig(108, 3)
player.packetSender.sendConfig(43, -1)
player.packetSender.setSidebarInterface(0, 328)
player.packetSender.sendString(MagicData.getSpellName(spellIndex), 352, true)
}
private companion object {
const val ANCIENT_STAFF = 4675
const val SLAYERS_STAFF = 4170
val SPELL_BY_BUTTON = mapOf(
// Interface 1829 (Modern Combat Spells)
1830 to 0, 1831 to 1, 1832 to 2, 1833 to 3,
1834 to 4, 1835 to 5, 1836 to 6, 1837 to 7,
1838 to 8, 1839 to 9, 1840 to 10, 1841 to 11,
1842 to 12, 1843 to 13, 1844 to 14, 1845 to 15,
// Interface 1689 (Ancient Magicks)
13189 to 32, 13241 to 33, 13147 to 34, 6162 to 35,
13215 to 36, 13267 to 37, 13167 to 38, 13125 to 39,
13202 to 40, 13254 to 41, 13158 to 42, 13114 to 43,
13228 to 44, 13280 to 45, 13178 to 46, 13136 to 47,
// Interface 12050 (Slayer Staff)
12052 to 27, 12056 to 25,
12051 to 12, 12053 to 13, 12054 to 14, 12055 to 15,
// Legacy / Custom Interface Fallback IDs
7038 to 0, 7039 to 1, 7040 to 2, 7041 to 3,
7042 to 4, 7043 to 5, 7044 to 6, 7045 to 7,
7046 to 8, 7047 to 9, 7048 to 10, 7049 to 11,
7050 to 12, 7051 to 13, 7052 to 14, 7053 to 15,
51133 to 32, 51185 to 33, 51091 to 34, 24018 to 35,
51159 to 36, 51211 to 37, 51111 to 38, 51069 to 39,
51146 to 40, 51198 to 41, 51102 to 42, 51058 to 43,
51172 to 44, 51224 to 45, 51122 to 46, 51080 to 47,
47019 to 27, 47020 to 25,
47021 to 12, 47022 to 13, 47023 to 14, 47024 to 15
)
}
}
@@ -0,0 +1,38 @@
package plugin.buttons.combat
import com.rs2.event.EventContext
import com.rs2.event.EventSubscriber
import com.rs2.event.SubscribesTo
import com.rs2.event.impl.ButtonActionEvent
import com.rs2.game.players.Player
@SubscribesTo(ButtonActionEvent::class)
class CombatStyleButtonsPlugin : EventSubscriber<ButtonActionEvent> {
override fun test(event: ButtonActionEvent) = STYLE_BY_BUTTON.containsKey(event.button)
override fun subscribe(context: EventContext, player: Player, event: ButtonActionEvent) {
if (player.isDead) return
player.fightMode = STYLE_BY_BUTTON.getValue(event.button)
if (player.autocasting) {
player.playerAssistant.resetAutocast()
}
}
private companion object {
val STYLE_BY_BUTTON = mapOf(
// Attack / Accurate (0)
9125 to 0, 6221 to 0, 22228 to 0, 48010 to 0, 21200 to 0, 1080 to 0,
6168 to 0, 6236 to 0, 17102 to 0, 8234 to 0, 14218 to 0, 14221 to 0,
// Defence / Defensive (1)
9126 to 1, 48008 to 1, 22229 to 1, 21201 to 1, 1078 to 1, 6169 to 1,
33019 to 1, 18078 to 1, 8235 to 1, 14219 to 1,
// Strength / Aggressive / Rapid (2)
9128 to 2, 6220 to 2, 22230 to 2, 21203 to 2, 21202 to 2, 1079 to 2,
6171 to 2, 6170 to 2, 33020 to 2, 6235 to 2, 17101 to 2, 8237 to 2,
8236 to 2, 14220 to 2,
// Controlled / Longrange (3)
9127 to 3, 48009 to 3, 33018 to 3, 6234 to 3, 6219 to 3, 18077 to 3,
18080 to 3, 18079 to 3, 17100 to 3
)
}
}
@@ -0,0 +1,125 @@
package plugin.buttons.gameframe
import com.rs2.event.EventContext
import com.rs2.event.EventSubscriber
import com.rs2.event.SubscribesTo
import com.rs2.event.impl.ButtonActionEvent
import com.rs2.game.content.music.Music
import com.rs2.game.items.impl.LightSources
import com.rs2.game.players.Player
@SubscribesTo(ButtonActionEvent::class)
class GameOptionsPlugin : EventSubscriber<ButtonActionEvent> {
private data class ToggleOption(
val configId: Int,
val configValue: Int,
val apply: (Player) -> Unit
)
override fun test(event: ButtonActionEvent): Boolean =
event.button in BRIGHTNESS_ACTIONS ||
event.button in TOGGLE_OPTIONS ||
event.button in MUSIC_VOLUME_RANGE ||
event.button in SOUND_VOLUME_RANGE
override fun subscribe(context: EventContext, player: Player?, event: ButtonActionEvent) {
if (player == null) return
val button = event.button
BRIGHTNESS_ACTIONS[button]?.let { action ->
action(player)
return
}
TOGGLE_OPTIONS[button]?.let { option ->
option.apply(player)
player.packetSender.sendConfig(option.configId, option.configValue)
return
}
when (button) {
in MUSIC_VOLUME_RANGE -> handleMusicVolume(player, MUSIC_VOLUME_RANGE.last - button)
in SOUND_VOLUME_RANGE -> handleSoundVolume(player, SOUND_VOLUME_RANGE.last - button)
}
}
private fun handleMusicVolume(player: Player, level: Int) {
player.musicVolumeLevel = level
player.packetSender.sendConfig(CONFIG_MUSIC_VOLUME, level)
if (level == VOLUME_MUTED) {
if (player.musicOn) {
player.musicOn = false
player.addTemporary("CURRENT_SONG", NO_SONG)
} else {
player.packetSender.sendMessage("Your music is already turned off.")
}
} else {
player.musicOn = true
Music.playMusic(player)
}
}
private fun handleSoundVolume(player: Player, level: Int) {
player.soundVolumeLevel = level
player.packetSender.sendConfig(CONFIG_SOUND_VOLUME, level)
if (level == VOLUME_MUTED) {
if (player.soundOn) {
player.soundOn = false
} else {
player.packetSender.sendMessage("Your sound is already turned off.")
}
} else {
player.soundOn = true
}
}
private companion object {
const val BUTTON_BRIGHTNESS_1 = 3138
const val BUTTON_BRIGHTNESS_2 = 3140
const val BUTTON_BRIGHTNESS_3 = 3142
const val BUTTON_BRIGHTNESS_4 = 3144
const val BUTTON_TWO_MOUSE_BUTTONS = 3145
const val BUTTON_ONE_MOUSE_BUTTON = 3146
const val BUTTON_CHAT_EFFECTS_ON = 3147
const val BUTTON_CHAT_EFFECTS_OFF = 3148
const val BUTTON_SPLIT_CHAT_ON = 3189
const val BUTTON_SPLIT_CHAT_OFF = 3190
const val BUTTON_ACCEPT_AID_ON = 48176
const val BUTTON_ACCEPT_AID_OFF = 48177
val MUSIC_VOLUME_RANGE = 3162..3166
val SOUND_VOLUME_RANGE = 3173..3177
const val VOLUME_MUTED = 4
const val NO_SONG = -1
const val CONFIG_MUSIC_VOLUME = 168
const val CONFIG_SOUND_VOLUME = 169
const val CONFIG_MOUSE_BUTTONS = 170
const val CONFIG_CHAT_EFFECTS = 171
const val CONFIG_SPLIT_CHAT = 287
const val CONFIG_ACCEPT_AID = 427
const val STATE_OFF = 0
const val STATE_ON = 1
val BRIGHTNESS_ACTIONS: Map<Int, (Player) -> Unit> = mapOf(
BUTTON_BRIGHTNESS_1 to LightSources::brightness1,
BUTTON_BRIGHTNESS_2 to LightSources::brightness2,
BUTTON_BRIGHTNESS_3 to LightSources::brightness3,
BUTTON_BRIGHTNESS_4 to LightSources::brightness4
)
val TOGGLE_OPTIONS: Map<Int, ToggleOption> = mapOf(
BUTTON_TWO_MOUSE_BUTTONS to ToggleOption(CONFIG_MOUSE_BUTTONS, STATE_OFF) { it.mouseButton = false },
BUTTON_ONE_MOUSE_BUTTON to ToggleOption(CONFIG_MOUSE_BUTTONS, STATE_ON) { it.mouseButton = true },
BUTTON_CHAT_EFFECTS_ON to ToggleOption(CONFIG_CHAT_EFFECTS, STATE_OFF) { it.chatEffects = true },
BUTTON_CHAT_EFFECTS_OFF to ToggleOption(CONFIG_CHAT_EFFECTS, STATE_ON) { it.chatEffects = false },
BUTTON_SPLIT_CHAT_ON to ToggleOption(CONFIG_SPLIT_CHAT, STATE_ON) { it.splitChat = true },
BUTTON_SPLIT_CHAT_OFF to ToggleOption(CONFIG_SPLIT_CHAT, STATE_OFF) { it.splitChat = false },
BUTTON_ACCEPT_AID_ON to ToggleOption(CONFIG_ACCEPT_AID, STATE_ON) { it.acceptAid = true },
BUTTON_ACCEPT_AID_OFF to ToggleOption(CONFIG_ACCEPT_AID, STATE_OFF) { it.acceptAid = false }
)
}
}
@@ -0,0 +1,25 @@
package plugin.commands
import com.rs2.event.EventContext
import com.rs2.event.EventSubscriber
import com.rs2.event.SubscribesTo
import com.rs2.event.impl.CommandEvent
import com.rs2.game.players.Player
@SubscribesTo(CommandEvent::class)
class RandomToggle : EventSubscriber<CommandEvent> {
override fun test(event: CommandEvent): Boolean =
event.name.equals("random", ignoreCase = true) ||
event.name.equals("randomtoggle", ignoreCase = true) ||
event.name.equals("togglerandom", ignoreCase = true)
override fun subscribe(context: EventContext, player: Player?, event: CommandEvent) {
if (player == null) return
context.breakSubscriberChain()
player.randomEventsEnabled = !player.randomEventsEnabled
val stateText = if (player.randomEventsEnabled) "now" else "no longer"
player.packetSender.sendMessage("You will $stateText receive random events.")
}
}
@@ -0,0 +1,350 @@
package plugin.commands
import com.rs2.event.EventContext
import com.rs2.event.EventSubscriber
import com.rs2.event.SubscribesTo
import com.rs2.event.impl.CommandEvent
import com.rs2.game.npcs.NPCDefinition
import com.rs2.game.npcs.drops.ItemDrop
import com.rs2.game.npcs.drops.NPCDropsHandler
import com.rs2.game.players.Player
import com.rs2.util.NpcDrop
import org.apollo.cache.def.ItemDefinition
@SubscribesTo(CommandEvent::class)
class SearchDrops : EventSubscriber<CommandEvent> {
companion object {
private const val INTERFACE_ID = 8134
private const val TITLE_LINE_ID = 8144
private const val SUBTITLE_LINE_ID = 8145
private const val MAX_SCROLL_LINES = 199
private const val MAX_DISPLAY_RESULTS = 196
private val CLEAR_RANGES = arrayOf(8146..8195, 12174..12223, 14945..15044)
private fun formatChance(chance: Int): String = when {
chance <= 1 -> "@gre@Always@bla@"
chance <= 32 -> "@blu@1/$chance@bla@"
chance <= 128 -> "@yel@1/$chance@bla@"
else -> "@red@1/$chance@bla@"
}
private fun formatAmount(amounts: IntArray?): String {
if (amounts == null || amounts.isEmpty()) return ""
return if (amounts.size >= 2 && amounts[0] != amounts[1]) "${amounts[0]}-${amounts[1]}x " else "${amounts[0]}x "
}
private fun ItemDefinition.displayName(): String {
val noteTag = if (isNote) " (noted)" else ""
return "$name$noteTag"
}
private fun String.toTitleCase(): String =
split(" ")
.filter { it.isNotEmpty() }
.joinToString(" ") { word ->
word.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }
}
private fun findCacheItemName(query: String): String? {
val defs = ItemDefinition.getDefinitions() ?: return null
return defs.firstOrNull { it?.name.equals(query, ignoreCase = true) }?.displayName()
}
private fun formatDisplayTitle(input: String, searchId: Int?, matchedItemNames: Set<String>): String {
if (searchId != null) {
ItemDefinition.forId(searchId)?.takeIf { !it.name.isNullOrEmpty() }?.let { return it.displayName() }
}
return findCacheItemName(input)
?: matchedItemNames.singleOrNull()
?: input.toTitleCase()
}
}
private class ScrollInterface(private val player: Player) {
var linesWritten = 0
private set
fun open(title: String, subtitle: String) {
for (range in CLEAR_RANGES) {
for (i in range) {
player.packetSender.sendString("", i)
}
}
player.packetSender.sendString("@dre@$title", TITLE_LINE_ID)
player.packetSender.sendString(subtitle, SUBTITLE_LINE_ID)
}
fun writeLine(text: String): Boolean {
if (linesWritten >= MAX_SCROLL_LINES) return false
val lineId = when {
linesWritten < 49 -> 8147 + linesWritten
linesWritten < 99 -> 12174 + (linesWritten - 49)
else -> 14945 + (linesWritten - 99)
}
player.packetSender.sendString(text, lineId)
linesWritten++
return true
}
fun show() {
player.packetSender.showInterface(INTERFACE_ID)
}
}
private data class ItemDropResult(
val npcName: String,
val combatLevel: Int,
val itemDisplayName: String,
val amountStr: String,
val chance: Int
) {
fun toDisplayText(): String =
"@blu@$npcName@bla@ (lvl $combatLevel) - $amountStr$itemDisplayName (${formatChance(chance)})"
}
private data class NpcDropEntry(
val itemId: Int,
val chance: Int,
val amountStr: String
)
private class NpcGroup(val combat: Int) {
val items = ArrayList<ItemDrop>()
}
override fun test(event: CommandEvent): Boolean = when (event.name.lowercase()) {
"searchdrops", "drops", "dropsearch" -> true
else -> false
}
override fun subscribe(context: EventContext, player: Player?, event: CommandEvent) {
if (player == null) return
context.breakSubscriberChain()
handleDropsCommand(player, event.arguments)
}
private fun handleDropsCommand(player: Player, arguments: Array<String>) {
if (arguments.isEmpty()) {
sendUsage(player)
return
}
val subcommand = arguments[0].lowercase()
val query = arguments.drop(1).joinToString(" ").trim()
when (subcommand) {
"item", "i" -> {
if (query.isEmpty()) {
player.packetSender.sendMessage("Usage: ::searchdrops item <id or name>")
return
}
val drops = NPCDropsHandler.getNpcDrops()
if (drops.isNullOrEmpty()) {
player.packetSender.sendMessage("NPC drops are not currently loaded.")
return
}
handleItemDropsCommand(player, drops, query)
}
"npc", "n" -> {
if (query.isEmpty()) {
player.packetSender.sendMessage("Usage: ::searchdrops npc <id or name>")
return
}
val drops = NPCDropsHandler.getNpcDrops()
if (drops.isNullOrEmpty()) {
player.packetSender.sendMessage("NPC drops are not currently loaded.")
return
}
handleNpcDropsCommand(player, drops, query)
}
else -> sendUsage(player)
}
}
private fun sendUsage(player: Player) {
player.packetSender.sendMessage("Usage: ::searchdrops item <id/name> or ::searchdrops npc <id/name>")
}
private fun handleItemDropsCommand(player: Player, drops: Array<NpcDrop>, query: String) {
val searchId = query.toIntOrNull()
val results = LinkedHashSet<ItemDropResult>()
val matchedItemNames = LinkedHashSet<String>()
var totalVariants = 0
for (npcDrop in drops) {
val items = npcDrop.items ?: continue
val npcDef = NPCDefinition.forId(npcDrop.id) ?: continue
if (npcDef.combat <= 0) continue
val npcName = npcDef.name ?: "Unknown"
val combat = npcDef.combat
for (itemDrop in items) {
if (searchId != null && itemDrop.item_id != searchId) {
continue
}
val itemDef = ItemDefinition.forId(itemDrop.item_id) ?: continue
val rawName = itemDef.name ?: continue
if (searchId == null && !rawName.contains(query, ignoreCase = true)) {
continue
}
totalVariants++
val displayName = itemDef.displayName()
matchedItemNames.add(displayName)
results.add(
ItemDropResult(
npcName = npcName,
combatLevel = combat,
itemDisplayName = displayName,
amountStr = formatAmount(itemDrop.amounts),
chance = itemDrop.chance
)
)
}
}
val displayTitle = formatDisplayTitle(query, searchId, matchedItemNames)
if (results.isEmpty()) {
player.packetSender.sendMessage("No NPCs found dropping: '$displayTitle'")
return
}
val sortedResults = results.sortedWith(
compareBy({ it.combatLevel }, { it.npcName }, { it.chance })
)
val scroll = ScrollInterface(player)
scroll.open("NPC Drops: $displayTitle", "Showing NPCs that drop this item:")
val displayLimit = sortedResults.size.coerceAtMost(MAX_DISPLAY_RESULTS)
for (i in 0 until displayLimit) {
scroll.writeLine(sortedResults[i].toDisplayText())
}
scroll.writeLine("")
if (sortedResults.size > MAX_DISPLAY_RESULTS) {
scroll.writeLine("@red@Only $MAX_DISPLAY_RESULTS results can be displayed (out of ${sortedResults.size} matches).")
player.packetSender.sendMessage(
"Found ${sortedResults.size} drop matches for '$displayTitle'. Only $MAX_DISPLAY_RESULTS results can be displayed."
)
} else {
val variantsText = if (totalVariants > sortedResults.size) " ($totalVariants NPC variants)" else ""
scroll.writeLine("@dre@Total: ${sortedResults.size} unique drop match${if (sortedResults.size == 1) "" else "es"}$variantsText")
player.packetSender.sendMessage(
"Found ${sortedResults.size} drop match${if (sortedResults.size == 1) "" else "es"} for '$displayTitle'."
)
}
scroll.show()
}
private fun handleNpcDropsCommand(player: Player, drops: Array<NpcDrop>, query: String) {
val searchId = query.toIntOrNull()
val matchingNpcDrops = ArrayList<Pair<NPCDefinition, NpcDrop>>()
for (npcDrop in drops) {
val npcDef = NPCDefinition.forId(npcDrop.id) ?: continue
val npcName = npcDef.name ?: continue
if (npcName.isEmpty() || npcDef.combat <= 0) continue
val matches = if (searchId != null) {
npcDrop.id == searchId
} else {
npcName.contains(query, ignoreCase = true)
}
if (matches) {
matchingNpcDrops.add(Pair(npcDef, npcDrop))
}
}
if (matchingNpcDrops.isEmpty()) {
player.packetSender.sendMessage("No NPC found matching: '$query'")
return
}
val targetDrops = if (searchId == null) {
matchingNpcDrops.filter { it.first.name.equals(query, ignoreCase = true) }.ifEmpty { matchingNpcDrops }
} else {
matchingNpcDrops
}
val grouped = LinkedHashMap<String, NpcGroup>()
for ((npcDef, drop) in targetDrops) {
val group = grouped.getOrPut(npcDef.name) { NpcGroup(npcDef.combat) }
val items = drop.items ?: continue
group.items.addAll(items)
}
val singleNpc = grouped.size == 1
val headerTitle = if (singleNpc) {
val name = grouped.keys.first()
val combat = grouped[name]?.combat ?: 0
"$name (lvl $combat)"
} else {
query.toTitleCase()
}
val scroll = ScrollInterface(player)
scroll.open("Drop Table: $headerTitle", "Showing all drops for this NPC:")
var totalUniqueDrops = 0
var dropsDisplayed = 0
for ((npcName, group) in grouped) {
if (!singleNpc && dropsDisplayed < MAX_DISPLAY_RESULTS) {
scroll.writeLine("@dre@--- $npcName (lvl ${group.combat}) ---")
}
val distinctEntries = LinkedHashSet<NpcDropEntry>()
for (item in group.items) {
distinctEntries.add(
NpcDropEntry(
itemId = item.item_id,
chance = item.chance,
amountStr = formatAmount(item.amounts)
)
)
}
val sortedEntries = distinctEntries.sortedWith(
compareBy<NpcDropEntry>({ if (it.chance <= 1) 0 else 1 }, { it.chance })
.thenBy { ItemDefinition.forId(it.itemId)?.name.orEmpty() }
)
for (entry in sortedEntries) {
val def = ItemDefinition.forId(entry.itemId) ?: continue
if (def.name == null) continue
totalUniqueDrops++
if (dropsDisplayed < MAX_DISPLAY_RESULTS) {
val dropChance = formatChance(entry.chance)
scroll.writeLine("${entry.amountStr}${def.displayName()} ($dropChance)")
dropsDisplayed++
}
}
if (!singleNpc && dropsDisplayed < MAX_DISPLAY_RESULTS) {
scroll.writeLine("")
}
}
scroll.writeLine("")
if (totalUniqueDrops > MAX_DISPLAY_RESULTS) {
scroll.writeLine("@red@Only $MAX_DISPLAY_RESULTS results can be displayed (out of $totalUniqueDrops drops).")
} else {
scroll.writeLine("@dre@Total: $totalUniqueDrops unique drop${if (totalUniqueDrops == 1) "" else "s"}")
}
scroll.show()
player.packetSender.sendMessage("Found $totalUniqueDrops drops for '$headerTitle'.")
}
}
@@ -0,0 +1,99 @@
package plugin.commands
import com.rs2.event.EventContext
import com.rs2.event.EventSubscriber
import com.rs2.event.SubscribesTo
import com.rs2.event.impl.CommandEvent
import com.rs2.game.players.Player
import org.apollo.cache.def.ItemDefinition
@SubscribesTo(CommandEvent::class)
class SearchItem : EventSubscriber<CommandEvent> {
companion object {
/**
* Revision 377 maximum item ID (7,956 items in cache: IDs 0..7955).
*/
private const val MAX_ITEM_ID = 7955
private const val INTERFACE_ID = 8134
private const val TITLE_LINE_ID = 8144
private const val SUBTITLE_LINE_ID = 8145
private const val MAX_SCROLL_LINES = 199
private val CLEAR_RANGES = arrayOf(8146..8195, 12174..12223, 14945..15044)
private fun showResults(player: Player, query: String, results: List<String>) {
for (range in CLEAR_RANGES) {
for (i in range) {
player.packetSender.sendString("", i)
}
}
player.packetSender.sendString("@dre@Item Search: \"$query\"", TITLE_LINE_ID)
val total = results.size
val subtitle = if (total > MAX_SCROLL_LINES) {
"Showing first $MAX_SCROLL_LINES of $total matches (refine search for more)"
} else {
"$total match${if (total == 1) "" else "es"} found"
}
player.packetSender.sendString(subtitle, SUBTITLE_LINE_ID)
val display = results.take(MAX_SCROLL_LINES)
for ((index, line) in display.withIndex()) {
val lineId = when {
index < 49 -> 8147 + index
index < 99 -> 12174 + (index - 49)
else -> 14945 + (index - 99)
}
player.packetSender.sendString(line, lineId)
}
player.packetSender.showInterface(INTERFACE_ID)
}
}
override fun test(event: CommandEvent): Boolean = when (event.name.lowercase()) {
"searchitem", "itemsearch" -> true
else -> false
}
override fun subscribe(context: EventContext, player: Player?, event: CommandEvent) {
if (player == null) return
context.breakSubscriberChain()
val arguments = event.arguments
if (arguments.isEmpty()) {
player.packetSender.sendMessage("Specify an item name or ID to search: ::searchitem dragon or ::searchitem 4151")
return
}
val query = arguments.joinToString(" ").trim()
val searchId = query.toIntOrNull()
val count = ItemDefinition.count().coerceAtMost(MAX_ITEM_ID + 1)
val notedId = if (searchId != null && searchId in 0 until count) ItemDefinition.itemToNote(searchId) else -1
val unnotedId = if (searchId != null && searchId in 0 until count && ItemDefinition.lookup(searchId)?.isNote == true) {
ItemDefinition.lookup(searchId)?.noteInfoId ?: -1
} else -1
val results = ArrayList<String>()
for (id in 0 until count) {
val def = ItemDefinition.lookup(id) ?: continue
val defName = def.name ?: continue
if (defName.isEmpty() || defName.equals("null", ignoreCase = true)) continue
val matches = (searchId != null && (id == searchId || (notedId != searchId && id == notedId) || id == unnotedId))
|| defName.contains(query, ignoreCase = true)
if (matches) {
val tag = if (def.isNote) " @dre@(noted)@bla@" else ""
results.add("@bla@$defName$tag - ID: @blu@$id")
}
}
if (results.isEmpty()) {
player.packetSender.sendMessage("No items found matching: $query")
} else {
showResults(player, query, results)
}
}
}
@@ -0,0 +1,171 @@
package plugin.commands.admin
import com.rs2.Constants
import com.rs2.event.EventContext
import com.rs2.event.EventSubscriber
import com.rs2.event.SubscribesTo
import com.rs2.event.impl.AdminCommandEvent
import com.rs2.game.content.combat.magic.SpellTeleport
import com.rs2.game.content.music.sound.SoundList
import com.rs2.game.players.Player
@SubscribesTo(AdminCommandEvent::class)
class Teleport : EventSubscriber<AdminCommandEvent> {
companion object {
private const val ANIMATION_MODERN_START = 714
private const val ANIMATION_MODERN_END = 715
private const val GFX_MODERN = 308
private const val TIMER_MODERN = 10
private const val ANIMATION_ANCIENT_START = 1979
private const val GFX_ANCIENT = 392
private const val TIMER_ANCIENT = 9
private val CITIES = SpellTeleport.values().associateBy { it.name.lowercase().replace('_', ' ') }
private val CITY_ALIASES = mapOf(
"lumby" to "lumbridge",
"fally" to "falador",
"cammy" to "camelot",
"ardy" to "ardougne",
"ape" to "ape atoll",
"apeatoll" to "ape atoll",
"tav" to "taverley",
"taverly" to "taverley",
"edge" to "edgeville",
"alkharid" to "al kharid",
"duel" to "duel arena",
"cw" to "castle wars",
"castlewars" to "castle wars",
"pc" to "pest control",
"pestcontrol" to "pest control",
"portsarim" to "port sarim",
"sarim" to "port sarim",
"relekka" to "rellekka"
)
// Named destinations that are not spell teleports, mapped to x, y, z
private val NAMED_LOCATIONS = mapOf(
"barrows" to Triple(3565, 3308, 0),
"taverley" to Triple(2896, 3428, 0),
"edgeville" to Triple(3088, 3500, 0),
"al kharid" to Triple(3293, 3174, 0),
"karamja" to Triple(2911, 3152, 0),
"draynor" to Triple(3103, 3249, 0),
"duel arena" to Triple(3313, 3234, 0),
"castle wars" to Triple(2441, 3090, 0),
"pest control" to Triple(2659, 2676, 0),
"port sarim" to Triple(3041, 3202, 0),
"rellekka" to Triple(2620, 3686, 0),
"brimhaven" to Triple(2772, 3234, 0),
"entrana" to Triple(2834, 3335, 0),
"zanaris" to Triple(2452, 4470, 0)
)
private val VALID_CITIES_MESSAGES = listOf(
"Valid destinations:",
"Modern: varrock, lumbridge (lumby), falador (fally), camelot (cammy),",
" ardougne (ardy), watchtower, trollheim, ape atoll (ape)",
"Ancient: paddewwa, senntisten, kharyll, lassar,",
" dareeyak, carrallangar, annakarl, ghorrock",
"Other: barrows, taverley (tav), edgeville (edge), al kharid, karamja,",
" draynor, duel arena (duel), castle wars (cw), pest control (pc),",
" port sarim, rellekka, brimhaven, entrana, zanaris"
)
}
override fun test(event: AdminCommandEvent): Boolean =
event.name.equals("teleport", ignoreCase = true) || event.name.equals("tele", ignoreCase = true)
override fun subscribe(context: EventContext, player: Player?, event: AdminCommandEvent) {
if (player == null) return
context.breakSubscriberChain()
val rawArguments = event.arguments
if (rawArguments.isEmpty()) {
player.packetSender.sendMessage("Usage: ::teleport <x> <y> [z] or ::teleport <city>")
player.packetSender.sendMessage("Examples: ::teleport 3222 3218 0 or ::teleport varrock")
return
}
val arguments = rawArguments.map { it.trimEnd(',') }
val x = arguments[0].toIntOrNull()
if (x == null) {
val normalized = arguments.joinToString(" ").lowercase().replace('_', ' ').replace('-', ' ').trim()
val resolvedCity = CITY_ALIASES[normalized] ?: normalized
val namedLocation = NAMED_LOCATIONS[resolvedCity]
if (namedLocation != null) {
val (destX, destY, destZ) = namedLocation
val displayName = resolvedCity.split(" ").joinToString(" ") { it.replaceFirstChar(Char::titlecase) }
teleport(player, destX, destY, destZ, player.playerMagicBook == 1)
player.packetSender.sendMessage("Teleporting to $displayName...")
return
}
val city = CITIES[resolvedCity]
if (city == null) {
player.packetSender.sendMessage("Unknown city '$normalized'.")
VALID_CITIES_MESSAGES.forEach { player.packetSender.sendMessage(it) }
return
}
val isAncient = city.type.equals("ancient", ignoreCase = true)
val displayName = city.name.lowercase().replace('_', ' ').split(" ").joinToString(" ") { it.replaceFirstChar(Char::titlecase) }
teleport(player, city.destX, city.destY, city.destZ, isAncient)
player.packetSender.sendMessage("Teleporting to $displayName...")
return
}
val y = arguments.getOrNull(1)?.toIntOrNull()
if (y == null) {
player.packetSender.sendMessage("Must specify coordinates: ::teleport <x> <y> [z]")
return
}
val z = arguments.getOrNull(2)?.toIntOrNull() ?: player.heightLevel
val isAncient = player.playerMagicBook == 1
teleport(player, x, y, z, isAncient)
player.packetSender.sendMessage("Teleporting to $x, $y${if (z != 0) ", $z" else ""}...")
}
private fun teleport(player: Player, x: Int, y: Int, z: Int, isAncient: Boolean) {
if (player.isDead || player.teleTimer > 0) return
with(player) {
if (playerIndex > 0 || npcIndex > 0) {
combatAssistant.resetPlayerAttack()
}
if (clickedTree) {
clickedTree = false
}
stopMovement()
packetSender.closeAllWindows()
teleX = x
teleY = y
npcIndex = 0
playerIndex = 0
faceUpdate(0)
refresh = heightLevel != z
teleHeight = z
isTeleporting = true
if (Constants.SOUND) {
packetSender.sendSound(SoundList.TELEPORT, 100, 700)
}
if (isAncient) {
startAnimation(ANIMATION_ANCIENT_START)
teleGfx = 0
teleTimer = TIMER_ANCIENT
teleEndAnimation = 0
gfx0(GFX_ANCIENT)
} else {
startAnimation(ANIMATION_MODERN_START, 10)
teleTimer = TIMER_MODERN
teleGfx = GFX_MODERN
teleEndAnimation = ANIMATION_MODERN_END
}
}
}
}
@@ -0,0 +1,97 @@
package plugin.commands.developer
import com.rs2.event.EventContext
import com.rs2.event.EventSubscriber
import com.rs2.event.SubscribesTo
import com.rs2.event.impl.DeveloperCommandEvent
import com.rs2.game.npcs.NPCDefinition
import com.rs2.game.players.Player
@SubscribesTo(DeveloperCommandEvent::class)
class SearchNpc : EventSubscriber<DeveloperCommandEvent> {
companion object {
/**
* Revision 377 maximum NPC ID (3,852 NPCs in cache: IDs 0..3851).
*/
private const val MAX_NPC_ID = 3851
private const val INTERFACE_ID = 8134
private const val TITLE_LINE_ID = 8144
private const val SUBTITLE_LINE_ID = 8145
private const val MAX_SCROLL_LINES = 199
private val CLEAR_RANGES = arrayOf(8146..8195, 12174..12223, 14945..15044)
private fun showResults(player: Player, query: String, results: List<String>) {
for (range in CLEAR_RANGES) {
for (i in range) {
player.packetSender.sendString("", i)
}
}
player.packetSender.sendString("@dre@NPC Search: \"$query\"", TITLE_LINE_ID)
val total = results.size
val subtitle = if (total > MAX_SCROLL_LINES) {
"Showing first $MAX_SCROLL_LINES of $total matches (refine search for more)"
} else {
"$total match${if (total == 1) "" else "es"} found"
}
player.packetSender.sendString(subtitle, SUBTITLE_LINE_ID)
val display = results.take(MAX_SCROLL_LINES)
for ((index, line) in display.withIndex()) {
val lineId = when {
index < 49 -> 8147 + index
index < 99 -> 12174 + (index - 49)
else -> 14945 + (index - 99)
}
player.packetSender.sendString(line, lineId)
}
player.packetSender.showInterface(INTERFACE_ID)
}
}
override fun test(event: DeveloperCommandEvent): Boolean = when (event.name.lowercase()) {
"searchnpc", "npcsearch" -> true
else -> false
}
override fun subscribe(context: EventContext, player: Player?, event: DeveloperCommandEvent) {
if (player == null) return
context.breakSubscriberChain()
val arguments = event.arguments
if (arguments.isEmpty()) {
player.packetSender.sendMessage("Specify an NPC name or ID to search: ::searchnpc goblin or ::searchnpc 9")
return
}
val query = arguments.joinToString(" ").trim()
val searchId = query.toIntOrNull()
val results = ArrayList<String>()
for (id in 0..MAX_NPC_ID) {
try {
val def = NPCDefinition.forId(id) ?: continue
val defName = def.name ?: continue
if (defName.isEmpty() || defName.equals("null", ignoreCase = true) || defName.startsWith("NPC #")) continue
val matches = (searchId != null && id == searchId) || defName.contains(query, ignoreCase = true)
if (matches) {
val combatTag = if (def.combat > 0) " @yel@(Level: ${def.combat})@bla@" else ""
results.add("@bla@$defName$combatTag - ID: @blu@$id")
}
} catch (ignored: Exception) {
continue
}
}
if (results.isEmpty()) {
player.packetSender.sendMessage("No NPCs found matching: $query")
} else {
showResults(player, query, results)
}
}
}
@@ -0,0 +1,136 @@
package plugin.commands.developer
import com.rs2.Constants
import com.rs2.event.EventContext
import com.rs2.event.EventSubscriber
import com.rs2.event.SubscribesTo
import com.rs2.event.impl.DeveloperCommandEvent
import com.rs2.game.players.Player
import com.rs2.game.players.PlayerAssistant
@SubscribesTo(DeveloperCommandEvent::class)
class SetLevel : EventSubscriber<DeveloperCommandEvent> {
companion object {
private val COMMAND_NAMES = setOf("setlevel", "level", "skill")
private val SKILL_NAMES = listOf(
"Attack",
"Defence",
"Strength",
"Hitpoints",
"Ranged",
"Prayer",
"Magic",
"Cooking",
"Woodcutting",
"Fletching",
"Fishing",
"Firemaking",
"Crafting",
"Smithing",
"Mining",
"Herblore",
"Agility",
"Thieving",
"Slayer",
"Farming",
"Runecrafting"
)
private val SKILL_IDS_BY_NAME = mapOf(
"attack" to Constants.ATTACK,
"att" to Constants.ATTACK,
"atk" to Constants.ATTACK,
"defence" to Constants.DEFENCE,
"defense" to Constants.DEFENCE,
"def" to Constants.DEFENCE,
"strength" to Constants.STRENGTH,
"str" to Constants.STRENGTH,
"hitpoints" to Constants.HITPOINTS,
"hitpoint" to Constants.HITPOINTS,
"hp" to Constants.HITPOINTS,
"ranged" to Constants.RANGED,
"range" to Constants.RANGED,
"rng" to Constants.RANGED,
"prayer" to Constants.PRAYER,
"pray" to Constants.PRAYER,
"magic" to Constants.MAGIC,
"mage" to Constants.MAGIC,
"cooking" to Constants.COOKING,
"cook" to Constants.COOKING,
"woodcutting" to Constants.WOODCUTTING,
"wc" to Constants.WOODCUTTING,
"fletching" to Constants.FLETCHING,
"fletch" to Constants.FLETCHING,
"fishing" to Constants.FISHING,
"fish" to Constants.FISHING,
"firemaking" to Constants.FIREMAKING,
"fm" to Constants.FIREMAKING,
"crafting" to Constants.CRAFTING,
"craft" to Constants.CRAFTING,
"smithing" to Constants.SMITHING,
"smith" to Constants.SMITHING,
"mining" to Constants.MINING,
"mine" to Constants.MINING,
"herblore" to Constants.HERBLORE,
"herb" to Constants.HERBLORE,
"agility" to Constants.AGILITY,
"agil" to Constants.AGILITY,
"thieving" to Constants.THIEVING,
"thief" to Constants.THIEVING,
"slayer" to Constants.SLAYER,
"slay" to Constants.SLAYER,
"farming" to Constants.FARMING,
"farm" to Constants.FARMING,
"runecrafting" to Constants.RUNECRAFTING,
"runecraft" to Constants.RUNECRAFTING,
"rc" to Constants.RUNECRAFTING
)
private fun resolveSkillId(rawSkill: String): Int? {
val numeric = rawSkill.toIntOrNull()
if (numeric != null) {
return if (numeric in SKILL_NAMES.indices) numeric else null
}
val normalized = rawSkill.lowercase().replace(" ", "").replace("_", "").replace("-", "")
return SKILL_IDS_BY_NAME[normalized]
}
}
override fun test(event: DeveloperCommandEvent): Boolean =
COMMAND_NAMES.contains(event.name.lowercase())
override fun subscribe(context: EventContext, player: Player?, event: DeveloperCommandEvent) {
if (player == null) return
context.breakSubscriberChain()
val arguments = event.arguments
if (arguments.size < 2) {
player.packetSender.sendMessage("Usage: ::setlevel <skillId|skillName> <level>")
player.packetSender.sendMessage("Examples: ::setlevel 1 99 or ::setlevel attack 99")
return
}
val level = arguments.last().toIntOrNull()
if (level == null) {
player.packetSender.sendMessage("Usage: ::setlevel <skillId|skillName> <level>")
return
}
val rawSkill = arguments.dropLast(1).joinToString(" ")
val skillId = resolveSkillId(rawSkill)
if (skillId == null) {
player.packetSender.sendMessage("Unknown skill '$rawSkill'. Valid IDs: 0-${SKILL_NAMES.lastIndex} (e.g. attack, hitpoints, herblore, rc).")
return
}
val clampedLevel = level.coerceIn(1, 99)
player.playerXP[skillId] = PlayerAssistant.getXPForLevel(clampedLevel) + 5
player.playerLevel[skillId] = PlayerAssistant.getLevelForXP(player.playerXP[skillId])
player.playerAssistant.refreshSkill(skillId)
player.playerAssistant.levelUp(skillId)
player.packetSender.sendMessage("Set your ${SKILL_NAMES[skillId]} level to $clampedLevel.")
}
}
Loaded 100 of 360 files, more files were not shown because too many files have changed in this diff. Show more