Compare commits

..
10 Commits
Author SHA1 Message Date
Dark98 ef7eca97e3 fix(web): support minimap bezel overlay, HTTPS /ws/ proxy routing, dynamic WS buffer, and VirtualFile cache fallback
Updates the TeaVM web client to render the 249x156 minimap bezel overlay cleanly, route WebSockets through same-origin /ws/<port> on HTTPS, dynamically grow WebSocket receive buffers, and fall back to preloaded VirtualFile cache data.

### Core / System Architecture
- `DesktopHooks.java`:
  - Added `setModernMinimapOverlay(int[])` reference-cached pixel conversion for the 249x156 minimap bezel overlay and `hasCachedMainDat(String)` checking `Signlink.cache_dat.length() > 0`.
- `Signlink.java`:
  - Routed `opensocket(int)` on `https://` origins through `wss://<window.location.host>/ws/<wsPort>` while keeping `ws://<host>:<wsPort>/` on `http://`.
- `WebLauncher.java`, `index.html`:
  - Removed the hardcoded `192.168.1.88` server override so the client defaults cleanly to `ClientSettings.SERVER_IP` (`server.2006scape.org`).

### Bug Fixes & Edge Cases
- `WebSocketAdapter.java`:
  - Replaced the fixed `262144`-byte ring buffer with a dynamically growing ring buffer (up to 32 MB) synchronized on `rxLock` to prevent truncation on large transfers.
2026-12-05 02:33:57 +00:00
Dark98 2dfee296e4 feat(web): add localStorage browser/editor modal and arrow-key modal navigation
Adds an in-browser LocalStorage Browser & Editor modal with live hot-reload for plugin configs and scripts, consolidates file importing into the Storage modal, and forwards arrow keys while Plugin Hub text inputs are focused.

### Storage Browser & Editor
- `index.html`:
  - Added `#btn-storage` in `#rs-footer` and the `#storage-modal` split-pane browser/editor UI with key filtering, `+ New` script/key creation, `Download`, `Delete`, `Save`, and `Save & Reload`.
  - Moved `#script-upload` into `#storage-modal` as `#storage-import` (`Import File`), auto-selecting imported `2006scape_script_*` files and refreshing the sidebar and live runtime.
- `WebLauncher.java`:
  - Registered `window.scapeReloadStorage` via `registerStorageReload()` to invoke `PluginManager.reloadStorage()` on the client thread.

### Input Handling
- `RSApplet.java`:
  - Queued Left (`1`) and Right (`2`) arrow keys into `charQueue` when `PluginPanelUI.isSearchFocused()` is true.
2026-12-02 18:25:43 +00:00
Dark98 e57315b785 feat(web): add Pause in Background option, TeaVM reflection filtering, and HUD drawImage guards
Improve webclient stability, background resource usage, and script reflection compatibility across desktop and mobile browsers.

### Web Client Features & Fixes
- `index.html` & `RSApplet.java`
  - Added a **Pause in Background** (`#opt-pause-bg`) option under **Display & Graphics** persisted in `localStorage` (`2006scape_web_options.pauseInBackground`) and synced live via `window.scapePauseInBackground`.
  - Added `visibilitychange` Web Audio suspend/resume handling in `index.html` and `isPausedInBackground()` loop throttling in `RSApplet.run()` (resetting timing buffers on resume to avoid tick bursts).
- `DesktopHooks.java`
  - Added `naturalWidth > 0` guards to `jsDrawModernMinimap` and `jsDrawModernChat` to prevent `InvalidStateError` on `drawImage` when HUD images are still loading or broken.

### TeaVM Script Reflection
- `WebReflectionSupplier.java`
  - Added `hasUnscriptableParam(...)` to exclude methods referencing `java.util.function.*`, `java.lang.Thread*`, `java.io.*`, or `java.awt.*` from TeaVM reflection metadata.
2026-12-02 17:20:27 +00:00
Dark98 ea04dfe196 feat(web): whitelist StringBuilder, LinkedHashMap, HashSet, and Set in WebReflectionSupplier
Expose `StringBuilder` and additional `java.util` collection/map types to TeaVM reflection so scripts constructing them via `new` work in `2006Scape-Web`.

### TeaVM Script Reflection
- `WebReflectionSupplier.java`
  - Added `java.lang.StringBuilder` (`append`, `toString`, `length`, `setLength`, `charAt`, `insert`, `delete`) and `java.util.LinkedHashMap`, `java.util.HashSet`, `java.util.Set` to `getAccessibleMethods`.
2026-12-02 01:56:04 +00:00
Dark98 f08736d2df feat(web): align Web audio/clipboard/screenshot hooks and reflection whitelist with Desktop and Android
Bring `2006Scape-Web` platform hooks and TeaVM reflection support in-line with the shared `2006Scape Client` and `2006Scape-Android` implementations.

### Platform Hooks & Web Audio
- `Class56_Sub1_Sub1.java` & `index.html`
  - Forwarded `boolean loop` from `method827` to `DesktopHooks.playMidiBytes(midiBytes, vol, loop)` and `window.scapeWebAudio.playMidi(bytes, volume, loop)` so FluidSynth honors `setPlayerLoop(loop ? -1 : 0)`.
  - Overrode `setLoop(boolean loop, boolean restartIfStopped)` to sync MIDI loop toggles immediately via `DesktopHooks.setMidiLoop` and `scapeWebAudio.setMidiLoop`.
- `DesktopHooks.java` & `index.html`
  - Added browser `paste` and `focus` (`navigator.clipboard.readText()`) tracking to `window.scapeClipboardText` and implemented ASCII `32..122` filtering in `DesktopHooks.getClipBoard()`.
  - Updated `takeScreenshot` to use `<username or SERVER_NAME>_<timestamp>.png` and send `"A picture has been downloaded."` to in-game chat when `sendMessage` is `true`.
  - Removed duplicate `ensureHudAssets()` call in `drawModernMinimap`.

### TeaVM Script Reflection
- `WebReflectionSupplier.java`
  - Added `WorldWebWalker` to `SCRIPTABLE_CLASSES` and expanded `isLangStr` (`lastIndexOf`, `charAt`, `split`) and `isUtilColl` (`set`, `indexOf`, `containsValue`, `keySet`, `values`).
2026-12-02 01:24:54 +00:00
Dark98 558243a3b7 fix(hd): sync web Client Options 317HD state with Plugin Hub 317 HD config
Keeps the webclient's Client Options modal (2006scape_web_options.hd), startup URL/option state, and Plugin Hub's plugin.317_HD.enabled property synchronized in both directions and at runtime.

### Web HD State Synchronization
- src/main/java/org/scape2006/web/WebLauncher.java:
  - Added syncHdStorageState(boolean) on startup when ?hd= or saved web options specify HD so plugin.317_HD.enabled in 2006scape_plugin_settings matches ClientSettings.HD_317 before PluginManager boots.
  - Registered window.scapeSetHd317 callback forwarding live HD toggles to game.setHD317Enabled(boolean).
- src/main/java/org/scape2006/web/DesktopHooks.java:
  - Added jsSyncWebOptionHdFromPluginConfig(String) in savePluginConfig(String) so toggling 317 HD in Plugin Hub or via ::hd updates 2006scape_web_options.hd in localStorage.
- src/main/webapp/index.html:
  - Updated saveOpts(applyLive) to mirror o.hd into plugin.317_HD.enabled in 2006scape_plugin_settings and invoke window.scapeSetHd317(o.hd) when saving live.
2026-12-02 00:36:05 +00:00
Dark98 6737a936df fix(audio): decode 8-bit PCM WAVs synchronously and preload FluidSynth assets
Eliminates per-sound async decodeAudioData latency and lazy SoundFont loading delays in the TeaVM webclient while preserving main-thread FluidSynth audio stability.

### Web Audio Pipeline
- src/main/webapp/index.html:
  - Added decodeWav8MonoSync(ctx, bytes) to decode 8-bit unsigned mono PCM WAVs from Sounds.java synchronously into an AudioBuffer with decodeAudioData fallback.
  - Added preloadFluidSynthAssets() on page load to initialize JSSynth and fetch TimGM6mb.sf2 before the first user gesture, and added midiPlaySeq cancellation across async playMidi() steps.
  - Configured AudioContext with { latencyHint: 'interactive' }, guarded playPcm() against suspended contexts, and kept FluidSynth ScriptProcessorNode at 4096 samples to avoid main-thread underruns.
- src/main/java/org/scape2006/web/DesktopHooks.java:
  - Skipped JS sound marshaling when vol <= 0.0f and forwarded delayMs to window.scapeWebAudio.playPcm(arr, vol, delayMs).
- src/main/webapp/sw.js:
  - Bumped CACHE_VERSION to 2006scape-web-v6 to invalidate stale cached web assets.
2026-12-02 00:28:48 +00:00
Dark98 02c3d8fb10 feat(web-audio): implement Class56 MIDI player with FluidSynth and TimGM6mb.sf2
Enables authentic General MIDI music playback in `2006Scape-Web` over both HTTP and HTTPS by implementing the missing `Class56_Sub1_Sub1` web adapter and wiring `js-synthesizer` (`libfluidsynth-2.3.0.js`) with the `TimGM6mb.sf2` SoundFont.

### Java MIDI Pipeline Bridge
- `Class56_Sub1_Sub1.java`:
  - Added `org.scape2006.web` implementation of `Class56` forwarding `method827`, `method828`, `method830`, `method831`, `method832`, and `method833` to `DesktopHooks.playMidiBytes`, `setSignlinkVolume`, and `stopSignlinkMidi`.
- `build.gradle`:
  - Patched `Game.constructMusic()` in `syncSharedSources` to instantiate `new Class56_Sub1_Sub1()` directly instead of `Class.forName("Class56_Sub1_Sub1").newInstance()`, preventing `musicIsntNull()` from returning `false`.

### FluidSynth Web Audio & Caching
- `src/main/webapp/libfluidsynth-2.3.0.js`, `js-synthesizer.min.js`, `TimGM6mb.sf2`:
  - Bundled FluidSynth WASM/JS synthesizer and General MIDI SoundFont (`5.8M`) locally for offline and plain-HTTP LAN compatibility.
- `src/main/webapp/index.html`:
  - Wired `window.scapeWebAudio` (`ensureFluidSynth`, `playMidi`, `setMidiVolume`, `stopMidi`) to load `TimGM6mb.sf2`, loop tracks via `setPlayerLoop(-1)`, and resume pending MIDI on first user gesture.
- `src/main/webapp/sw.js`:
  - Added `libfluidsynth-2.3.0.js`, `js-synthesizer.min.js`, and `TimGM6mb.sf2` to `SHELL_ASSETS` and bumped `CACHE_VERSION` to `2006scape-web-v5`.
2026-12-01 14:53:04 +00:00
Dark98 4bcb91c3a2 fix(web): fix Android Chrome black screen and Fixed-mode WebGL2 viewport scissor
Resolves the Android Chrome black screen after closing the welcome back interface and prevents Fixed-mode 317HD `gl.clear` from wiping surrounding HUD/border regions.

### WebGL2 Context & Fixed-Mode Scissoring
- `WebGL2.java`:
  - Enabled `preserveDrawingBuffer: true` and removed `desynchronized: true` on the `#gl-canvas` WebGL2 context to prevent Android Chrome from clearing or failing to composite between frames.
  - Added `SCISSOR_TEST` (`0x0C11`) and `scissor(x, y, width, height)` bindings.
- `WebHd317Renderer.java`:
  - Wrapped Pass 2 (`gl.clear` and 3D scene draw) in `GL_SCISSOR_TEST` (`gl.scissor(vpX, vpY, width, height)`) so Fixed-mode stone borders, chatbox, and tab areas are preserved.
  - Reused `HD317Pipeline.backend` in `ensureOverlayReady()` to avoid creating duplicate `WebHd317Renderer` instances.
- `RSImageProducer.java`:
  - Removed `desynchronized: true` from `#game-canvas`'s 2D context so Android Chrome composites `#game-canvas` transparently over `#gl-canvas`.

### Service Worker Caching
- `src/main/webapp/sw.js`:
  - Bumped `CACHE_VERSION` to `2006scape-web-v3` and switched `js/client.js` to network-first (with cache fallback) so client updates take effect immediately when online.
2026-11-30 22:41:05 +00:00
Dark98 ededb882a0 refactor(web): rename 117HD WebGL2 renderer and UI references to 317HD
Renames `WebHd117Renderer` and all remaining `117HD` symbols, build exclusions, and UI labels in `2006Scape-Web` to `317HD`.

### WebGL2 Renderer & Build
- `WebHd317Renderer.java`:
  - Renamed from `WebHd117Renderer.java` and updated class/log references to `WebHd317Renderer` / `317HD`.
- `build.gradle`, `WebLauncher.java`, `RSImageProducer.java`, `DesktopHooks.java`, `WebGL2.java`:
  - Updated `DesktopHd117Renderer.java` exclusion to `DesktopHd317Renderer.java` and updated pipeline/renderer call sites to `HD317Pipeline` and `WebHd317Renderer`.
- `src/main/webapp/index.html`:
  - Updated UI label from `117HD (WebGL2)` to `317HD (WebGL2)`.
2026-11-30 21:57:21 +00:00
16 changed files with 1024 additions and 133 deletions

No files matched your search

+2 -1
View File
@@ -41,7 +41,7 @@ def syncSharedSources = tasks.register('syncSharedSources') {
def excluded = [
'RSApplet.java', 'RSImageProducer.java', 'RSFrame.java',
'Main.java', 'LocalGame.java', 'Class56_Sub1_Sub1.java',
'DesktopHooks.java', 'AndroidHooks.java', 'DesktopHd117Renderer.java',
'DesktopHooks.java', 'AndroidHooks.java', 'DesktopHd317Renderer.java',
'SoundPlayer.java', 'Midi.java', 'Client.java',
'RSSocket.java', 'Signlink.java', 'Decompressor.java',
'ExternalPluginLoader.java'
@@ -56,6 +56,7 @@ def syncSharedSources = tasks.register('syncSharedSources') {
src = src.replace('java.net.InetSocketAddress', 'org.scape2006.web.net.InetSocketAddress')
if (element.name == 'Game.java') {
src = src.replace('Signlink.reporterror("glfc_ex "', 'Signlink.reporterror("glfc_ex " + _ex + " | "')
src = src.replace('(Class56) Class.forName("Class56_Sub1_Sub1").newInstance()', 'new Class56_Sub1_Sub1()')
}
dest.text = "package org.scape2006.web;\n" + src
}
@@ -0,0 +1,49 @@
package org.scape2006.web;
/**
* Web MIDI player implementation of Class56, bridging Game's music pipeline
* to DesktopHooks / window.scapeWebAudio (WebAudioTinySynth).
*/
public final class Class56_Sub1_Sub1 extends Class56 {
@Override
void method827(int volume, byte[] midiBytes, int unused, boolean loop) {
if (midiBytes != null && midiBytes.length > 0) {
DesktopHooks.playMidiBytes(midiBytes, volume, loop);
} else {
DesktopHooks.stopSignlinkMidi();
}
}
@Override
void setLoop(boolean loop, boolean restartIfStopped) {
DesktopHooks.setMidiLoop(loop, restartIfStopped);
}
@Override
void method828() {
DesktopHooks.stopSignlinkMidi();
}
@Override
void method830(int volume, int fade) {
DesktopHooks.setSignlinkVolume(volume);
}
@Override
void method831(int volume) {
DesktopHooks.setSignlinkVolume(volume);
}
@Override
void method832(int i) {
if (i > -90) {
DesktopHooks.stopSignlinkMidi();
}
}
@Override
void method833() {
DesktopHooks.stopSignlinkMidi();
}
}
+121 -28
View File
@@ -12,7 +12,7 @@ import org.teavm.jso.typedarrays.Uint8ClampedArray;
/**
* Web implementation of DesktopHooks for TeaVM.
* Bridges audio (Web Audio + SpessaSynth), clipboard, screenshots, and 117HD backend init.
* Bridges audio (Web Audio + SpessaSynth), clipboard, screenshots, and 317HD backend init.
*/
public final class DesktopHooks {
@@ -88,14 +88,28 @@ public final class DesktopHooks {
private static native void jsDecodeImage(Uint8Array bytes, ImageDecodeCallback cb);
public static String getClipBoard() {
return "";
String raw = jsGetClipboardText();
if (raw == null || raw.isEmpty()) return "";
StringBuilder out = new StringBuilder(raw.length());
for (int i = 0; i < raw.length(); i++) {
char c = raw.charAt(i);
if (c >= 32 && c <= 122) {
out.append(c);
}
}
return out.toString();
}
public static void takeScreenshot(Game game, boolean sendMessage, String... subfolders) {
ensureHudAssets();
HTMLCanvasElement canvas = RSImageProducer.getCanvas();
if (canvas != null) {
downloadCanvasPng(canvas, "2006scape_" + System.currentTimeMillis() + ".png");
String prefix = (game != null && game.myUsername != null && !game.myUsername.isEmpty())
? game.myUsername : ClientSettings.SERVER_NAME;
downloadCanvasPng(canvas, prefix + "_" + System.currentTimeMillis() + ".png");
if (sendMessage && game != null) {
game.pushMessage("A picture has been downloaded.", 0, "");
}
}
}
@@ -107,12 +121,13 @@ public final class DesktopHooks {
public static void playSound(byte[] buffer, int offset, int length, int level, int delay) {
if (buffer == null || length <= 0 || offset + length > buffer.length) return;
float vol = soundVolume * Math.max(0f, Math.min(1f, level / 100.0f));
if (vol <= 0.0f) return;
Uint8Array arr = Uint8Array.create(length);
for (int i = 0; i < length; i++) {
arr.set(i, (short) (buffer[offset + i] & 0xFF));
}
float vol = soundVolume * Math.max(0f, Math.min(1f, level / 100.0f));
jsPlayPcm(arr, vol);
jsPlayPcm(arr, vol, Math.max(0, delay));
}
public static void setSoundVolume(int config) {
@@ -136,11 +151,19 @@ public final class DesktopHooks {
}
public static void playMidiBytes(byte[] midiBytes, int vol) {
playMidiBytes(midiBytes, vol, true);
}
public static void playMidiBytes(byte[] midiBytes, int vol, boolean loop) {
if (midiBytes == null || midiBytes.length == 0) return;
midiVolume = Math.max(0.0f, Math.min(1.0f, vol / 255.0f));
Uint8Array arr = Uint8Array.create(midiBytes.length);
arr.set(midiBytes, 0);
jsPlayMidi(arr, midiVolume);
jsPlayMidi(arr, midiVolume, loop);
}
public static void setMidiLoop(boolean loop, boolean restartIfStopped) {
jsSetMidiLoop(loop, restartIfStopped);
}
public static boolean setSignlinkVolume(int vol) {
@@ -156,19 +179,52 @@ public final class DesktopHooks {
private static int[] modernTabPixels = null;
private static boolean[] modernTabMask = null;
private static boolean hudImagesRequested = false;
private static int[] modernMinimapOverlayPixels = null;
private static int[] lastModernMinimapOverlayRef = null;
private static Uint8ClampedArray cachedModernMinimapOverlayRgba = null;
public static void setModernMinimapOverlay(int[] overlay249x156) {
modernMinimapOverlayPixels = overlay249x156;
}
public static void drawModernMinimap(Object graphics, int[] minimapPixels, int windowWidth) {
if (minimapPixels == null || minimapPixels.length < 172 * 156) return;
ensureHudAssets();
ensureHudAssets();
HTMLCanvasElement canvas = RSImageProducer.getCanvas();
if (canvas == null) return;
Uint8ClampedArray rgba = toRgbaOpaque(minimapPixels, 172 * 156);
boolean toGpu = WebHd117Renderer.ensureOverlayReady();
HTMLCanvasElement hudC = jsDrawModernMinimap(canvas, rgba, windowWidth, !toGpu);
if (toGpu && hudC != null) {
WebHd117Renderer.drawHudCanvas(hudC, windowWidth - 249, 0, 249, 168);
int[] ov = modernMinimapOverlayPixels;
if (ov != lastModernMinimapOverlayRef) {
cachedModernMinimapOverlayRgba = (ov != null && ov.length >= 249 * 156)
? toRgbaWithSentinel(ov, 249 * 156, Game.MODERN_BEZEL_SENTINEL)
: null;
lastModernMinimapOverlayRef = ov;
}
boolean toGpu = WebHd317Renderer.ensureOverlayReady();
HTMLCanvasElement hudC = jsDrawModernMinimap(canvas, rgba, cachedModernMinimapOverlayRgba, windowWidth, !toGpu);
if (toGpu && hudC != null) {
WebHd317Renderer.drawHudCanvas(hudC, windowWidth - 249, 0, 249, 168);
}
}
private static Uint8ClampedArray toRgbaWithSentinel(int[] pixels, int len, int sentinel) {
Uint8ClampedArray out = Uint8ClampedArray.create(len * 4);
int idx = 0;
for (int i = 0; i < len; i++) {
int p = pixels[i];
if (p == sentinel || p == 0) {
out.set(idx++, 0);
out.set(idx++, 0);
out.set(idx++, 0);
out.set(idx++, 0);
} else {
out.set(idx++, (p >> 16) & 0xff);
out.set(idx++, (p >> 8) & 0xff);
out.set(idx++, p & 0xff);
out.set(idx++, 255);
}
}
return out;
}
public static void drawModernChat(Object graphics, int[] chatContentPixels, int[] chatButtonsPixels, int windowHeight) {
@@ -179,10 +235,10 @@ public final class DesktopHooks {
? toRgbaOpaque(chatContentPixels, 479 * 96) : null;
Uint8ClampedArray buttonsRgba = (chatButtonsPixels != null && chatButtonsPixels.length >= 496 * 50)
? toRgbaOpaque(chatButtonsPixels, 496 * 50) : null;
boolean toGpu = WebHd117Renderer.ensureOverlayReady();
boolean toGpu = WebHd317Renderer.ensureOverlayReady();
HTMLCanvasElement hudC = jsDrawModernChat(canvas, contentRgba, buttonsRgba, windowHeight, !toGpu);
if (toGpu && hudC != null) {
WebHd117Renderer.drawHudCanvas(hudC, 0, windowHeight - 165, 519, 165);
WebHd317Renderer.drawHudCanvas(hudC, 0, windowHeight - 165, 519, 165);
}
}
@@ -248,10 +304,10 @@ public final class DesktopHooks {
rgba.set(j + 3, (short) 0);
}
}
boolean toGpu = WebHd117Renderer.ensureOverlayReady();
boolean toGpu = WebHd317Renderer.ensureOverlayReady();
HTMLCanvasElement hudC = jsDrawModernTab(canvas, rgba, windowWidth - 249, windowHeight - 343, !toGpu);
if (toGpu && hudC != null) {
WebHd117Renderer.drawHudCanvas(hudC, windowWidth - 249, windowHeight - 343, 249, 343);
WebHd317Renderer.drawHudCanvas(hudC, windowWidth - 249, windowHeight - 343, 249, 343);
}
}
@@ -304,7 +360,7 @@ public final class DesktopHooks {
double minScale = Math.max(1.0, Math.max(765.0 / rawW, 503.0 / rawH));
int w = Math.max(765, (int) Math.round(rawW * minScale));
int h = Math.max(503, (int) Math.round(rawH * minScale));
boolean fullRes = "true".equalsIgnoreCase(getParameter("fullres")) || HD117Pipeline.isGpuActive();
boolean fullRes = "true".equalsIgnoreCase(getParameter("fullres")) || HD317Pipeline.isGpuActive();
if (!fullRes && w > 1280) {
w = 1280;
h = Math.max(503, (int) Math.round(rawH * (1280.0 / rawW)));
@@ -433,19 +489,24 @@ public final class DesktopHooks {
"};")
private static native void jsInitHudAssets();
@JSBody(params = {"canvas", "rgba", "winW", "draw2d"}, script =
"var h = window.scapeHud; if (!h || !h.minimapBezel.complete || !h.minimapHole.complete) return null;\n" +
@JSBody(params = {"canvas", "rgba", "overlayRgba", "winW", "draw2d"}, script =
"var h = window.scapeHud; if (!h || !h.minimapBezel.complete || h.minimapBezel.naturalWidth <= 0 || !h.minimapHole.complete || h.minimapHole.naturalWidth <= 0) return null;\n" +
"var id = h.mContentCtx.createImageData(172, 156); id.data.set(rgba); h.mContentCtx.putImageData(id, 0, 0);\n" +
"var g = h.mcCtx; g.clearRect(0, 0, 249, 168);\n" +
"g.globalCompositeOperation = 'source-over'; g.drawImage(h.mContent, 34, 4);\n" +
"g.globalCompositeOperation = 'destination-in'; g.drawImage(h.minimapHole, 0, 0);\n" +
"g.globalCompositeOperation = 'source-over'; g.drawImage(h.minimapBezel, 0, 0);\n" +
"if (overlayRgba) {\n" +
" if (!h.mOv) { h.mOv = document.createElement('canvas'); h.mOv.width = 249; h.mOv.height = 156; h.mOvCtx = h.mOv.getContext('2d'); }\n" +
" var oid = h.mOvCtx.createImageData(249, 156); oid.data.set(overlayRgba); h.mOvCtx.putImageData(oid, 0, 0);\n" +
" g.drawImage(h.mOv, 0, 4);\n" +
"}\n" +
"if (draw2d) canvas.getContext('2d').drawImage(h.mc, winW - 249, 0);\n" +
"return h.mc;")
private static native HTMLCanvasElement jsDrawModernMinimap(HTMLCanvasElement canvas, Uint8ClampedArray rgba, int winW, boolean draw2d);
private static native HTMLCanvasElement jsDrawModernMinimap(HTMLCanvasElement canvas, Uint8ClampedArray rgba, Uint8ClampedArray overlayRgba, int winW, boolean draw2d);
@JSBody(params = {"canvas", "contentRgba", "buttonsRgba", "winH", "draw2d"}, script =
"var h = window.scapeHud; if (!h || !h.chatFrame.complete) return null;\n" +
"var h = window.scapeHud; if (!h || !h.chatFrame.complete || h.chatFrame.naturalWidth <= 0) return null;\n" +
"var g = h.ccCtx; g.clearRect(0, 0, 519, 165);\n" +
"g.globalCompositeOperation = 'source-over'; g.drawImage(h.chatFrame, 0, 0);\n" +
"if (contentRgba) { var id1 = h.cContentCtx.createImageData(479, 96); id1.data.set(contentRgba); h.cContentCtx.putImageData(id1, 0, 0); g.drawImage(h.cContent, 17, 19); }\n" +
@@ -479,18 +540,25 @@ public final class DesktopHooks {
private static native void jsRedrawScaledLogin(HTMLCanvasElement canvas, int winW, int winH, int dx, int dy, int dw, int dh);
public static void initHdBackend() {
if (HD117Pipeline.backend == null) {
HD117Pipeline.backend = new WebHd117Renderer();
if (HD317Pipeline.backend == null) {
HD317Pipeline.backend = new WebHd317Renderer();
}
}
@JSBody(params = {"arr", "vol"}, script =
"if (window.scapeWebAudio && window.scapeWebAudio.playPcm) window.scapeWebAudio.playPcm(arr, vol);")
private static native void jsPlayPcm(Uint8Array arr, float vol);
@JSBody(params = {"arr", "vol", "delayMs"}, script =
"if (window.scapeWebAudio && window.scapeWebAudio.playPcm) window.scapeWebAudio.playPcm(arr, vol, delayMs);")
private static native void jsPlayPcm(Uint8Array arr, float vol, int delayMs);
@JSBody(params = {"arr", "vol"}, script =
"if (window.scapeWebAudio && window.scapeWebAudio.playMidi) window.scapeWebAudio.playMidi(arr, vol);")
private static native void jsPlayMidi(Uint8Array arr, float vol);
@JSBody(params = {"arr", "vol", "loop"}, script =
"if (window.scapeWebAudio && window.scapeWebAudio.playMidi) window.scapeWebAudio.playMidi(arr, vol, loop);")
private static native void jsPlayMidi(Uint8Array arr, float vol, boolean loop);
@JSBody(params = {"loop", "restartIfStopped"}, script =
"if (window.scapeWebAudio && window.scapeWebAudio.setMidiLoop) window.scapeWebAudio.setMidiLoop(loop, restartIfStopped);")
private static native void jsSetMidiLoop(boolean loop, boolean restartIfStopped);
@JSBody(script = "return window.scapeClipboardText || '';")
private static native String jsGetClipboardText();
@JSBody(params = {"vol"}, script =
"if (window.scapeWebAudio && window.scapeWebAudio.setMidiVolume) window.scapeWebAudio.setMidiVolume(vol);")
@@ -572,6 +640,7 @@ public final class DesktopHooks {
public static boolean savePluginConfig(String content) {
if (content == null) return false;
jsSavePluginConfig(content);
jsSyncWebOptionHdFromPluginConfig(content);
return true;
}
@@ -582,6 +651,22 @@ public final class DesktopHooks {
"if (window.localStorage) window.localStorage.setItem('2006scape_plugin_settings', content);")
private static native void jsSavePluginConfig(String content);
@JSBody(params = {"content"}, script =
"try {\n" +
" if (!window.localStorage || !content) return;\n" +
" var m = content.match(/(?:^|\\r?\\n)plugin\\.317_HD\\.enabled\\s*=\\s*(true|false)/i);\n" +
" if (!m) return;\n" +
" var hdEnabled = m[1].toLowerCase() === 'true';\n" +
" var raw = window.localStorage.getItem('2006scape_web_options');\n" +
" var opts = raw ? JSON.parse(raw) : {};\n" +
" if (!opts || typeof opts !== 'object') opts = {};\n" +
" if (opts.hd !== hdEnabled) {\n" +
" opts.hd = hdEnabled;\n" +
" window.localStorage.setItem('2006scape_web_options', JSON.stringify(opts));\n" +
" }\n" +
"} catch (_) {}")
private static native void jsSyncWebOptionHdFromPluginConfig(String content);
public static void yieldUi() {
try {
Thread.sleep(1L);
@@ -625,6 +710,14 @@ public final class DesktopHooks {
return v;
}
public static boolean hasCachedMainDat(String cacheDir) {
try {
return Signlink.cache_dat != null && Signlink.cache_dat.length() > 0;
} catch (Throwable ignored) {
return false;
}
}
@JSBody(params = {"v"}, script = "return v === undefined || v === null;")
private static native boolean jsIsUndefined(JSObject v);
+16 -1
View File
@@ -594,6 +594,18 @@ public class RSApplet implements Runnable {
}
while (anInt4 >= 0) {
if (isPausedInBackground()) {
try {
Thread.sleep(250);
} catch (InterruptedException ignored) {}
long resetNow = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
aLongArray7[i] = resetNow;
}
count = 0;
continue;
}
if (anInt4 > 0) {
anInt4--;
if (anInt4 == 0) {
@@ -705,7 +717,7 @@ public class RSApplet implements Runnable {
if (ch > 0 && ch < 128) {
keyArray[ch] = 1;
}
if (ch > 4) {
if (ch > 4 || ((ch == 1 || ch == 2) && PluginPanelUI.isSearchFocused())) {
charQueue[writeIndex] = ch;
writeIndex = (writeIndex + 1) & 0x7f;
}
@@ -844,6 +856,9 @@ public class RSApplet implements Runnable {
return DesktopHooks.getParameter(s);
}
@JSBody(script = "return !!(window.scapePauseInBackground && document.hidden);")
private static native boolean isPausedInBackground();
@JSBody(params = {"we"}, script = "return !!(we && we.ctrlKey);")
private static native boolean isWheelCtrlKey(WheelEvent we);
@@ -55,7 +55,7 @@ public final class RSImageProducer {
}
@JSBody(params = {"canvas"}, script =
"try { return canvas.getContext('2d', { alpha: true, desynchronized: true }) || canvas.getContext('2d'); }\n" +
"try { return canvas.getContext('2d', { alpha: true }) || canvas.getContext('2d'); }\n" +
"catch (_) { return canvas.getContext('2d'); }")
private static native CanvasRenderingContext2D create2dContext(HTMLCanvasElement canvas);
@@ -81,13 +81,13 @@ public final class RSImageProducer {
}
ensureCanvas();
if (ctx2d == null) return;
boolean gpuViewport = HD117Pipeline.isGpuActive() && anInt316 == ClientSettings.VIEWPORT_WIDTH && anInt317 == ClientSettings.VIEWPORT_HEIGHT;
if (WebHd117Renderer.ensureOverlayReady()) {
boolean gpuViewport = HD317Pipeline.isGpuActive() && anInt316 == ClientSettings.VIEWPORT_WIDTH && anInt317 == ClientSettings.VIEWPORT_HEIGHT;
if (WebHd317Renderer.ensureOverlayReady()) {
if (!cleared2dForGpu && canvas != null) {
ctx2d.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
cleared2dForGpu = true;
}
WebHd117Renderer.drawHudPixels(anIntArray315, x, y, anInt316, anInt317, gpuViewport);
WebHd317Renderer.drawHudPixels(anIntArray315, x, y, anInt316, anInt317, gpuViewport);
return;
}
cleared2dForGpu = false;
+11 -2
View File
@@ -53,8 +53,14 @@ public final class Signlink {
host = "127.0.0.1";
}
}
String proto = isSecureOrigin() ? "wss://" : "ws://";
String url = proto + host + ":" + wsPort + "/";
if (isSecureOrigin()) {
String pageHost = getBrowserHost();
if (pageHost != null && !pageHost.isEmpty()) {
return new WebSocketAdapter("wss://" + pageHost + "/ws/" + wsPort);
}
return new WebSocketAdapter("wss://" + host + ":" + wsPort + "/");
}
String url = "ws://" + host + ":" + wsPort + "/";
return new WebSocketAdapter(url);
}
@@ -119,6 +125,9 @@ public final class Signlink {
// Nothing to close synchronously
}
@JSBody(script = "return window.location.host || '';")
private static native String getBrowserHost();
@JSBody(script = "return window.location.hostname || '127.0.0.1';")
private static native String getBrowserHostname();
+4 -2
View File
@@ -7,7 +7,7 @@ import org.teavm.jso.typedarrays.Float32Array;
import org.teavm.jso.typedarrays.Uint8Array;
/**
* TeaVM JSO bindings for WebGL 2.0 (OpenGL ES 3.0) used by WebHd117Renderer.
* TeaVM JSO bindings for WebGL 2.0 (OpenGL ES 3.0) used by WebHd317Renderer.
*/
public interface WebGL2 extends JSObject {
@@ -20,6 +20,7 @@ public interface WebGL2 extends JSObject {
int SRC_ALPHA = 0x0302;
int ONE_MINUS_SRC_ALPHA = 0x0303;
int DEPTH_TEST = 0x0B71;
int SCISSOR_TEST = 0x0C11;
int BLEND = 0x0BE2;
int POLYGON_OFFSET_FILL = 0x8037;
int FLOAT = 0x1406;
@@ -65,12 +66,13 @@ public interface WebGL2 extends JSObject {
interface UniformLocation extends JSObject {}
@JSBody(params = {"canvas"}, script =
"return canvas.getContext('webgl2', { alpha: false, antialias: false, preserveDrawingBuffer: false, powerPreference: 'high-performance', desynchronized: true });")
"return canvas.getContext('webgl2', { alpha: false, antialias: false, preserveDrawingBuffer: true, powerPreference: 'high-performance' });")
static WebGL2 getContext(HTMLCanvasElement canvas) {
return null;
}
void viewport(int x, int y, int width, int height);
void scissor(int x, int y, int width, int height);
void clearColor(float r, float g, float b, float a);
void clear(int mask);
void enable(int cap);
@@ -14,10 +14,10 @@ import java.nio.ByteOrder;
import java.util.Arrays;
/**
* WebGL 2.0 (GLSL ES 3.00) 117HD Hardware Renderer for 2006Scape-Web.
* Reuses HD117Pipeline shaders, HdSceneUploader, HdMaterial, and HdProceduralGenerator.
* WebGL 2.0 (GLSL ES 3.00) 317HD Hardware Renderer for 2006Scape-Web.
* Reuses HD317Pipeline shaders, HdSceneUploader, HdMaterial, and HdProceduralGenerator.
*/
public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
public final class WebHd317Renderer implements HD317Pipeline.HdRendererBackend {
private static final String OVERLAY_VERT =
"#version 300 es\n" +
@@ -39,7 +39,7 @@ public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
" fragColor = texture(uTex, vUv);\n" +
"}\n";
private static WebHd117Renderer instance = null;
private static WebHd317Renderer instance = null;
private int shadowMapSize = 1024;
private static final boolean IS_IOS = jsIsIos();
private final HdProceduralGenerator procGen = new HdProceduralGenerator();
@@ -144,7 +144,7 @@ public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
private ObjectManager lastObjectManager = null;
private WorldController lastWorldController = null;
public WebHd117Renderer() {
public WebHd317Renderer() {
instance = this;
float len = (float) Math.sqrt(sunDir[0] * sunDir[0] + sunDir[1] * sunDir[1] + sunDir[2] * sunDir[2]);
sunDir[0] /= len;
@@ -167,7 +167,7 @@ public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
sceneUploader.setSceneContext(procGen, worldController);
sceneLoaded = true;
} catch (Throwable t) {
System.err.println("[WebHd117Renderer] Error generating scene data: " + t.getMessage());
System.err.println("[WebHd317Renderer] Error generating scene data: " + t.getMessage());
}
}
@@ -272,8 +272,8 @@ public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
computeCameraAndLightMatrices(width, height);
selectActiveLights();
boolean shadowsOn = HD117Pipeline.cfgShadowsEnabled && !IS_IOS;
int desiredShadowSize = IS_IOS ? 512 : HD117Pipeline.cfgShadowResolution;
boolean shadowsOn = HD317Pipeline.cfgShadowsEnabled && !IS_IOS;
int desiredShadowSize = IS_IOS ? 512 : HD317Pipeline.cfgShadowResolution;
if (shadowsOn && desiredShadowSize != shadowMapSize &&
(desiredShadowSize == 512 || desiredShadowSize == 1024 || desiredShadowSize == 2048)) {
shadowMapSize = desiredShadowSize;
@@ -345,7 +345,7 @@ public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
gl.disable(WebGL2.POLYGON_OFFSET_FILL);
}
// Pass 2: Main 117HD Scene directly onto #gl-canvas default framebuffer (zero readPixels!)
// Pass 2: Main 317HD Scene directly onto #gl-canvas default framebuffer (zero readPixels!)
int targetCanvasW = ClientSettings.isDesktopModern() ? width : 765;
int targetCanvasH = ClientSettings.isDesktopModern() ? height : 503;
if (glCanvas.getWidth() != targetCanvasW || glCanvas.getHeight() != targetCanvasH
@@ -358,6 +358,8 @@ public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
int vpY = ClientSettings.isDesktopModern() ? 0 : Math.max(0, canvasH - 4 - height);
gl.bindFramebuffer(WebGL2.FRAMEBUFFER, null);
gl.viewport(vpX, vpY, width, height);
gl.enable(WebGL2.SCISSOR_TEST);
gl.scissor(vpX, vpY, width, height);
gl.clearColor(fogColor[0], fogColor[1], fogColor[2], 1.0f);
gl.clear(WebGL2.COLOR_BUFFER_BIT | WebGL2.DEPTH_BUFFER_BIT);
gl.enable(WebGL2.DEPTH_TEST);
@@ -382,18 +384,18 @@ public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
gl.uniform3f(uSceneAmbientColor, ambientColor[0], ambientColor[1], ambientColor[2]);
gl.uniform3f(uSceneSkyColor, skyColor[0], skyColor[1], skyColor[2]);
gl.uniform3f(uSceneFogColor, fogColor[0], fogColor[1], fogColor[2]);
gl.uniform1f(uSceneFogMin, HD117Pipeline.cfgAtmosphericFog ? fogMin : 999999.0f);
gl.uniform1f(uSceneFogMax, HD117Pipeline.cfgAtmosphericFog ? fogMax : 1000000.0f);
gl.uniform1f(uSceneFogMin, HD317Pipeline.cfgAtmosphericFog ? fogMin : 999999.0f);
gl.uniform1f(uSceneFogMax, HD317Pipeline.cfgAtmosphericFog ? fogMax : 1000000.0f);
gl.uniform1f(uSceneTime, (System.currentTimeMillis() - startTimeMs) * 0.001f);
gl.uniform1f(uSceneShadowTexelSize, 1.0f / shadowMapSize);
gl.uniform1i(uSceneShadowsEnabled, shadowsOn ? 1 : 0);
gl.uniform1i(uSceneShadowSoftPcf, HD117Pipeline.cfgShadowSoftPcf ? 1 : 0);
gl.uniform1i(uSceneGroundTextures, HD117Pipeline.cfgGroundTextures ? 1 : 0);
gl.uniform1i(uSceneNormalMapping, HD117Pipeline.cfgNormalMapping ? 1 : 0);
gl.uniform1i(uSceneWaterShader, HD117Pipeline.cfgWaterShader ? 1 : 0);
gl.uniform1f(uSceneSaturation, HD117Pipeline.cfgSaturation);
gl.uniform1f(uSceneBrightness, HD117Pipeline.cfgBrightness);
gl.uniform1i(uSceneContrastCurve, HD117Pipeline.cfgContrastCurve ? 1 : 0);
gl.uniform1i(uSceneShadowSoftPcf, HD317Pipeline.cfgShadowSoftPcf ? 1 : 0);
gl.uniform1i(uSceneGroundTextures, HD317Pipeline.cfgGroundTextures ? 1 : 0);
gl.uniform1i(uSceneNormalMapping, HD317Pipeline.cfgNormalMapping ? 1 : 0);
gl.uniform1i(uSceneWaterShader, HD317Pipeline.cfgWaterShader ? 1 : 0);
gl.uniform1f(uSceneSaturation, HD317Pipeline.cfgSaturation);
gl.uniform1f(uSceneBrightness, HD317Pipeline.cfgBrightness);
gl.uniform1i(uSceneContrastCurve, HD317Pipeline.cfgContrastCurve ? 1 : 0);
gl.uniform1i(uSceneLightCount, activeLightCount);
if (activeLightCount > 0) {
@@ -466,12 +468,13 @@ public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
unbindSceneVertexAttribs();
}
gl.disable(WebGL2.SCISSOR_TEST);
if (!loggedFirstFrame) {
loggedFirstFrame = true;
int err = getGlError(gl);
if (err != 0) {
RSApplet.appendLog("[WebHd117Renderer] glErr=" + err);
RSApplet.appendLog("[WebHd317Renderer] glErr=" + err);
}
}
// Clear dstPixels to sentinel 0x010203 (transparent) so 0x000000 black UI/shadows stay opaque on #game-canvas above #gl-canvas
@@ -630,9 +633,9 @@ public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
return false;
}
shadowProgram = createProgram(HD117Pipeline.SHADOW_VERT, HD117Pipeline.SHADOW_FRAG);
String sceneFragRgba = HD117Pipeline.SCENE_FRAG_DIRECT.replace("col.b, col.g, col.r", "col.r, col.g, col.b");
sceneProgram = createProgram(HD117Pipeline.SCENE_VERT, sceneFragRgba);
shadowProgram = createProgram(HD317Pipeline.SHADOW_VERT, HD317Pipeline.SHADOW_FRAG);
String sceneFragRgba = HD317Pipeline.SCENE_FRAG_DIRECT.replace("col.b, col.g, col.r", "col.r, col.g, col.b");
sceneProgram = createProgram(HD317Pipeline.SCENE_VERT, sceneFragRgba);
if (shadowProgram == null || sceneProgram == null) {
glFailed = true;
return false;
@@ -698,7 +701,7 @@ public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
glInitialized = true;
return true;
} catch (Throwable t) {
RSApplet.appendLog("[WebHd117Renderer] WebGL2 init failed: " + t);
RSApplet.appendLog("[WebHd317Renderer] WebGL2 init failed: " + t);
glFailed = true;
return false;
}
@@ -711,7 +714,14 @@ public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
public static boolean ensureOverlayReady() {
if (isOverlayReady()) return true;
if (instance == null) {
new WebHd117Renderer();
if (HD317Pipeline.backend instanceof WebHd317Renderer) {
instance = (WebHd317Renderer) HD317Pipeline.backend;
} else {
instance = new WebHd317Renderer();
if (HD317Pipeline.backend == null) {
HD317Pipeline.backend = instance;
}
}
}
return instance.ensureOverlayContext();
}
@@ -819,7 +829,7 @@ public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
gl.attachShader(prog, fs);
gl.linkProgram(prog);
if (!gl.getProgramParameter(prog, WebGL2.LINK_STATUS)) {
RSApplet.appendLog("[WebHd117Renderer] Link error: " + gl.getProgramInfoLog(prog));
RSApplet.appendLog("[WebHd317Renderer] Link error: " + gl.getProgramInfoLog(prog));
return null;
}
return prog;
@@ -834,7 +844,7 @@ public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
gl.shaderSource(shader, src);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, WebGL2.COMPILE_STATUS)) {
RSApplet.appendLog("[WebHd117Renderer] Shader error: " + gl.getShaderInfoLog(shader));
RSApplet.appendLog("[WebHd317Renderer] Shader error: " + gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
@@ -915,7 +925,7 @@ public final class WebHd117Renderer implements HD117Pipeline.HdRendererBackend {
private void selectActiveLights() {
activeLightCount = 0;
if (!HD117Pipeline.cfgDynamicLights) return;
if (!HD317Pipeline.cfgDynamicLights) return;
int total = procGen.sceneLightCount;
if (total <= 0) return;
@@ -7,7 +7,7 @@ import org.teavm.jso.typedarrays.Uint8Array;
/**
* TeaVM browser entrypoint for 2006Scape-Web.
* Preloads the 377 cache via IndexedDB / HTTP fetch, initializes 117HD WebGL2, and boots Game.
* Preloads the 377 cache via IndexedDB / HTTP fetch, initializes 317HD WebGL2, and boots Game.
*/
public final class WebLauncher {
@@ -37,8 +37,6 @@ public final class WebLauncher {
ClientSettings.SERVER_IP = serverParam;
} else if (!optServer.isEmpty()) {
ClientSettings.SERVER_IP = optServer;
} else {
ClientSettings.SERVER_IP = "192.168.1.88";
}
String wsPortParam = DesktopHooks.getParameter("wsPort");
if (!wsPortParam.isEmpty()) {
@@ -49,11 +47,17 @@ public final class WebLauncher {
String hdParam = DesktopHooks.getParameter("hd");
String optHd = getSavedOption("hd");
if ("true".equalsIgnoreCase(hdParam) || "1".equals(hdParam)) {
ClientSettings.HD_117 = true;
ClientSettings.HD_317 = true;
syncHdStorageState(true);
} else if ("false".equalsIgnoreCase(hdParam) || "0".equals(hdParam)) {
ClientSettings.HD_117 = false;
ClientSettings.HD_317 = false;
syncHdStorageState(false);
} else if ("true".equalsIgnoreCase(optHd)) {
ClientSettings.HD_117 = true;
ClientSettings.HD_317 = true;
syncHdStorageState(true);
} else if ("false".equalsIgnoreCase(optHd)) {
ClientSettings.HD_317 = false;
syncHdStorageState(false);
}
String resizeParam = DesktopHooks.getParameter("resize");
String optMode = getSavedOption("displayMode");
@@ -80,7 +84,7 @@ public final class WebLauncher {
// Keep desktop/mouse layout in browser; Signlink.mainapp non-null routes sockets via Signlink.opensocket()
ClientSettings.ANDROID = false;
Signlink.mainapp = new Object();
HD117Pipeline.useStaticScenery = true;
HD317Pipeline.useStaticScenery = true;
DesktopHooks.initHdBackend();
RSApplet.updateLoadingOverlay(10, "Loading 377 cache from IndexedDB / HTTP...");
@@ -107,6 +111,13 @@ public final class WebLauncher {
RSApplet.updateLoadingOverlay(100, "Starting 2006Scape...");
setStatusBadge("WS Port " + (overrideWsPort > 0 ? overrideWsPort : (ClientSettings.SERVER_WORLD == 1 ? 44594 : 44596 + ClientSettings.SERVER_WORLD)));
Game game = new Game();
registerHdToggle(enabled -> game.setHD317Enabled(enabled));
registerStorageReload(() -> {
PluginManager pm = PluginManager.get();
if (pm != null) {
pm.reloadStorage();
}
});
Game.server = ClientSettings.SERVER_IP;
if ("true".equalsIgnoreCase(getSavedOption("autoLogin"))) {
String u = getSavedOption("username");
@@ -147,6 +158,44 @@ public final class WebLauncher {
"if (window.scapeInitNavbar) window.scapeInitNavbar(visible, mainMenuUrl, worldMapUrl, manualUrl, rulesUrl);")
private static native void initNavbar(boolean visible, String mainMenuUrl, String worldMapUrl, String manualUrl, String rulesUrl);
@JSFunctor
public interface HdToggleCallback extends JSObject {
void onToggle(boolean enabled);
}
@JSBody(params = {"cb"}, script = "window.scapeSetHd317 = cb;")
private static native void registerHdToggle(HdToggleCallback cb);
@JSFunctor
public interface StorageReloadCallback extends JSObject {
void onReload();
}
@JSBody(params = {"cb"}, script = "window.scapeReloadStorage = cb;")
private static native void registerStorageReload(StorageReloadCallback cb);
@JSBody(params = {"enabled"}, script =
"try {\n" +
" if (!window.localStorage) return;\n" +
" var rawOpts = window.localStorage.getItem('2006scape_web_options');\n" +
" var opts = rawOpts ? JSON.parse(rawOpts) : {};\n" +
" if (!opts || typeof opts !== 'object') opts = {};\n" +
" opts.hd = !!enabled;\n" +
" window.localStorage.setItem('2006scape_web_options', JSON.stringify(opts));\n" +
" var props = window.localStorage.getItem('2006scape_plugin_settings') || '';\n" +
" var lines = props ? props.split(/\\r?\\n/) : [];\n" +
" var updated = false;\n" +
" for (var i = 0; i < lines.length; i++) {\n" +
" if (lines[i].indexOf('plugin.317_HD.enabled=') === 0) {\n" +
" lines[i] = 'plugin.317_HD.enabled=' + (!!enabled);\n" +
" updated = true;\n" +
" }\n" +
" }\n" +
" if (!updated) lines.push('plugin.317_HD.enabled=' + (!!enabled));\n" +
" window.localStorage.setItem('2006scape_plugin_settings', lines.filter(Boolean).join('\\n') + '\\n');\n" +
"} catch (_) {}")
private static native void syncHdStorageState(boolean enabled);
@JSBody(params = {"key"}, script =
"try {\n" +
" var raw = window.localStorage ? window.localStorage.getItem('2006scape_web_options') : null;\n" +
@@ -6,6 +6,7 @@ import org.teavm.model.ClassReader;
import org.teavm.model.FieldReader;
import org.teavm.model.MethodDescriptor;
import org.teavm.model.MethodReader;
import org.teavm.model.ValueType;
import java.util.ArrayList;
import java.util.Collection;
@@ -41,10 +42,12 @@ public final class WebReflectionSupplier implements ReflectionSupplier {
SCRIPTABLE_CLASSES.add(p + "PluginContext$PlayerQuery");
SCRIPTABLE_CLASSES.add(p + "PluginGraphics");
SCRIPTABLE_CLASSES.add(p + "PluginConfigItem");
SCRIPTABLE_CLASSES.add(p + "MenuEntry");
SCRIPTABLE_CLASSES.add(p + "ClientScript");
SCRIPTABLE_CLASSES.add(p + "ClientPlugin");
SCRIPTABLE_CLASSES.add(p + "ClientSettings");
SCRIPTABLE_CLASSES.add(p + "ScriptLogger");
SCRIPTABLE_CLASSES.add(p + "WorldWebWalker");
SCRIPTABLE_CLASSES.add(p + "Game");
SCRIPTABLE_CLASSES.add(p + "Player");
SCRIPTABLE_CLASSES.add(p + "NPC");
@@ -89,13 +92,15 @@ public final class WebReflectionSupplier implements ReflectionSupplier {
boolean isLangMath = "java.lang.Math".equals(className);
boolean isLangSys = "java.lang.System".equals(className);
boolean isLangStr = "java.lang.String".equals(className);
boolean isLangSb = "java.lang.StringBuilder".equals(className);
boolean isUtilColl = "java.util.List".equals(className) || "java.util.ArrayList".equals(className)
|| "java.util.Collection".equals(className) || "java.util.Map".equals(className)
|| "java.util.HashMap".equals(className)
|| "java.util.HashMap".equals(className) || "java.util.LinkedHashMap".equals(className)
|| "java.util.Set".equals(className) || "java.util.HashSet".equals(className)
|| "java.util.Collections$EmptyList".equals(className)
|| "java.util.Collections$SingletonList".equals(className)
|| "java.util.Arrays$ArrayList".equals(className);
if (!SCRIPTABLE_CLASSES.contains(className) && !isLangMath && !isLangSys && !isLangStr && !isUtilColl) {
if (!SCRIPTABLE_CLASSES.contains(className) && !isLangMath && !isLangSys && !isLangStr && !isLangSb && !isUtilColl) {
return Collections.emptyList();
}
ClassReader cls = context.getClassSource().get(className);
@@ -104,6 +109,7 @@ public final class WebReflectionSupplier implements ReflectionSupplier {
}
List<MethodDescriptor> methods = new ArrayList<>();
for (MethodReader m : cls.getMethods()) {
if (hasUnscriptableParam(m.getDescriptor())) continue;
String name = m.getName();
if (isLangSys) {
if (!"currentTimeMillis".equals(name) && !"nanoTime".equals(name)) continue;
@@ -116,15 +122,40 @@ public final class WebReflectionSupplier implements ReflectionSupplier {
if (!"length".equals(name) && !"equals".equals(name) && !"equalsIgnoreCase".equals(name)
&& !"contains".equals(name) && !"startsWith".equals(name) && !"endsWith".equals(name)
&& !"toLowerCase".equals(name) && !"toUpperCase".equals(name) && !"trim".equals(name)
&& !"substring".equals(name) && !"indexOf".equals(name) && !"replace".equals(name)
&& !"substring".equals(name) && !"indexOf".equals(name) && !"lastIndexOf".equals(name)
&& !"replace".equals(name) && !"charAt".equals(name) && !"split".equals(name)
&& !"isEmpty".equals(name) && !"valueOf".equals(name)) continue;
} else if (isLangSb) {
if (!"append".equals(name) && !"toString".equals(name) && !"length".equals(name)
&& !"setLength".equals(name) && !"charAt".equals(name)
&& !"insert".equals(name) && !"delete".equals(name)) continue;
} else if (isUtilColl) {
if (!"size".equals(name) && !"isEmpty".equals(name) && !"get".equals(name)
&& !"add".equals(name) && !"remove".equals(name) && !"clear".equals(name)
&& !"contains".equals(name) && !"containsKey".equals(name) && !"put".equals(name)) continue;
&& !"set".equals(name) && !"add".equals(name) && !"remove".equals(name)
&& !"clear".equals(name) && !"contains".equals(name) && !"indexOf".equals(name)
&& !"containsKey".equals(name) && !"containsValue".equals(name)
&& !"put".equals(name) && !"keySet".equals(name) && !"values".equals(name)) continue;
}
methods.add(m.getDescriptor());
}
return methods;
}
private static boolean hasUnscriptableParam(MethodDescriptor desc) {
ValueType[] params = desc.getParameterTypes();
for (int i = 0; i < params.length; i++) {
ValueType vt = params[i];
while (vt instanceof ValueType.Array) {
vt = ((ValueType.Array) vt).getItemType();
}
if (vt instanceof ValueType.Object) {
String clsName = ((ValueType.Object) vt).getClassName();
if (clsName.startsWith("java.util.function.") || clsName.startsWith("java.lang.Thread")
|| clsName.startsWith("java.io.") || clsName.startsWith("java.awt.")) {
return true;
}
}
}
return false;
}
}
@@ -21,10 +21,12 @@ import java.io.OutputStream;
*/
public final class WebSocketAdapter extends Socket {
private static final int BUFFER_CAPACITY = 262144; // 256 KB ring buffer
private static final int INITIAL_BUFFER_CAPACITY = 262144; // 256 KB initial ring buffer
private static final int MAX_BUFFER_CAPACITY = 32 * 1024 * 1024; // 32 MB cap for large archive transfers
private final WebSocket ws;
private final byte[] rxBuffer = new byte[BUFFER_CAPACITY];
private final Object rxLock = new Object();
private byte[] rxBuffer = new byte[INITIAL_BUFFER_CAPACITY];
private int rxHead = 0;
private int rxTail = 0;
private int rxCount = 0;
@@ -55,15 +57,30 @@ public final class WebSocketAdapter extends Socket {
ArrayBuffer buf = (ArrayBuffer) data;
Uint8Array arr = Uint8Array.create(buf);
int len = arr.getLength();
synchronized (rxBuffer) {
synchronized (rxLock) {
int needed = rxCount + len;
if (needed > rxBuffer.length && rxBuffer.length < MAX_BUFFER_CAPACITY) {
int newCap = rxBuffer.length;
while (newCap < needed && newCap < MAX_BUFFER_CAPACITY) {
newCap = Math.min(MAX_BUFFER_CAPACITY, newCap * 2);
}
byte[] next = new byte[newCap];
for (int i = 0; i < rxCount; i++) {
next[i] = rxBuffer[(rxHead + i) % rxBuffer.length];
}
rxBuffer = next;
rxHead = 0;
rxTail = rxCount;
}
int cap = rxBuffer.length;
for (int i = 0; i < len; i++) {
if (rxCount >= BUFFER_CAPACITY) {
// Drop oldest byte on overflow to prevent lockup
rxHead = (rxHead + 1) % BUFFER_CAPACITY;
if (rxCount >= cap) {
// Drop oldest byte only if MAX_BUFFER_CAPACITY is exceeded
rxHead = (rxHead + 1) % cap;
rxCount--;
}
rxBuffer[rxTail] = (byte) arr.get(i);
rxTail = (rxTail + 1) % BUFFER_CAPACITY;
rxTail = (rxTail + 1) % cap;
rxCount++;
}
}
@@ -129,7 +146,7 @@ public final class WebSocketAdapter extends Socket {
private final class WsInputStream extends InputStream {
@Override
public int available() {
synchronized (rxBuffer) {
synchronized (rxLock) {
return rxCount;
}
}
@@ -137,10 +154,10 @@ public final class WebSocketAdapter extends Socket {
@Override
public int read() throws IOException {
while (true) {
synchronized (rxBuffer) {
synchronized (rxLock) {
if (rxCount > 0) {
int b = rxBuffer[rxHead] & 0xFF;
rxHead = (rxHead + 1) % BUFFER_CAPACITY;
rxHead = (rxHead + 1) % rxBuffer.length;
rxCount--;
return b;
}
@@ -160,12 +177,13 @@ public final class WebSocketAdapter extends Socket {
public int read(byte[] b, int off, int len) throws IOException {
if (len <= 0) return 0;
while (true) {
synchronized (rxBuffer) {
synchronized (rxLock) {
if (rxCount > 0) {
int toRead = Math.min(len, rxCount);
int cap = rxBuffer.length;
for (int i = 0; i < toRead; i++) {
b[off + i] = rxBuffer[rxHead];
rxHead = (rxHead + 1) % BUFFER_CAPACITY;
rxHead = (rxHead + 1) % cap;
rxCount--;
}
return toRead;
Binary file not shown.
+619 -40
View File
@@ -306,6 +306,157 @@
color: #fff3d6;
font-weight: 600;
}
#storage-modal {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.72);
display: none;
align-items: center;
justify-content: center;
z-index: 210;
padding: 12px;
}
#storage-modal.open { display: flex; }
.storage-card {
width: min(860px, 100%);
height: min(620px, 92dvh);
display: flex;
flex-direction: column;
background: #1d1a14;
border: 1px solid #594b34;
border-radius: 6px;
box-shadow: 0 14px 40px rgba(0, 0, 0, 0.75);
color: #d8cfa8;
font-size: 13px;
overflow: hidden;
}
.storage-body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: row;
}
.storage-sidebar {
width: 260px;
max-width: 42%;
border-right: 1px solid #3c3428;
display: flex;
flex-direction: column;
background: #171410;
}
.storage-toolbar {
display: flex;
gap: 6px;
padding: 8px;
border-bottom: 1px solid #2e2820;
}
.storage-toolbar input {
flex: 1;
min-width: 0;
background: #110f0c;
color: #eee2c0;
border: 1px solid #4e4230;
border-radius: 3px;
padding: 4px 7px;
font-size: 12px;
}
.storage-toolbar button, .storage-editor-bar button {
background: #2b251c;
color: #e6d5a8;
border: 1px solid #4e4230;
border-radius: 3px;
padding: 4px 8px;
cursor: pointer;
font-size: 11px;
white-space: nowrap;
}
.storage-list {
flex: 1;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
.storage-item {
padding: 7px 10px;
border-bottom: 1px solid #252019;
cursor: pointer;
display: flex;
flex-direction: column;
gap: 2px;
}
.storage-item:hover { background: #262119; }
.storage-item.active {
background: #332a1d;
border-left: 3px solid #f3c65f;
padding-left: 7px;
}
.storage-item-name {
color: #f0dfad;
font-weight: 600;
font-size: 12px;
word-break: break-all;
}
.storage-item-meta {
display: flex;
justify-content: space-between;
font-size: 10px;
color: #9e9170;
}
.storage-editor {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
padding: 8px 10px;
gap: 8px;
}
.storage-editor-bar {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.storage-key-input {
flex: 1;
min-width: 140px;
background: #110f0c;
color: #f3c65f;
border: 1px solid #4e4230;
border-radius: 3px;
padding: 5px 8px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
#storage-textarea {
flex: 1;
width: 100%;
min-height: 160px;
resize: none;
background: #110f0c;
color: #e9e0c6;
border: 1px solid #4e4230;
border-radius: 4px;
padding: 8px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
line-height: 1.45;
tab-size: 4;
}
#storage-status {
font-size: 11px;
color: #a99b76;
margin-right: auto;
}
@media (max-width: 640px) {
.storage-body { flex-direction: column; }
.storage-sidebar {
width: 100%;
max-width: 100%;
height: 36%;
border-right: 0;
border-bottom: 1px solid #3c3428;
}
.storage-toolbar input, .storage-key-input, #storage-textarea { font-size: 14px; }
}
</style>
</head>
<body>
@@ -339,8 +490,7 @@
<div>
<a id="btn-options" href="javascript:void(0)" title="Configure auto-login, server, and graphics">Options</a>
|
<label for="script-upload" title="Import .script / .bsh / .java into browser storage">Import Script</label>
<input id="script-upload" type="file" accept=".script,.bsh,.java" multiple style="display:none" />
<a id="btn-storage" href="javascript:void(0)" title="Browse and edit browser localStorage (plugin configs, scripts, options)">Storage</a>
</div>
<div class="legal">
RuneScape is a registered trademark of Jagex Limited in the United Kingdom and other countries.<br />
@@ -383,7 +533,7 @@
<div class="opt-group-title">Server &amp; World</div>
<label class="opt-row">
<span>Server Host</span>
<input id="opt-server" type="text" placeholder="192.168.1.88" />
<input id="opt-server" type="text" placeholder="server.2006scape.org" />
</label>
<label class="opt-row">
<span>World</span>
@@ -393,7 +543,7 @@
<div class="opt-group">
<div class="opt-group-title">Display &amp; Graphics</div>
<label class="opt-row">
<span>117HD (WebGL2)</span>
<span>317HD (WebGL2)</span>
<input id="opt-hd" type="checkbox" />
</label>
<label class="opt-row">
@@ -408,6 +558,10 @@
<span>Show Classic Navbar</span>
<input id="opt-navbar" type="checkbox" />
</label>
<label class="opt-row">
<span>Pause in Background</span>
<input id="opt-pause-bg" type="checkbox" />
</label>
</div>
</div>
<div class="options-footer">
@@ -418,60 +572,253 @@
</form>
</div>
<div id="storage-modal">
<div class="storage-card">
<div class="options-header">
<span>LocalStorage Browser &amp; Editor</span>
<button id="storage-close" type="button">&times;</button>
</div>
<div class="storage-body">
<div class="storage-sidebar">
<div class="storage-toolbar">
<input id="storage-filter" type="text" placeholder="Filter keys..." />
<button id="storage-new" type="button" title="Create new script or storage key">+ New</button>
<button id="storage-refresh" type="button" title="Refresh key list">&#x21bb;</button>
</div>
<div id="storage-list" class="storage-list"></div>
</div>
<div class="storage-editor">
<div class="storage-editor-bar">
<input id="storage-key" class="storage-key-input" type="text" placeholder="Select or enter localStorage key..." />
<button id="storage-download" type="button">Download</button>
<button id="storage-delete" type="button">Delete</button>
</div>
<textarea id="storage-textarea" spellcheck="false" placeholder="Select a file from localStorage or click + New..."></textarea>
</div>
</div>
<div class="options-footer">
<span id="storage-status">Ready</span>
<button id="storage-import" type="button" title="Import .script / .bsh / .java into browser storage">Import File</button>
<input id="script-upload" type="file" accept=".script,.bsh,.java" multiple style="display:none" />
<button id="storage-cancel" type="button">Close</button>
<button id="storage-save" type="button">Save</button>
<button id="storage-save-reload" type="button" class="primary">Save &amp; Reload</button>
</div>
</div>
</div>
<!-- Web Audio + Cache Preloader (must run synchronously before client.js main()) -->
<script src="libfluidsynth-2.3.0.js"></script>
<script src="js-synthesizer.min.js"></script>
<script>
window.scapeWebAudio = {
ctx: null,
midiGain: 0.7,
synth: null,
sequencer: null,
synthNode: null,
synthLoading: null,
synthAssetsLoading: null,
synthReady: false,
pendingMidi: null,
midiPlaySeq: 0,
ensureCtx() {
if (!this.ctx) {
const AudioCtx = window.AudioContext || window.webkitAudioContext;
if (AudioCtx) this.ctx = new AudioCtx();
if (AudioCtx) {
try {
this.ctx = new AudioCtx({ latencyHint: 'interactive' });
} catch (_) {
this.ctx = new AudioCtx();
}
}
}
if (this.ctx && this.ctx.state === 'suspended') {
this.ctx.resume().catch(() => {});
this.ctx.resume().then(() => {
if (this.pendingMidi && this.synthReady && this.ctx && this.ctx.state === 'running') {
const pending = this.pendingMidi;
this.pendingMidi = null;
this.playMidi(pending, this.midiGain, this.midiLoop);
}
}).catch(() => {});
}
return this.ctx;
},
playPcm(bytes, volume) {
preloadFluidSynthAssets() {
if (this.synthAssetsLoading) return this.synthAssetsLoading;
if (typeof JSSynth === 'undefined') return Promise.resolve(null);
this.synthAssetsLoading = (async () => {
const [, sfBuf] = await Promise.all([
JSSynth.waitForReady(),
fetch('TimGM6mb.sf2').then(resp => {
if (!resp || !resp.ok) throw new Error('Failed to fetch TimGM6mb.sf2');
return resp.arrayBuffer();
})
]);
return sfBuf;
})().catch(e => {
console.warn('FluidSynth preload error:', e);
this.synthAssetsLoading = null;
return null;
});
return this.synthAssetsLoading;
},
ensureFluidSynth() {
if (this.synthReady) return Promise.resolve(this.synth);
if (this.synthLoading) return this.synthLoading;
const ctx = this.ensureCtx();
if (!ctx || !bytes || bytes.length === 0) return;
if (!ctx || typeof JSSynth === 'undefined') return Promise.resolve(null);
this.synthLoading = (async () => {
try {
const sfBuf = await this.preloadFluidSynthAssets();
if (!sfBuf) throw new Error('SoundFont unavailable');
const s = new JSSynth.Synthesizer();
s.init(ctx.sampleRate);
await s.loadSFont(sfBuf);
s.setGain(this.midiGain * 0.5);
const node = s.createAudioNode(ctx, 4096);
node.connect(ctx.destination);
this.synth = s;
this.synthNode = node;
this.synthReady = true;
if (this.pendingMidi && this.ctx && this.ctx.state === 'running') {
const pending = this.pendingMidi;
this.pendingMidi = null;
this.playMidi(pending, this.midiGain, this.midiLoop);
}
return s;
} catch (e) {
console.warn('FluidSynth init error:', e);
this.synthLoading = null;
return null;
}
})();
return this.synthLoading;
},
decodeWav8MonoSync(ctx, bytes) {
if (!bytes || bytes.length < 44) return null;
if (bytes[0] !== 0x52 || bytes[1] !== 0x49 || bytes[2] !== 0x46 || bytes[3] !== 0x46) return null; // RIFF
if (bytes[8] !== 0x57 || bytes[9] !== 0x41 || bytes[10] !== 0x56 || bytes[11] !== 0x45) return null; // WAVE
const audioFmt = bytes[20] | (bytes[21] << 8);
const channels = bytes[22] | (bytes[23] << 8);
const bitsPerSample = bytes[34] | (bytes[35] << 8);
if (audioFmt !== 1 || channels !== 1 || bitsPerSample !== 8) return null;
if (bytes[36] !== 0x64 || bytes[37] !== 0x61 || bytes[38] !== 0x74 || bytes[39] !== 0x61) return null; // data
const sampleRate = (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16) | (bytes[27] << 24)) >>> 0;
const dataSize = Math.min(
(bytes[40] | (bytes[41] << 8) | (bytes[42] << 16) | (bytes[43] << 24)) >>> 0,
bytes.length - 44
);
if (sampleRate < 4000 || dataSize <= 0) return null;
const buf = ctx.createBuffer(1, dataSize, sampleRate);
const out = buf.getChannelData(0);
for (let i = 0; i < dataSize; i++) {
out[i] = (bytes[44 + i] - 128) / 128.0;
}
return buf;
},
playBuffer(ctx, buf, volume, delayMs) {
const src = ctx.createBufferSource();
const gain = ctx.createGain();
gain.gain.value = Math.max(0, Math.min(1, volume));
src.buffer = buf;
src.connect(gain);
gain.connect(ctx.destination);
const startAt = (delayMs && delayMs > 0) ? (ctx.currentTime + delayMs / 1000.0) : 0;
src.start(startAt);
},
playPcm(bytes, volume, delayMs) {
const ctx = this.ensureCtx();
if (!ctx || ctx.state === 'suspended' || !bytes || bytes.length === 0) return;
const syncBuf = this.decodeWav8MonoSync(ctx, bytes);
if (syncBuf) {
this.playBuffer(ctx, syncBuf, volume, delayMs);
return;
}
const copy = new Uint8Array(bytes).buffer;
ctx.decodeAudioData(copy).then(buf => {
const src = ctx.createBufferSource();
const gain = ctx.createGain();
gain.gain.value = Math.max(0, Math.min(1, volume));
src.buffer = buf;
src.connect(gain);
gain.connect(ctx.destination);
src.start(0);
this.playBuffer(ctx, buf, volume, delayMs);
}).catch(() => {});
},
playMidi(bytes, volume) {
async playMidi(bytes, volume, loop) {
this.midiGain = Math.max(0, Math.min(1, volume));
if (this.sequencer && bytes && bytes.length > 0) {
try {
this.sequencer.loadNewSongList([{ binary: new Uint8Array(bytes).buffer }]);
this.sequencer.play();
} catch (e) {
console.warn('SpessaSynth MIDI playback error:', e);
if (typeof loop === 'boolean') this.midiLoop = loop;
if (!bytes || bytes.length === 0) return;
this.lastMidiBytes = new Uint8Array(bytes);
const seq = ++this.midiPlaySeq;
this.ensureCtx();
if (!this.synthReady) {
this.pendingMidi = new Uint8Array(bytes);
this.ensureFluidSynth();
return;
}
if (this.ctx && this.ctx.state === 'suspended') {
this.pendingMidi = new Uint8Array(bytes);
return;
}
this.pendingMidi = null;
try {
const copy = new Uint8Array(bytes).buffer;
this.synth.setGain(this.midiGain * 0.5);
await this.synth.stopPlayer();
if (seq !== this.midiPlaySeq) return;
await this.synth.resetPlayer();
if (seq !== this.midiPlaySeq) return;
await this.synth.addSMFDataToPlayer(copy);
if (seq !== this.midiPlaySeq) return;
if (this.synth.setPlayerLoop) {
this.synth.setPlayerLoop(this.midiLoop === false ? 0 : -1);
}
await this.synth.playPlayer();
} catch (e) {
console.warn('FluidSynth MIDI playback error:', e);
}
},
setMidiLoop(loop, restartIfStopped) {
this.midiLoop = !!loop;
if (this.synthReady && this.synth && this.synth.setPlayerLoop) {
try { this.synth.setPlayerLoop(this.midiLoop ? -1 : 0); } catch (_) {}
}
if (restartIfStopped && this.lastMidiBytes && this.synthReady && this.synth) {
try {
if (this.synth.isPlaying && !this.synth.isPlaying()) {
this.playMidi(this.lastMidiBytes, this.midiGain, this.midiLoop);
}
} catch (_) {}
}
},
setMidiVolume(volume) {
this.midiGain = Math.max(0, Math.min(1, volume));
if (this.synth && this.synth.setMasterGain) {
this.synth.setMasterGain(this.midiGain);
if (this.synthReady && this.synth) {
this.synth.setGain(this.midiGain * 0.5);
}
},
stopMidi() {
if (this.sequencer && this.sequencer.pause) {
try { this.sequencer.pause(); } catch (_) {}
this.midiPlaySeq++;
this.pendingMidi = null;
if (this.synthReady && this.synth) {
try { this.synth.stopPlayer(); } catch (_) {}
}
}
};
window.scapeClipboardText = '';
window.addEventListener('paste', (e) => {
try {
const txt = e.clipboardData ? e.clipboardData.getData('text') : '';
if (txt) window.scapeClipboardText = txt;
} catch (_) {}
});
window.addEventListener('focus', () => {
if (navigator.clipboard && navigator.clipboard.readText) {
navigator.clipboard.readText().then(t => { if (typeof t === 'string') window.scapeClipboardText = t; }).catch(() => {});
}
}, { passive: true });
window.scapeWebAudio.preloadFluidSynthAssets();
['pointerdown', 'keydown', 'touchstart'].forEach(evt => {
window.addEventListener(evt, () => {
window.scapeWebAudio.ensureCtx();
window.scapeWebAudio.ensureFluidSynth();
}, { passive: true });
});
// Cache preloader (IndexedDB + HTTP fetch)
window.scapePreloadCache = async function(cb) {
@@ -523,15 +870,7 @@
cb(results[0], results[1], results[2], results[3], results[4], results[5]);
};
// Script import handler into localStorage virtual FS
document.getElementById('script-upload').addEventListener('change', async (ev) => {
for (const file of ev.target.files) {
const text = await file.text();
localStorage.setItem('2006scape_script_' + file.name, text);
console.log('[2006Scape-Web] Imported script:', file.name);
}
ev.target.value = '';
});
// Script import handler moved into Storage modal below
window.scapeInitNavbar = function(visible, mainMenuUrl, worldMapUrl, manualUrl, rulesUrl) {
const nav = document.getElementById('rs-navbar');
@@ -568,12 +907,13 @@
document.getElementById('opt-autologin').checked = !!o.autoLogin;
document.getElementById('opt-username').value = o.username || '';
document.getElementById('opt-password').value = o.password || '';
document.getElementById('opt-server').value = o.server || params.get('server') || '192.168.1.88';
document.getElementById('opt-server').value = o.server || params.get('server') || 'server.2006scape.org';
document.getElementById('opt-world').value = o.world || params.get('world') || '1';
document.getElementById('opt-hd').checked = (o.hd !== undefined) ? !!o.hd : (params.get('hd') === 'true' || params.get('hd') === '1');
document.getElementById('opt-mode').value = String(window.scapeDisplayMode !== undefined ? window.scapeDisplayMode : (o.displayMode || 0));
const nav = document.getElementById('rs-navbar');
document.getElementById('opt-navbar').checked = (o.navbar !== undefined) ? !!o.navbar : (nav ? nav.classList.contains('visible') : true);
document.getElementById('opt-pause-bg').checked = !!o.pauseInBackground;
}
function saveOpts(applyLive) {
@@ -581,14 +921,32 @@
autoLogin: document.getElementById('opt-autologin').checked,
username: document.getElementById('opt-username').value.trim(),
password: document.getElementById('opt-password').value,
server: document.getElementById('opt-server').value.trim() || '192.168.1.88',
server: document.getElementById('opt-server').value.trim() || 'server.2006scape.org',
world: parseInt(document.getElementById('opt-world').value, 10) || 1,
hd: document.getElementById('opt-hd').checked,
displayMode: parseInt(document.getElementById('opt-mode').value, 10) || 0,
navbar: document.getElementById('opt-navbar').checked
navbar: document.getElementById('opt-navbar').checked,
pauseInBackground: document.getElementById('opt-pause-bg').checked
};
try { localStorage.setItem(OPT_KEY, JSON.stringify(o)); } catch (_) {}
try {
localStorage.setItem(OPT_KEY, JSON.stringify(o));
const props = localStorage.getItem('2006scape_plugin_settings') || '';
const lines = props ? props.split(/\r?\n/) : [];
let found = false;
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith('plugin.317_HD.enabled=')) {
lines[i] = 'plugin.317_HD.enabled=' + o.hd;
found = true;
}
}
if (!found) lines.push('plugin.317_HD.enabled=' + o.hd);
localStorage.setItem('2006scape_plugin_settings', lines.filter(Boolean).join('\n') + '\n');
} catch (_) {}
if (applyLive) {
window.scapePauseInBackground = !!o.pauseInBackground;
if (typeof window.scapeSetHd317 === 'function') {
window.scapeSetHd317(o.hd);
}
const nav = document.getElementById('rs-navbar');
if (nav) nav.classList.toggle('visible', o.navbar);
if (typeof window.scapeDisplayMode === 'number' && window.scapeDisplayMode !== o.displayMode) {
@@ -612,6 +970,227 @@
if (modal) modal.addEventListener('click', (e) => { if (e.target === modal) modal.classList.remove('open'); });
if (btnSave) btnSave.addEventListener('click', () => { saveOpts(true); modal.classList.remove('open'); });
if (btnSaveReload) btnSaveReload.addEventListener('click', () => { saveOpts(false); window.location.reload(); });
window.scapePauseInBackground = !!loadOpts().pauseInBackground;
document.addEventListener('visibilitychange', () => {
if (!window.scapePauseInBackground) return;
const audio = window.scapeWebAudio;
if (!audio || !audio.ctx) return;
if (document.hidden) {
if (audio.ctx.state === 'running') {
window.scapePausedAudio = true;
audio.ctx.suspend().catch(() => {});
}
} else if (window.scapePausedAudio) {
window.scapePausedAudio = false;
audio.ctx.resume().catch(() => {});
}
});
})();
(function() {
const modal = document.getElementById('storage-modal');
const btnOpen = document.getElementById('btn-storage');
const btnClose = document.getElementById('storage-close');
const btnCancel = document.getElementById('storage-cancel');
const btnRefresh = document.getElementById('storage-refresh');
const btnNew = document.getElementById('storage-new');
const btnSave = document.getElementById('storage-save');
const btnSaveReload = document.getElementById('storage-save-reload');
const btnDelete = document.getElementById('storage-delete');
const btnDownload = document.getElementById('storage-download');
const filterEl = document.getElementById('storage-filter');
const listEl = document.getElementById('storage-list');
const keyEl = document.getElementById('storage-key');
const textEl = document.getElementById('storage-textarea');
const statusEl = document.getElementById('storage-status');
let selectedKey = '';
function formatBytes(len) {
return len < 1024 ? (len + ' B') : ((len / 1024).toFixed(1) + ' KB');
}
function classifyKey(k) {
if (k === '2006scape_plugin_settings') return { label: 'Plugin Config', rank: 0, title: 'plugin_config.ini (2006scape_plugin_settings)' };
if (k === '2006scape_web_options') return { label: 'Web Options', rank: 1, title: k };
if (k.startsWith('2006scape_script_')) return { label: 'Script/Plugin', rank: 2, title: k.slice('2006scape_script_'.length) };
return { label: 'Storage', rank: 3, title: k };
}
function getSortedKeys() {
const filter = (filterEl.value || '').trim().toLowerCase();
const keys = [];
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
if (k && (!filter || k.toLowerCase().includes(filter))) {
keys.push(k);
}
}
keys.sort((a, b) => {
const ca = classifyKey(a);
const cb = classifyKey(b);
if (ca.rank !== cb.rank) return ca.rank - cb.rank;
return a.localeCompare(b);
});
return keys;
}
function renderList() {
const keys = getSortedKeys();
listEl.innerHTML = '';
if (keys.length === 0) {
const empty = document.createElement('div');
empty.style.cssText = 'padding:12px;color:#8a7f63;font-size:12px;';
empty.textContent = 'No matching localStorage keys.';
listEl.appendChild(empty);
return;
}
for (const k of keys) {
const val = localStorage.getItem(k) || '';
const info = classifyKey(k);
const row = document.createElement('div');
row.className = 'storage-item' + (k === selectedKey ? ' active' : '');
const nameDiv = document.createElement('div');
nameDiv.className = 'storage-item-name';
nameDiv.textContent = info.title;
const metaDiv = document.createElement('div');
metaDiv.className = 'storage-item-meta';
const typeSpan = document.createElement('span');
typeSpan.textContent = info.label;
const sizeSpan = document.createElement('span');
sizeSpan.textContent = formatBytes(val.length);
metaDiv.appendChild(typeSpan);
metaDiv.appendChild(sizeSpan);
row.appendChild(nameDiv);
row.appendChild(metaDiv);
row.addEventListener('click', () => selectKey(k));
listEl.appendChild(row);
}
}
function selectKey(k) {
selectedKey = k;
keyEl.value = k;
const val = localStorage.getItem(k);
textEl.value = val !== null ? val : '';
statusEl.textContent = val !== null ? ('Loaded ' + k + ' (' + formatBytes(val.length) + ')') : 'New key';
renderList();
}
function saveCurrent(applyLive) {
const k = (keyEl.value || '').trim();
if (!k) {
statusEl.textContent = 'Enter a key name first.';
return false;
}
const val = textEl.value;
localStorage.setItem(k, val);
selectedKey = k;
renderList();
if (applyLive && (k === '2006scape_plugin_settings' || k.startsWith('2006scape_script_')) && typeof window.scapeReloadStorage === 'function') {
window.scapeReloadStorage();
statusEl.textContent = 'Saved & hot-reloaded: ' + k;
} else {
statusEl.textContent = 'Saved ' + k + ' (' + formatBytes(val.length) + ')';
}
return true;
}
if (btnOpen) btnOpen.addEventListener('click', () => {
const keys = getSortedKeys();
if (!selectedKey && keys.length > 0) selectedKey = keys[0];
if (selectedKey && localStorage.getItem(selectedKey) !== null) {
selectKey(selectedKey);
} else {
renderList();
}
modal.classList.add('open');
});
if (btnClose) btnClose.addEventListener('click', () => modal.classList.remove('open'));
if (btnCancel) btnCancel.addEventListener('click', () => modal.classList.remove('open'));
if (modal) modal.addEventListener('click', (e) => { if (e.target === modal) modal.classList.remove('open'); });
if (filterEl) filterEl.addEventListener('input', renderList);
if (btnRefresh) btnRefresh.addEventListener('click', () => {
renderList();
if (selectedKey && localStorage.getItem(selectedKey) !== null) selectKey(selectedKey);
});
if (btnNew) btnNew.addEventListener('click', () => {
const name = window.prompt('New script filename (e.g. MyPlugin.java / MyScript.script) or full localStorage key:', 'MyScript.script');
if (!name || !name.trim()) return;
const trimmed = name.trim();
const fullKey = (trimmed.startsWith('2006scape_') || !/\.(script|bsh|java)$/i.test(trimmed))
? trimmed
: ('2006scape_script_' + trimmed);
selectedKey = fullKey;
keyEl.value = fullKey;
if (localStorage.getItem(fullKey) !== null) {
textEl.value = localStorage.getItem(fullKey);
} else if (fullKey.startsWith('2006scape_script_')) {
textEl.value = '// @name New Script\n// @type script\n// @version 1.0.0\n\nvoid onStart(PluginContext c) {\n ctx = c;\n}\n';
} else {
textEl.value = '';
}
statusEl.textContent = 'Editing ' + fullKey + ' (unsaved)';
renderList();
});
if (btnSave) btnSave.addEventListener('click', () => saveCurrent(true));
if (btnSaveReload) btnSaveReload.addEventListener('click', () => {
if (saveCurrent(false)) window.location.reload();
});
if (btnDelete) btnDelete.addEventListener('click', () => {
const k = (keyEl.value || '').trim();
if (!k) return;
if (!window.confirm('Delete localStorage key "' + k + '"?')) return;
localStorage.removeItem(k);
if (selectedKey === k) selectedKey = '';
keyEl.value = '';
textEl.value = '';
renderList();
if ((k === '2006scape_plugin_settings' || k.startsWith('2006scape_script_')) && typeof window.scapeReloadStorage === 'function') {
window.scapeReloadStorage();
}
statusEl.textContent = 'Deleted ' + k;
});
if (btnDownload) btnDownload.addEventListener('click', () => {
const k = (keyEl.value || '').trim() || 'storage_export.txt';
const fileName = k === '2006scape_plugin_settings' ? 'plugin_config.ini'
: (k.startsWith('2006scape_script_') ? k.slice('2006scape_script_'.length) : (k + '.txt'));
const blob = new Blob([textEl.value], { type: 'text/plain;charset=utf-8' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = fileName;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
});
const btnImport = document.getElementById('storage-import');
const scriptUpload = document.getElementById('script-upload');
if (btnImport && scriptUpload) {
btnImport.addEventListener('click', () => scriptUpload.click());
scriptUpload.addEventListener('change', async (ev) => {
let count = 0;
let lastKey = '';
for (const file of ev.target.files) {
const text = await file.text();
lastKey = '2006scape_script_' + file.name;
localStorage.setItem(lastKey, text);
console.log('[2006Scape-Web] Imported script:', file.name);
count++;
}
ev.target.value = '';
if (count > 0) {
if (typeof window.scapeReloadStorage === 'function') {
window.scapeReloadStorage();
}
if (lastKey) {
selectedKey = lastKey;
keyEl.value = lastKey;
textEl.value = localStorage.getItem(lastKey) || '';
}
renderList();
statusEl.textContent = 'Imported ' + count + ' script(s) & reloaded';
}
});
}
})();
function updateCachedStageSize() {
+31
View File
@@ -0,0 +1,31 @@
/*!
js-synthesizer version 1.13.0
@license
Copyright (C) 2026 jet
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["js-synthesizer"]=t():e.JSSynth=t()}(this,()=>(()=>{"use strict";var e={d:(t,s)=>{for(var n in s)e.o(s,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:s[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{AudioWorkletNodeSynthesizer:()=>Z,Constants:()=>s,LogLevel:()=>Q,MessageError:()=>C,SequencerEventTypes:()=>n,Synthesizer:()=>B,disableLogging:()=>X,restoreLogging:()=>Y,rewriteEventData:()=>k,version:()=>ee,waitForReady:()=>D});var s={};e.r(s),e.d(s,{PlayerSetTempoType:()=>i});var n={};e.r(n);const i={Internal:0,ExternalBpm:1,ExternalMidi:2};let r,_,l,a,o,h,u,d,c,y,g,f,m,p,v;function P(e){if(null!=e||!c){if(null!=e){if(!e.addFunction||!e.removeFunction||!e.addOnPostRun)throw new Error("Invalid 'module' object. libfluidsynth-*.js (2.4.6 or higher) must be used.");r=e,_=r.addFunction,l=r.removeFunction,o=r.addOnPostRun}else if("undefined"!=typeof AudioWorkletGlobalScope)r=AudioWorkletGlobalScope.wasmModule,_=r.addFunction||AudioWorkletGlobalScope.wasmAddFunction,l=r.removeFunction||AudioWorkletGlobalScope.wasmRemoveFunction,o=r.addOnPostRun||AudioWorkletGlobalScope.addOnPostRun;else{if("undefined"==typeof Module)throw new Error("wasm module is not available. libfluidsynth-*.js must be loaded.");r=Module,r.addFunction?(_=r.addFunction,l=r.removeFunction):(_=addFunction,l=removeFunction),o=r.addOnPostRun?r.addOnPostRun:"undefined"!=typeof addOnPostRun?addOnPostRun:void 0}a=r.FS,h=r.cwrap("fluid_settings_setint","number",["number","string","number"]),u=r.cwrap("fluid_settings_setnum","number",["number","string","number"]),d=r.cwrap("fluid_settings_setstr","number",["number","string","string"]),c=r.cwrap("fluid_synth_error","string",["number"]),y=r.cwrap("fluid_synth_sfload","number",["number","string","number"]),g=r.cwrap("fluid_sequencer_register_client","number",["number","string","number","number"]),f=r._malloc.bind(r),m=r._free.bind(r),p=r._fluid_synth_handle_midi_event.bind(r)}}const b=0;class w{constructor(e,t){this._ptr=e,this._module=t}getRaw(){return this._ptr}dispose(){this._ptr=b}getType(){return this._ptr===b?-1:this._module._fluid_event_get_type(this._ptr)}getSource(){return this._ptr===b?-1:this._module._fluid_event_get_source(this._ptr)}getDest(){return this._ptr===b?-1:this._module._fluid_event_get_dest(this._ptr)}getChannel(){return this._ptr===b?-1:this._module._fluid_event_get_channel(this._ptr)}getKey(){return this._ptr===b?-1:this._module._fluid_event_get_key(this._ptr)}getVelocity(){return this._ptr===b?-1:this._module._fluid_event_get_velocity(this._ptr)}getControl(){return this._ptr===b?-1:this._module._fluid_event_get_control(this._ptr)}getValue(){return this._ptr===b?-1:this._module._fluid_event_get_value(this._ptr)}getProgram(){return this._ptr===b?-1:this._module._fluid_event_get_program(this._ptr)}getData(){return this._ptr===b?-1:this._module._fluid_event_get_data(this._ptr)}getDuration(){return this._ptr===b?-1:this._module._fluid_event_get_duration(this._ptr)}getBank(){return this._ptr===b?-1:this._module._fluid_event_get_bank(this._ptr)}getPitch(){return this._ptr===b?-1:this._module._fluid_event_get_pitch(this._ptr)}getSFontId(){return this._ptr===b?-1:this._module._fluid_event_get_sfont_id(this._ptr)}}function S(e,t){switch(t.type){case 0:case"note":r._fluid_event_note(e,t.channel,t.key,t.vel,t.duration);break;case 1:case"noteon":case"note-on":r._fluid_event_noteon(e,t.channel,t.key,t.vel);break;case 2:case"noteoff":case"note-off":r._fluid_event_noteoff(e,t.channel,t.key);break;case 3:case"allsoundsoff":case"all-sounds-off":r._fluid_event_all_sounds_off(e,t.channel);break;case 4:case"allnotesoff":case"all-notes-off":r._fluid_event_all_notes_off(e,t.channel);break;case 5:case"bankselect":case"bank-select":r._fluid_event_bank_select(e,t.channel,t.bank);break;case 6:case"programchange":case"program-change":r._fluid_event_program_change(e,t.channel,t.preset);break;case 7:case"programselect":case"program-select":r._fluid_event_program_select(e,t.channel,t.sfontId,t.bank,t.preset);break;case 12:case"controlchange":case"control-change":r._fluid_event_control_change(e,t.channel,t.control,t.value);break;case 8:case"pitchbend":case"pitch-bend":r._fluid_event_pitch_bend(e,t.channel,t.value);break;case 9:case"pitchwheelsens":case"pitchwheelsensitivity":case"pitch-wheel-sens":case"pitch-wheel-sensitivity":r._fluid_event_pitch_wheelsens(e,t.channel,t.value);break;case 10:case"modulation":r._fluid_event_modulation(e,t.channel,t.value);break;case 11:case"sustain":r._fluid_event_sustain(e,t.channel,t.value);break;case 13:case"pan":r._fluid_event_pan(e,t.channel,t.value);break;case 14:case"volume":r._fluid_event_volume(e,t.channeLine truncated
//# sourceMappingURL=js-synthesizer.min.js.map
+1
View File
@@ -0,0 +1 @@
var Module=typeof Module!="undefined"?Module:{};var document=typeof document!=="undefined"?document:{};var window=typeof window!=="undefined"?window:{};if(typeof AudioWorkletGlobalScope!=="undefined"&&AudioWorkletGlobalScope){AudioWorkletGlobalScope.wasmModule=Module;AudioWorkletGlobalScope.wasmAddFunction=addFunction;AudioWorkletGlobalScope.wasmRemoveFunction=removeFunction;AudioWorkletGlobalScope.addOnPreRun=addOnPreRun;AudioWorkletGlobalScope.addOnInit=addOnInit;AudioWorkletGlobalScope.addOnPostRun=addOnPostRun}var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=true;var ENVIRONMENT_IS_WORKER=false;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=(url=>{try{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText}catch(err){var data=tryParseAsDataURI(url);if(data){return intArrayToString(data)}throw err}});if(ENVIRONMENT_IS_WORKER){readBinary=(url=>{try{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}catch(err){var data=tryParseAsDataURI(url);if(data){return data}throw err}})}readAsync=((url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=(()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}var data=tryParseAsDataURI(url);if(data){onload(data.buffer);return}onerror()});xhr.onerror=onerror;xhr.send(null)})}setWindowTitle=(title=>document.title=title)}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];function uleb128Encode(n){if(n<128){return[n]}return[n%128|128,n>>7]}function convertJsFunctionToWasm(func,sig){if(typeof WebAssembly.Function=="function"){var typeNames={"i":"i32","j":"i64","f":"f32","d":"f64"};var type={parameters:[],results:sig[0]=="v"?[]:[typeNames[sig[0]]]};for(var i=1;i<sig.length;++i){type.parameters.push(typeNames[sig[i]])}return new WebAssembly.Function(type,func)}var typeSection=[1,96];var sigRet=sig.slice(0,1);var sigParam=sig.slice(1);var typeCodes={"i":127,"j":126,"f":125,"d":124};typeSection=typeSection.concat(uleb128Encode(sigParam.length));for(var i=0;i<sigParam.length;++i){typeSection.push(typeCodes[sigParam[i]])}if(sigRet=="v"){typeSection.push(0)}else{typeSection=typeSection.concat([1,typeCodes[sigRet]])}typeSection=[1].concat(uleb128Encode(typeSection.length),typeSection);var bytes=new Uint8Array([0,97,115,109,1,0,0,0].concat(typeSection,[2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0]));var module=new WebAssembly.Module(bytes);var instance=new WebAssembly.Instance(module,{"e":{"f":func}});var wrappedFunc=instance.exports["f"];return wrappedFunc}var freeTableIndexes=[];var functionsInTableMap;function getEmptyTableSlot(){if(freeTableIndexes.length){return freeTableIndexes.pop()}try{wasmTable.grow(1)}catch(err){if(!(err instanceof RangeError)){throw err}throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return wasmTable.length-1}function updateTableMap(offset,count){for(var i=offset;i<offset+count;i++){var item=getWasmTableEntry(i);if(item){functionsInTableMap.set(item,i)}}}function addFunction(func,sig){if(!functionsInTableMap){functionsInTableMap=new WeakMap;updateTableMap(0,wasmTable.length)}if(functionsInTableMap.has(func)){return functionsInTableMap.get(func)}var ret=getEmptyTableSlot();try{setWasmTableEntry(ret,func)}catch(err){if(!(err instanceof TypeError)){throw err}var wrapped=convertJsFunctionToWasm(func,sig);setWasmTableEntry(ret,wrapped)}functionsInTableMap.set(func,ret);return ret}function removeFunction(index){functionsInTableMap.delete(getWasmTableEntry(index));freeTableIndexes.push(index)}var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(text)}}function getCFunc(ident){var func=Module["_"+ident];return func}function ccall(ident,returnType,argTypes,args,opts){var toC={"string":function(str){var ret=0;if(str!==nullLine truncated
+7 -4
View File
@@ -1,8 +1,11 @@
const CACHE_VERSION = '2006scape-web-v1';
const CACHE_VERSION = '2006scape-web-v6';
const SHELL_ASSETS = [
'./',
'index.html',
'manifest.webmanifest',
'libfluidsynth-2.3.0.js',
'js-synthesizer.min.js',
'TimGM6mb.sf2',
'js/client.js',
'hud_minimap_bezel.png',
'hud_minimap_hole.png',
@@ -48,7 +51,7 @@ self.addEventListener('fetch', (event) => {
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
if (req.mode === 'navigate' || url.pathname.endsWith('/index.html') || url.pathname === '/') {
if (req.mode === 'navigate' || url.pathname.endsWith('/index.html') || url.pathname === '/' || url.pathname.endsWith('/js/client.js')) {
event.respondWith((async () => {
try {
const fresh = await fetch(req);
@@ -59,13 +62,13 @@ self.addEventListener('fetch', (event) => {
return fresh;
} catch (_) {
const cached = await caches.match(req);
return cached || caches.match('index.html');
return cached || (req.mode === 'navigate' ? caches.match('index.html') : Response.error());
}
})());
return;
}
if (/\.(js|png|gif|jpg|jpeg|webp|svg|ico|css|webmanifest|dat|idx\d*)$/i.test(url.pathname)) {
if (/\.(js|png|gif|jpg|jpeg|webp|svg|ico|css|webmanifest|dat|idx\d*|sf2|sf3|wasm)$/i.test(url.pathname)) {
event.respondWith((async () => {
const cache = await caches.open(CACHE_VERSION);
const cached = await cache.match(req);