- server/: Node (ws) static server + authoritative co-op rooms; dual-stack listen, proxy-aware client IP and Origin check, keep-alive pings, per-socket rate limits, graceful shutdown; 59 node:test tests - docs/DEPLOY.md + deploy/netwall.service: Debian 13 LXC, systemd, nginx Proxy Manager walk-through, path prefix, troubleshooting - e2e/: Playwright suite (smoke, touch, end flow, two-browser co-op incl. reconnect, 14-size layout matrix); npm run e2e - Music: tracks.json now points at the uploaded theme/battle/boss/win/lose files; stingers fade out when a new game starts - PAUSED indicator, refreshed icon Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
325 lines
15 KiB
JavaScript
325 lines
15 KiB
JavaScript
/*
|
|
* NETWALL audio: synthesised sound effects + background music.
|
|
*
|
|
* Music: looks for assets/music/<track>.mp3 (or .ogg) - tracks: theme (menu), battle, boss - plus one-shot
|
|
* stingers win / lose. Any track that is missing falls back to a small generative synth melody, so the game
|
|
* has music out of the box and a Suno-made file simply replaces it when you drop it in.
|
|
*/
|
|
(function (root) {
|
|
'use strict';
|
|
const NW = root.NW = root.NW || {};
|
|
|
|
const MUSIC_DIR = 'assets/music/';
|
|
const STORE = 'nw.audio';
|
|
|
|
let ctx = null, master = null, sfxBus = null, musBus = null, delayNode = null;
|
|
let muted = false, musicVol = 0.55, sfxVol = 0.8;
|
|
let unlocked = false;
|
|
let wanted = null; // music track the game currently wants ('theme' | 'battle' | 'boss' | null)
|
|
let current = null; // { name, kind:'file'|'synth', el?, stop() }
|
|
const fileState = {}; // name -> 'unknown' | 'ok' | 'missing'
|
|
const lastPlay = {};
|
|
const files = {}; // name -> HTMLAudioElement
|
|
|
|
try {
|
|
const s = JSON.parse(localStorage.getItem(STORE) || '{}');
|
|
if (typeof s.muted === 'boolean') muted = s.muted;
|
|
if (typeof s.music === 'number') musicVol = Math.min(1, Math.max(0, s.music));
|
|
} catch (e) { /* storage unavailable */ }
|
|
function save() { try { localStorage.setItem(STORE, JSON.stringify({ muted, music: musicVol })); } catch (e) { /* ignore */ } }
|
|
|
|
function ensureCtx() {
|
|
if (ctx) return ctx;
|
|
const AC = root.AudioContext || root.webkitAudioContext;
|
|
if (!AC) return null;
|
|
try { ctx = new AC(); } catch (e) { return null; }
|
|
master = ctx.createGain(); master.gain.value = muted ? 0 : 0.9;
|
|
master.connect(ctx.destination);
|
|
sfxBus = ctx.createGain(); sfxBus.gain.value = 0.32 * sfxVol; sfxBus.connect(master);
|
|
musBus = ctx.createGain(); musBus.gain.value = 0.3 * musicVol; musBus.connect(master);
|
|
return ctx;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- sfx
|
|
function tone(freq, dur, type, vol, slideTo, when) {
|
|
if (!ctx || muted) return;
|
|
const t0 = ctx.currentTime + (when || 0);
|
|
const o = ctx.createOscillator(), g = ctx.createGain();
|
|
o.type = type || 'square';
|
|
o.frequency.setValueAtTime(freq, t0);
|
|
if (slideTo) o.frequency.exponentialRampToValueAtTime(Math.max(20, slideTo), t0 + dur);
|
|
g.gain.setValueAtTime(0.0001, t0);
|
|
g.gain.exponentialRampToValueAtTime(vol, t0 + 0.008);
|
|
g.gain.exponentialRampToValueAtTime(0.0001, t0 + dur);
|
|
o.connect(g); g.connect(sfxBus);
|
|
o.start(t0); o.stop(t0 + dur + 0.02);
|
|
}
|
|
let noiseBuf = null;
|
|
function noiseBuffer() {
|
|
if (noiseBuf) return noiseBuf;
|
|
noiseBuf = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate);
|
|
const d = noiseBuf.getChannelData(0);
|
|
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
|
|
return noiseBuf;
|
|
}
|
|
function noise(dur, vol, filterType, f0, f1, when, bus) {
|
|
if (!ctx || muted) return;
|
|
const t0 = ctx.currentTime + (when || 0);
|
|
const s = ctx.createBufferSource(); s.buffer = noiseBuffer();
|
|
const f = ctx.createBiquadFilter(); f.type = filterType || 'lowpass';
|
|
f.frequency.setValueAtTime(f0, t0);
|
|
if (f1) f.frequency.exponentialRampToValueAtTime(f1, t0 + dur);
|
|
const g = ctx.createGain();
|
|
g.gain.setValueAtTime(vol, t0);
|
|
g.gain.exponentialRampToValueAtTime(0.0001, t0 + dur);
|
|
s.connect(f); f.connect(g); g.connect(bus || sfxBus);
|
|
s.start(t0, Math.random() * 0.5); s.stop(t0 + dur + 0.02);
|
|
}
|
|
|
|
const SFX = {
|
|
click: () => tone(660, 0.04, 'square', 0.12),
|
|
place: () => { tone(420, 0.07, 'square', 0.22, 700); noise(0.05, 0.12, 'highpass', 3000); },
|
|
wall: () => tone(240, 0.05, 'square', 0.16, 330),
|
|
sell: () => tone(560, 0.12, 'triangle', 0.22, 220),
|
|
up: () => { tone(520, 0.08, 'square', 0.18); tone(780, 0.08, 'square', 0.18, 0, 0.07); tone(1040, 0.14, 'square', 0.18, 0, 0.14); },
|
|
error: () => { tone(190, 0.1, 'square', 0.2); tone(150, 0.12, 'square', 0.2, 0, 0.09); },
|
|
shot_filter: () => noise(0.03, 0.07, 'highpass', 5000),
|
|
shot_ids: () => { tone(1100, 0.14, 'sawtooth', 0.2, 180); noise(0.08, 0.12, 'highpass', 2500); },
|
|
shot_mortar: () => tone(150, 0.18, 'sine', 0.45, 60),
|
|
arc: () => { noise(0.1, 0.16, 'bandpass', 3500, 900); tone(900, 0.08, 'sawtooth', 0.1, 300); },
|
|
boom: () => noise(0.32, 0.5, 'lowpass', 1800, 90),
|
|
kill: () => tone(820, 0.05, 'triangle', 0.1, 1200),
|
|
leak: () => { tone(320, 0.35, 'sawtooth', 0.3, 70); noise(0.25, 0.25, 'lowpass', 900, 100); },
|
|
wave: () => { tone(220, 0.35, 'sawtooth', 0.14, 330); tone(330, 0.35, 'sawtooth', 0.12, 495, 0.05); tone(440, 0.45, 'sawtooth', 0.1, 660, 0.1); },
|
|
boss: () => { tone(110, 0.8, 'sawtooth', 0.28, 55); tone(116, 0.8, 'sawtooth', 0.22, 58); noise(0.6, 0.2, 'lowpass', 600, 80); },
|
|
clear: () => { tone(660, 0.09, 'triangle', 0.2); tone(880, 0.09, 'triangle', 0.2, 0, 0.09); tone(1320, 0.2, 'triangle', 0.2, 0, 0.18); },
|
|
ping: () => { tone(1320, 0.18, 'sine', 0.25, 1760); tone(1760, 0.3, 'sine', 0.12, 0, 0.12); },
|
|
join: () => { tone(660, 0.1, 'triangle', 0.2); tone(990, 0.16, 'triangle', 0.2, 0, 0.1); },
|
|
};
|
|
const MIN_GAP = { shot_filter: 0.06, kill: 0.05, arc: 0.07, boom: 0.08, shot_mortar: 0.1, shot_ids: 0.08, wall: 0.03 };
|
|
|
|
function sfx(name) {
|
|
if (muted || !unlocked || !ctx || !SFX[name]) return;
|
|
const now = ctx.currentTime, gap = MIN_GAP[name] || 0;
|
|
if (gap && lastPlay[name] && now - lastPlay[name] < gap) return;
|
|
lastPlay[name] = now;
|
|
SFX[name]();
|
|
}
|
|
|
|
// ---------------------------------------------------------------- generative music (fallback)
|
|
const NOTE = (n) => 440 * Math.pow(2, (n - 69) / 12); // midi -> Hz
|
|
const PROGS = {
|
|
theme: { bpm: 76, chords: [[57, 60, 64], [53, 57, 60], [48, 52, 55], [55, 59, 62]], bass: [45, 41, 36, 43] },
|
|
battle: { bpm: 112, chords: [[57, 60, 64], [53, 57, 60], [48, 52, 55], [55, 59, 62]], bass: [45, 41, 36, 43] },
|
|
boss: { bpm: 138, chords: [[57, 60, 64], [57, 60, 64], [53, 57, 60], [52, 56, 59]], bass: [45, 45, 41, 40] },
|
|
};
|
|
const ARP = [0, 1, 2, 1, 2, 1, 2, 0, 1, 2, 1, 2, 1, 0, 2, 1]; // chord-tone index per 16th
|
|
|
|
function startSynth(name) {
|
|
const p = PROGS[name] || PROGS.battle;
|
|
const out = ctx.createGain(); out.gain.value = 0.0001; out.connect(musBus);
|
|
out.gain.exponentialRampToValueAtTime(1, ctx.currentTime + 1.5);
|
|
const delay = ctx.createDelay(1.0); delay.delayTime.value = 60 / p.bpm * 0.75;
|
|
const fb = ctx.createGain(); fb.gain.value = 0.38; delay.connect(fb); fb.connect(delay);
|
|
const wet = ctx.createGain(); wet.gain.value = 0.5; delay.connect(wet); wet.connect(out);
|
|
const sixteenth = 60 / p.bpm / 4;
|
|
let step = 0, next = ctx.currentTime + 0.1, timer = 0, dead = false;
|
|
|
|
function note(type, freq, t, dur, vol, cutoff, dest) {
|
|
const o = ctx.createOscillator(), f = ctx.createBiquadFilter(), g = ctx.createGain();
|
|
o.type = type; o.frequency.value = freq;
|
|
f.type = 'lowpass'; f.frequency.value = cutoff; f.Q.value = 2;
|
|
g.gain.setValueAtTime(0.0001, t);
|
|
g.gain.exponentialRampToValueAtTime(vol, t + Math.min(0.02, dur / 3));
|
|
g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
|
|
o.connect(f); f.connect(g); g.connect(dest || out);
|
|
o.start(t); o.stop(t + dur + 0.05);
|
|
}
|
|
function pad(chord, t, dur) {
|
|
for (const n of chord) {
|
|
for (const det of [-7, 7]) {
|
|
const o = ctx.createOscillator(), f = ctx.createBiquadFilter(), g = ctx.createGain();
|
|
o.type = 'sawtooth'; o.frequency.value = NOTE(n + 12); o.detune.value = det;
|
|
f.type = 'lowpass'; f.frequency.setValueAtTime(500, t); f.frequency.linearRampToValueAtTime(1400, t + dur * 0.5); f.frequency.linearRampToValueAtTime(600, t + dur);
|
|
g.gain.setValueAtTime(0.0001, t);
|
|
g.gain.linearRampToValueAtTime(0.05, t + dur * 0.3);
|
|
g.gain.linearRampToValueAtTime(0.0001, t + dur);
|
|
o.connect(f); f.connect(g); g.connect(out);
|
|
o.start(t); o.stop(t + dur + 0.05);
|
|
}
|
|
}
|
|
}
|
|
function kick(t) {
|
|
const o = ctx.createOscillator(), g = ctx.createGain();
|
|
o.type = 'sine'; o.frequency.setValueAtTime(140, t); o.frequency.exponentialRampToValueAtTime(42, t + 0.12);
|
|
g.gain.setValueAtTime(0.9, t); g.gain.exponentialRampToValueAtTime(0.0001, t + 0.22);
|
|
o.connect(g); g.connect(out); o.start(t); o.stop(t + 0.25);
|
|
}
|
|
|
|
function schedule() {
|
|
if (dead) return;
|
|
while (next < ctx.currentTime + 0.25) {
|
|
const bar = Math.floor(step / 16) % p.chords.length, s = step % 16;
|
|
const chord = p.chords[bar], t = next;
|
|
if (s === 0) pad(chord, t, sixteenth * 16 * 1.02);
|
|
if (name !== 'theme' || s % 4 === 0) {
|
|
// arpeggio, quieter and sparser for the menu theme
|
|
const idx = ARP[s], n = chord[idx % 3] + 12 * (idx === 2 ? 1 : 0) + 12;
|
|
const pat = name === 'theme' ? (s % 8 === 0) : (name === 'boss' ? true : (s % 2 === 0 || s % 16 === 15));
|
|
if (pat) note('square', NOTE(n), t, sixteenth * 1.6, name === 'theme' ? 0.05 : 0.06, 2600, delay);
|
|
if (pat) note('square', NOTE(n), t, sixteenth * 1.6, 0.03, 2600);
|
|
}
|
|
if (name !== 'theme') {
|
|
if (s % 2 === 0) note('sawtooth', NOTE(p.bass[bar] + (s % 8 === 6 ? 12 : 0)), t, sixteenth * 1.7, 0.16, 420);
|
|
if (s % 4 === 0) kick(t);
|
|
if (s % 4 === 2) noise(0.05, 0.12, 'highpass', 7000, 0, t - ctx.currentTime, out);
|
|
if (name === 'boss' && s % 8 === 4) noise(0.12, 0.2, 'bandpass', 1800, 900, t - ctx.currentTime, out);
|
|
} else if (s === 0) {
|
|
note('sine', NOTE(p.bass[bar]), t, sixteenth * 14, 0.22, 300);
|
|
}
|
|
step++; next += sixteenth;
|
|
}
|
|
}
|
|
timer = setInterval(schedule, 40);
|
|
schedule();
|
|
return {
|
|
name, kind: 'synth',
|
|
stop(fade) {
|
|
dead = true; clearInterval(timer);
|
|
const t = ctx.currentTime;
|
|
out.gain.cancelScheduledValues(t);
|
|
out.gain.setValueAtTime(Math.max(0.0001, out.gain.value), t);
|
|
out.gain.exponentialRampToValueAtTime(0.0001, t + (fade || 0.8));
|
|
setTimeout(() => { try { out.disconnect(); } catch (e) { /* ignore */ } }, ((fade || 0.8) + 0.2) * 1000);
|
|
},
|
|
};
|
|
}
|
|
|
|
// ---------------------------------------------------------------- file music
|
|
// assets/music/tracks.json maps track names to file names, e.g. {"battle": "my-song.mp3"}; null = use the synth.
|
|
// Reading one small manifest (instead of probing for files) keeps the console free of 404s.
|
|
let manifestP = null;
|
|
function manifest() {
|
|
if (!manifestP) {
|
|
manifestP = (typeof fetch === 'function' && root.location && /^https?:/.test(root.location.protocol))
|
|
? fetch(MUSIC_DIR + 'tracks.json', { cache: 'no-cache' }).then((r) => (r.ok ? r.json() : {})).catch(() => ({}))
|
|
: Promise.resolve({});
|
|
}
|
|
return manifestP;
|
|
}
|
|
function fileFor(name, cb) {
|
|
if (fileState[name] === 'missing') { cb(null); return; }
|
|
if (files[name]) { cb(files[name]); return; }
|
|
manifest().then((m) => {
|
|
const f = m && typeof m[name] === 'string' && /^[\w .()-]+\.(mp3|ogg|m4a|wav)$/i.test(m[name]) ? m[name] : null;
|
|
if (!f) { fileState[name] = 'missing'; cb(null); return; }
|
|
const el = new Audio();
|
|
el.preload = 'auto';
|
|
el.loop = name !== 'win' && name !== 'lose';
|
|
el.addEventListener('canplay', () => { fileState[name] = 'ok'; files[name] = el; cb(el); }, { once: true });
|
|
el.addEventListener('error', () => { fileState[name] = 'missing'; cb(null); }, { once: true });
|
|
el.src = MUSIC_DIR + encodeURIComponent(f).replace(/%2F/g, '/');
|
|
el.load();
|
|
});
|
|
}
|
|
|
|
function fadeEl(el, to, ms, done) {
|
|
const from = el.volume, t0 = performance.now();
|
|
const step = () => {
|
|
const k = Math.min(1, (performance.now() - t0) / ms);
|
|
try { el.volume = Math.max(0, Math.min(1, from + (to - from) * k)); } catch (e) { /* ignore */ }
|
|
if (k < 1) requestAnimationFrame(step); else if (done) done();
|
|
};
|
|
step();
|
|
}
|
|
|
|
function stopCurrent(fade) {
|
|
const c = current; current = null;
|
|
if (!c || c.kind === 'pending') return;
|
|
if (c.kind === 'synth') c.stop(fade);
|
|
else fadeEl(c.el, 0, (fade || 0.8) * 1000, () => { try { c.el.pause(); } catch (e) { /* ignore */ } });
|
|
}
|
|
|
|
function applyMusic() {
|
|
if (!unlocked) return;
|
|
if (wanted) stopStinger(0.8);
|
|
if (!wanted || muted) { stopCurrent(0.4); return; }
|
|
if (current && current.name === wanted) return;
|
|
const name = wanted;
|
|
stopCurrent(0.9);
|
|
// placeholder so that rapid calls do not stack
|
|
const token = current = { name, kind: 'pending', stop() {} };
|
|
fileFor(name, (el) => {
|
|
if (current !== token) return; // superseded while loading
|
|
if (el) {
|
|
el.currentTime = 0; el.volume = 0;
|
|
const pr = el.play();
|
|
if (pr && pr.catch) pr.catch(() => { /* blocked: will retry on next gesture */ current = null; });
|
|
current = { name, kind: 'file', el, stop() {} };
|
|
fadeEl(el, 0.8 * musicVol, 1200);
|
|
} else {
|
|
const c = ensureCtx();
|
|
current = c ? startSynth(name) : null;
|
|
if (current) current.name = name;
|
|
}
|
|
});
|
|
}
|
|
|
|
let stingEl = null;
|
|
function stopStinger(fade) {
|
|
const el = stingEl; stingEl = null;
|
|
if (el) fadeEl(el, 0, (fade || 0.6) * 1000, () => { try { el.pause(); } catch (e) { /* ignore */ } });
|
|
}
|
|
function stinger(name) {
|
|
if (muted || !unlocked) return;
|
|
fileFor(name, (el) => {
|
|
if (el) { try { stopStinger(0.2); stingEl = el; el.currentTime = 0; el.volume = Math.min(1, 0.9 * Math.max(0.3, musicVol)); el.play().catch(() => {}); } catch (e) { /* ignore */ } return; }
|
|
if (name === 'win') { [0, 4, 7, 12, 16, 19, 24].forEach((n, i) => tone(NOTE(69 + n), 0.3, 'triangle', 0.22, 0, i * 0.11)); }
|
|
else { [0, -3, -7, -12, -17].forEach((n, i) => tone(NOTE(60 + n), 0.5, 'sawtooth', 0.2, NOTE(58 + n), i * 0.22)); }
|
|
});
|
|
}
|
|
|
|
// ---------------------------------------------------------------- public
|
|
function unlock() {
|
|
if (unlocked) return;
|
|
const c = ensureCtx();
|
|
if (c && c.state === 'suspended') c.resume();
|
|
unlocked = true;
|
|
applyMusic();
|
|
}
|
|
|
|
root.addEventListener('pointerdown', unlock, { passive: true });
|
|
root.addEventListener('keydown', unlock, { passive: true });
|
|
document.addEventListener('visibilitychange', () => {
|
|
if (!ctx) return;
|
|
if (document.hidden) {
|
|
ctx.suspend && ctx.suspend();
|
|
if (current && current.kind === 'file') current.el.pause();
|
|
} else {
|
|
ctx.resume && ctx.resume();
|
|
if (current && current.kind === 'file' && !muted) current.el.play().catch(() => {});
|
|
}
|
|
});
|
|
|
|
NW.Audio = {
|
|
sfx,
|
|
unlock,
|
|
stinger,
|
|
get muted() { return muted; },
|
|
get now() { return current ? { name: current.name, kind: current.kind } : null; }, // for tests / debugging
|
|
setMuted(m) {
|
|
muted = !!m; save();
|
|
if (master) master.gain.value = muted ? 0 : 0.9;
|
|
if (muted) stopCurrent(0.2); else applyMusic();
|
|
},
|
|
toggleMuted() { this.setMuted(!muted); return muted; },
|
|
// Which music the game wants right now: 'theme' | 'battle' | 'boss' | null
|
|
music(name) { wanted = name; applyMusic(); },
|
|
get musicVolume() { return musicVol; },
|
|
setMusicVolume(v) {
|
|
musicVol = Math.min(1, Math.max(0, v)); save();
|
|
if (musBus) musBus.gain.value = 0.3 * musicVol;
|
|
if (current && current.kind === 'file') current.el.volume = 0.8 * musicVol;
|
|
},
|
|
};
|
|
})(typeof self !== 'undefined' ? self : this);
|