// tsbutt webapp logic — DOM-free so test.html can exercise it with a fake // clock. All device interaction goes through `ports`: // // ports.sendVibrate(id, percent01) — vibrate one vibrator at 0..1; may // throw or reject on failure // ports.sendStop(id) — stop one vibrator (may throw/reject) // ports.stopAll() — stop every device (emergency stop) // ports.now() — milliseconds // ports.schedule(fn, delayMs) — one-shot timer handle // ports.cancel(handle) — clear timer // ports.onError(err) — optional failed-command reporter // ports.onChange() — optional registry/state change hook // ports.onEmergencyStop() — optional hook run when halting (modes // use it to stop their own drivers) // // Every vibrator is addressed by a stable id ("deviceIndex:featureIndex"). // The output for each vibrator is computed by ONE codepath: a hold override // ("max" or "stop") if one is active, otherwise the base value supplied by // the active mode's base provider. Modes switch providers via // setBaseProvider(); devices may be added or removed at any time via // setVibrators() and every vibrator immediately joins the current base. // // Safety invariants: any disconnect, page hide, or failed command halts // everything and issues a stop. Emergency stop also clears holds and resets // all slider set-points to 0. export const MIN_COMMAND_INTERVAL_MS = 100; export function clampPercent(pct) { if (typeof pct !== "number" || Number.isNaN(pct)) return 0; return Math.min(100, Math.max(0, pct)); } export function vibratorId(deviceIndex, featureIndex) { return `${deviceIndex}:${featureIndex}`; } // Normalize a list of vibrator descriptors ({deviceIndex, featureIndex, // deviceName, featureLabel}) into stable, deduplicated snapshots. export function sanitizeVibrators(list) { if (!Array.isArray(list)) return []; const seen = new Set(); const out = []; for (const d of list) { if (!d) continue; if (typeof d.deviceIndex !== "number" || typeof d.featureIndex !== "number") continue; const id = vibratorId(d.deviceIndex, d.featureIndex); if (seen.has(id)) continue; seen.add(id); out.push({ id, deviceIndex: d.deviceIndex, featureIndex: d.featureIndex, deviceName: String(d.deviceName ?? "unknown device"), featureLabel: String(d.featureLabel ?? "?"), }); } return out; } export function createVibrationManager(ports) { // id -> {id, deviceIndex, featureIndex, deviceName, featureLabel, // slider, hold, lastSentPct, lastSentAt, pendingTrailing} const vibrators = new Map(); let connected = false; let halted = true; // safety latch; lifted by handleConnected/handleVisible let baseProvider = null; // (vibratorState) => percent 0..100 function snapshot(st) { return { id: st.id, deviceIndex: st.deviceIndex, featureIndex: st.featureIndex, deviceName: st.deviceName, featureLabel: st.featureLabel, slider: st.slider, hold: st.hold, }; } function onChange() { if (typeof ports.onChange === "function") { try { ports.onChange(); } catch { /* UI render failures must never affect device state */ } } } function cancelPending(st) { if (st.pendingTrailing !== null) { ports.cancel(st.pendingTrailing); st.pendingTrailing = null; } } function baseFor(st) { if (typeof baseProvider === "function") { try { return clampPercent(baseProvider(st)); } catch { return 0; } } // No mode installed: direct control falls back to the slider set-point. return st.slider; } function effective(st) { if (st.hold === "max") return 100; if (st.hold === "stop") return 0; return baseFor(st); } // dispatch funnels every device command through safety handling: buttplug // commands are async, so failures surface as rejections, and ports may also // throw synchronously (e.g. device vanished). Either way a failed command // halts everything and issues a stop — including from timer callbacks, // which have no other try/catch around them. function dispatch(issue) { let result; try { result = issue(); } catch (err) { handleCommandError(err); return; } Promise.resolve(result).catch((err) => handleCommandError(err)); } function sendNow(st, pct) { st.lastSentPct = pct; st.lastSentAt = ports.now(); if (pct === 0) { dispatch(() => ports.sendStop(st.id)); } else { dispatch(() => ports.sendVibrate(st.id, pct / 100)); } } // Bring one vibrator's output to its current effective value. Skips work // when the value is unchanged; nonzero values are throttled per vibrator // with a trailing send so the latest value always lands. function sync(id, force = false) { const st = vibrators.get(id); if (!st) return; const pct = halted ? 0 : effective(st); if (!force && pct === st.lastSentPct) return; st.lastSentPct = pct; if (pct === 0) { // Stops are never throttled; they must land immediately. cancelPending(st); if (!connected) return; st.lastSentAt = ports.now(); dispatch(() => ports.sendStop(st.id)); return; } if (!connected) return; const elapsed = ports.now() - st.lastSentAt; if (elapsed >= MIN_COMMAND_INTERVAL_MS) { sendNow(st, pct); return; } // Inside the throttle window: make sure the latest value is sent once it // closes. A later sync reschedules nothing and stacks nothing — the // trailing callback reads the effective value at fire time. if (st.pendingTrailing === null) { st.pendingTrailing = ports.schedule(() => { st.pendingTrailing = null; if (!connected || halted) return; const pctNow = effective(st); sendNow(st, pctNow); }, MIN_COMMAND_INTERVAL_MS - elapsed); } } function refreshBase() { for (const st of vibrators.values()) sync(st.id); } // --- registry ------------------------------------------------------------ // Replace the vibrator set. Removed vibrators are dropped (their device is // gone; the server has already stopped it). Added vibrators start with a // 0 slider, no hold, and immediately sync to the current base so they join // whatever the active mode is doing. function setVibrators(descriptors) { const list = sanitizeVibrators(descriptors); const next = new Map(); for (const d of list) { const prev = vibrators.get(d.id); next.set( d.id, prev ?? { id: d.id, deviceIndex: d.deviceIndex, featureIndex: d.featureIndex, deviceName: d.deviceName, featureLabel: d.featureLabel, slider: 0, hold: null, lastSentPct: 0, lastSentAt: -Infinity, pendingTrailing: null, }, ); } const changed = next.size !== vibrators.size || [...next.keys()].some((id) => !vibrators.has(id)) || [...next.values()].some( (st) => st.deviceName !== vibrators.get(st.id)?.deviceName || st.featureLabel !== vibrators.get(st.id)?.featureLabel, ); vibrators.clear(); for (const [k, v] of next) vibrators.set(k, v); refreshBase(); if (changed) onChange(); } // --- controls ------------------------------------------------------------ // Direct-control set-point. Applies immediately unless a hold is active; // the hold release then returns output to this value. function setSlider(id, pct) { const st = vibrators.get(id); if (!st) return; st.slider = clampPercent(pct); if (st.hold === null) sync(id); } function setHold(id, kind) { const st = vibrators.get(id); if (!st) return; if (kind !== "max" && kind !== "stop") return; st.hold = kind; sync(id); } function releaseHold(id) { const st = vibrators.get(id); if (!st || st.hold === null) return; st.hold = null; sync(id); } // --- mode abstraction ---------------------------------------------------- // The active mode installs a provider; it is consulted for every vibrator // on every sync. Pass null for "everything at 0". function setBaseProvider(fn) { baseProvider = fn; refreshBase(); } // --- safety events ------------------------------------------------------- // Stop everything now: clear holds, reset slider set-points, halt all // timers, and issue a global stop. `latch` keeps controls halted afterwards // (used by safety events: page hide, failed commands); the user-facing // emergency stop button passes latch:false so the app stays operable. function emergencyStop({ latch = true } = {}) { halted = latch; for (const st of vibrators.values()) { st.hold = null; st.slider = 0; st.lastSentPct = 0; cancelPending(st); } if (typeof ports.onEmergencyStop === "function") { try { ports.onEmergencyStop(); } catch { /* mode cleanup must not block the stop */ } } if (connected) { // Reported directly rather than through dispatch: a failure here must // not re-enter emergencyStop. try { const r = ports.stopAll(); if (r && typeof r.catch === "function") { r.catch((err) => ports.onError?.(err)); } } catch (err) { ports.onError?.(err); } } onChange(); } function handleCommandError(err) { emergencyStop(); if (ports.onError) ports.onError(err); } function handleDisconnect() { const wasConnected = connected; connected = false; halted = true; for (const st of vibrators.values()) { st.hold = null; st.slider = 0; st.lastSentPct = 0; cancelPending(st); } return wasConnected; } function handlePageHide() { emergencyStop(); } function handleConnected() { connected = true; halted = false; // Devices were stopped at disconnect; desired state is all zeros, so a // plain (deduplicated) refresh is enough. refreshBase(); } // handleVisible undoes the halt from handlePageHide for the common // app-switch case (hidden then visible with no disconnect). Emergency stop // already reset sliders to 0, so nothing vibrates on resume until the user // or an active mode drives output again. function handleVisible() { if (connected) { halted = false; refreshBase(); } } return { // state queries (for tests/UI) vibrators: () => [...vibrators.values()].map(snapshot), vibrator: (id) => { const st = vibrators.get(id); return st ? snapshot(st) : undefined; }, isConnected: () => connected, isHalted: () => halted, // connection lifecycle handleConnected, handleDisconnect, handlePageHide, handleVisible, handleCommandError, emergencyStop, // registry + modes setVibrators, setBaseProvider, refreshBase, // controls setSlider, setHold, releaseHold, }; } // --- pattern engine -------------------------------------------------------- // A pattern is one waveform per vibrator: PATTERN_SAMPLES values (0..100) // played in sync over a configurable loop length. The engine is a mode // driver: while playing it is consulted through the manager's base provider // (installed by the caller) and it calls refreshBase() on every tick, so // output flows through the exact same codepath as direct control. Editing a // waveform mid-playback takes effect immediately. export const PATTERN_SAMPLES = 64; export const MIN_LOOP_SECONDS = 0.5; export const MAX_LOOP_SECONDS = 60; const PATTERN_TICK_MS = 40; export function clampLoopSeconds(s) { const n = Number(s); if (!Number.isFinite(n)) return 4; return Math.min(MAX_LOOP_SECONDS, Math.max(MIN_LOOP_SECONDS, n)); } export function createPatternEngine(manager, ports) { const waves = new Map(); // vibrator id -> Float32Array(PATTERN_SAMPLES), 0..100 let loopMs = 4000; let playing = false; let pausedPhase = 0; // phase (0..1) to resume from when stopped/paused let startAt = 0; // timestamp at which the current loop's phase was 0 let tickTimer = null; function cancelTick() { if (tickTimer !== null) { ports.cancel(tickTimer); tickTimer = null; } } function tick() { tickTimer = null; if (!playing) return; manager.refreshBase(); tickTimer = ports.schedule(tick, PATTERN_TICK_MS); } function currentPhase() { if (!playing) return pausedPhase; return ((ports.now() - startAt) % loopMs) / loopMs; } // Linear interpolation between neighboring samples, using the same // index mapping as the editor's x axis (phase * (N-1)); no wrap, so the // loop point plays samples[N-1] then jumps to samples[0]. function sampleWave(id, phase) { const w = waves.get(id); if (!w) return 0; const x = Math.min(PATTERN_SAMPLES - 1, phase * (PATTERN_SAMPLES - 1)); const i = Math.floor(x); const frac = x - i; const a = w[i] ?? 0; const b = w[Math.min(PATTERN_SAMPLES - 1, i + 1)] ?? 0; return a + (b - a) * frac; } // --- transport --- function play() { if (playing) return; startAt = ports.now() - pausedPhase * loopMs; pausedPhase = 0; playing = true; cancelTick(); tick(); } function restart() { pausedPhase = 0; if (playing) { startAt = ports.now(); manager.refreshBase(); } else { play(); } } function pause() { if (!playing) return; pausedPhase = currentPhase(); playing = false; cancelTick(); manager.refreshBase(); // paused outputs zero; position is retained } function stop() { playing = false; pausedPhase = 0; cancelTick(); manager.refreshBase(); } function setLoopSeconds(s) { const clamped = clampLoopSeconds(s); if (clamped * 1000 === loopMs) return; const phase = currentPhase(); // keep position across the change loopMs = clamped * 1000; if (playing) startAt = ports.now() - phase * loopMs; } // --- waveforms --- function waveData(id) { let w = waves.get(id); if (!w) { w = new Float32Array(PATTERN_SAMPLES); waves.set(id, w); } return w; } function waveEdited(id) { if (waves.has(id)) manager.refreshBase(); } // Keep the wave map in step with the vibrator registry: new vibrators get // a flat 0 waveform, removed ones are dropped. function syncVibrators(vibrators) { const ids = new Set(vibrators.map((v) => v.id)); for (const id of ids) waveData(id); for (const id of [...waves.keys()]) { if (!ids.has(id)) waves.delete(id); } } function waveSnapshot() { const out = {}; for (const [id, w] of waves) out[id] = [...w]; return out; } function loadWaves(saved, loopSeconds) { waves.clear(); if (saved && typeof saved === "object") { for (const [id, arr] of Object.entries(saved)) { if (!Array.isArray(arr)) continue; const w = new Float32Array(PATTERN_SAMPLES); for (let i = 0; i < Math.min(PATTERN_SAMPLES, arr.length); i++) { w[i] = clampPercent(Number(arr[i])); } waves.set(id, w); } } if (loopSeconds !== undefined) loopMs = clampLoopSeconds(loopSeconds) * 1000; } return { play, restart, pause, stop, isPlaying: () => playing, phase: currentPhase, sample: (id) => sampleWave(id, currentPhase()), loopSeconds: () => loopMs / 1000, setLoopSeconds, waveData, waveEdited, syncVibrators, waveSnapshot, loadWaves, }; } // --- freehand intensity curve ---------------------------------------------- // Intensity for one vibrator given the distance from the selected point to // the vibrator's center, expressed as a fraction of that vibrator's ring // radius (0 = at the center, 1 = on the ring edge, >1 = outside). Falloff is // (1 - d)^gamma: gamma 1 is linear, higher gamma concentrates intensity near // the center, lower gamma spreads it toward the edge. The UI visualizes the // curve as the alpha gradient of a ring's shading (capped below full // opacity so overlaid interface elements stay visible). export const FREEHAND_MIN_GAMMA = 0.3; export const FREEHAND_MAX_GAMMA = 4; export const FREEHAND_MAX_SHADE_ALPHA = 0.6; export function clampGamma(g) { const n = Number(g); if (!Number.isFinite(n)) return 1; return Math.min(FREEHAND_MAX_GAMMA, Math.max(FREEHAND_MIN_GAMMA, n)); } export function freehandIntensity(distanceToRadius, gamma = 1) { const d = Number(distanceToRadius); if (!Number.isFinite(d) || d < 0) return 0; if (d >= 1) return 0; return clampPercent(100 * Math.pow(1 - d, clampGamma(gamma))); } // Shade opacity across the ring visualizes the DERIVATIVE of the // distance-intensity curve rather than the curve itself, so the shading // communicates how fast intensity changes: a constant transparency means // intensity falls off linearly (gamma 1), a bright middle with transparent // edge means intensity is concentrated near the center (gamma > 1), and a // brightening edge means intensity is held until near the edge (gamma < 1). // Always capped below full opacity so overlaid elements stay visible. export function freehandShadeAlpha(distanceToRadius, gamma = 1) { const n = Number(distanceToRadius); if (!Number.isFinite(n)) return 0; const d = Math.min(1, Math.max(0, n)); const g = clampGamma(gamma); // Slope of (1-d)^g up to a constant factor: (1-d)^(g-1). let slope; if (g >= 1) { slope = Math.pow(1 - d, g - 1); // 1 at the center; 0 at the edge if g > 1 } else { // The slope grows without bound toward the edge; normalize against // d = 0.95 so the ramp reaches full strength just before the edge. slope = Math.pow(1 - d, g - 1) / Math.pow(0.05, g - 1); } return Math.min(1, slope) * FREEHAND_MAX_SHADE_ALPHA; }