diff --git a/tsbridge/webapp/app.js b/tsbridge/webapp/app.js index e65c337..d925a5a 100644 --- a/tsbridge/webapp/app.js +++ b/tsbridge/webapp/app.js @@ -1,9 +1,8 @@ // tsbutt webapp — DOM wiring. All vibration logic lives in logic.js; this -// file connects it to buttplug.js and the page, and renders the vibrator -// list. Every vibrator (one vibrate-capable feature on one device) gets its -// own slider, hold-to-max and hold-to-stop buttons. Devices may appear or -// disappear at any time; the registry diff in logic.js keeps output state -// consistent and the UI re-renders from manager state. +// file connects it to buttplug.js and the page, renders the vibrator list, +// and hosts the mode system. Every mode drives output through the same +// manager codepath (a base provider); devices may appear or disappear at +// any time and every view re-renders from manager state. import { ButtplugBrowserWebsocketClientConnector, @@ -13,7 +12,12 @@ import { InputType, OutputType, } from "./vendor/buttplug.mjs"; -import { createVibrationManager, vibratorId } from "./logic.js"; +import { + createVibrationManager, + createPatternEngine, + vibratorId, + PATTERN_SAMPLES, +} from "./logic.js"; // --- helpers ------------------------------------------------------------- @@ -71,8 +75,8 @@ const manager = createVibrationManager({ log(`command error: ${err?.message ?? err}`); }, onEmergencyStop() { - // Future modes stop their own drivers here; direct control has nothing - // beyond the manager's own reset. + // Every mode stops its own driver here; the manager handles the rest. + patternEngine.stop(); }, onChange: render, }); @@ -85,6 +89,88 @@ function runCommand(fn) { } } +// --- pattern engine ------------------------------------------------------ + +const patternEngine = createPatternEngine(manager, { + now: () => performance.now(), + schedule: (fn, ms) => setTimeout(fn, ms), + cancel: (h) => clearTimeout(h), +}); + +// The pattern mode's base provider: while playing, every vibrator is driven +// by its waveform at the current phase; otherwise it rests at 0. +const patternProvider = (st) => (patternEngine.isPlaying() ? patternEngine.sample(st.id) : 0); + +const PATTERN_STORE_KEY = "tsbutt.pattern2"; + +function savePatternState() { + try { + localStorage.setItem( + PATTERN_STORE_KEY, + JSON.stringify({ + loop: patternEngine.loopSeconds(), + waves: patternEngine.waveSnapshot(), + }), + ); + } catch { + /* private mode etc. — the pattern just won't persist */ + } +} + +function loadPatternState() { + let parsed = null; + try { + parsed = JSON.parse(localStorage.getItem(PATTERN_STORE_KEY) ?? "null"); + } catch { + /* fall through to defaults */ + } + patternEngine.loadWaves(parsed?.waves, parsed?.loop); + $("pat-loop").value = String(patternEngine.loopSeconds()); +} + +// --- mode system --------------------------------------------------------- + +const modes = { + direct: { + view: "view-direct", + tab: "tab-direct", + activate() { + // No provider: the manager falls back to the slider set-points. + manager.setBaseProvider(null); + }, + deactivate() {}, + }, + pattern: { + view: "view-pattern", + tab: "tab-pattern", + activate() { + manager.setBaseProvider(patternProvider); + }, + deactivate() { + patternEngine.stop(); + }, + }, +}; +let activeMode = "direct"; + +function switchMode(name) { + if (name === activeMode || !modes[name]) return; + modes[activeMode].deactivate(); + activeMode = name; + for (const [key, m] of Object.entries(modes)) { + $(m.view).classList.toggle("hidden", key !== name); + const tab = $(m.tab); + tab.classList.toggle("active", key === name); + tab.setAttribute("aria-selected", String(key === name)); + } + modes[name].activate(); + updateTransport(); +} + +for (const [key, m] of Object.entries(modes)) { + $(m.tab).addEventListener("click", () => switchMode(key)); +} + // --- buttplug client ----------------------------------------------------- let client = null; @@ -121,6 +207,7 @@ function refreshRegistry() { } } manager.setVibrators(descriptors); + patternEngine.syncVibrators(manager.vibrators()); } // --- battery polling ----------------------------------------------------- @@ -166,10 +253,16 @@ function startBatteryPolling() { // --- rendering ----------------------------------------------------------- -// Renders the direct-control view from manager state. Called on registry -// changes, connection changes, and emergency stop; slider drags do not -// re-render (the manager holds the value). +// Renders both views from manager state. Called on registry changes, +// connection changes, and emergency stop; slider drags and waveform edits do +// not re-render (the manager/engine hold the values). function render() { + renderDeviceList(); + renderPatternRows(); + updateTransport(); +} + +function renderDeviceList() { const host = $("device-list"); const connected = manager.isConnected(); host.textContent = ""; @@ -262,7 +355,7 @@ function vibratorRow(v, connected) { } // Hold buttons: output runs at the hold level while pressed and returns to -// the slider value on release (handled by the manager). +// the base value on release (handled by the manager). Used by both modes. function wireHold(btn, id, kind) { btn.addEventListener("pointerdown", (e) => { e.preventDefault(); @@ -280,6 +373,185 @@ function wireHold(btn, id, kind) { btn.addEventListener("contextmenu", (e) => e.preventDefault()); } +// --- pattern view --------------------------------------------------------- + +function renderPatternRows() { + const host = $("pattern-rows"); + host.textContent = ""; + for (const v of manager.vibrators()) host.append(patternRow(v)); +} + +function patternRow(v) { + const row = document.createElement("div"); + row.className = "prow"; + + // Small unlabeled hold buttons, stacked vertically to leave the waveform + // maximum width. Same colors as the direct-control hold buttons. + const btns = document.createElement("div"); + btns.className = "pbtns"; + const maxBtn = document.createElement("button"); + maxBtn.type = "button"; + maxBtn.className = "hold hold-max glyph"; + maxBtn.textContent = "⏫"; + maxBtn.setAttribute("aria-label", `${v.deviceName} ${v.featureLabel}: hold to vibrate at maximum`); + maxBtn.title = "Hold to max"; + wireHold(maxBtn, v.id, "max"); + const stopBtn = document.createElement("button"); + stopBtn.type = "button"; + stopBtn.className = "hold hold-stop glyph"; + stopBtn.textContent = "⏹"; + stopBtn.setAttribute("aria-label", `${v.deviceName} ${v.featureLabel}: hold to stop`); + stopBtn.title = "Hold to stop"; + wireHold(stopBtn, v.id, "stop"); + btns.append(maxBtn, stopBtn); + row.append(btns); + + const wrap = document.createElement("div"); + wrap.className = "pwave-wrap"; + + // Waveform editor: viewBox 0 0 100 100 stretched to the row width; x maps + // to sample index phase*(N-1), y to intensity (top = 100%). + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + svg.setAttribute("class", "wave"); + svg.setAttribute("viewBox", "0 0 100 100"); + svg.setAttribute("preserveAspectRatio", "none"); + + const zero = document.createElementNS("http://www.w3.org/2000/svg", "line"); + zero.setAttribute("class", "wave-zero"); + zero.setAttribute("x1", "0"); + zero.setAttribute("x2", "100"); + zero.setAttribute("y1", "100"); + zero.setAttribute("y2", "100"); + svg.append(zero); + + const line = document.createElementNS("http://www.w3.org/2000/svg", "polyline"); + line.setAttribute("class", "wave-line"); + line.setAttribute("vector-effect", "non-scaling-stroke"); + svg.append(line); + + const head = document.createElementNS("http://www.w3.org/2000/svg", "line"); + head.setAttribute("class", "wave-head"); + head.setAttribute("vector-effect", "non-scaling-stroke"); + head.setAttribute("visibility", "hidden"); + head.setAttribute("y1", "0"); + head.setAttribute("y2", "100"); + svg.append(head); + + updateWaveLine(line, patternEngine.waveData(v.id)); + + let editing = false; + let editCol = null; + const applyEdit = (e) => { + const rect = svg.getBoundingClientRect(); + const x01 = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width)); + const y01 = Math.min(1, Math.max(0, 1 - (e.clientY - rect.top) / rect.height)); + const col = Math.round(x01 * (PATTERN_SAMPLES - 1)); + const data = patternEngine.waveData(v.id); + if (editCol === null || editCol === col) { + data[col] = y01 * 100; + } else { + // Fill the span between the last and current column (interpolated) + // so fast drags don't leave gaps. + const startVal = data[editCol]; + for (let i = Math.min(editCol, col); i <= Math.max(editCol, col); i++) { + const t = (i - editCol) / (col - editCol); + data[i] = startVal + (y01 * 100 - startVal) * t; + } + } + editCol = col; + updateWaveLine(line, data); + patternEngine.waveEdited(v.id); + }; + svg.addEventListener("pointerdown", (e) => { + e.preventDefault(); + svg.setPointerCapture(e.pointerId); + editing = true; + editCol = null; + applyEdit(e); + }); + svg.addEventListener("pointermove", (e) => { + if (!editing) return; + applyEdit(e); + }); + for (const ev of ["pointerup", "pointercancel"]) { + svg.addEventListener(ev, () => { + if (!editing) return; + editing = false; + savePatternState(); + }); + } + svg.addEventListener("contextmenu", (e) => e.preventDefault()); + + wrap.append(svg); + // Label sits inside the waveform's top-left corner so rows stay compact. + const tag = document.createElement("div"); + tag.className = "wave-tag"; + tag.textContent = `${v.deviceName} · ${v.featureLabel}`; + wrap.append(tag); + row.append(wrap); + return row; +} + +function updateWaveLine(line, data) { + const pts = []; + for (let i = 0; i < PATTERN_SAMPLES; i++) { + pts.push(`${((i / (PATTERN_SAMPLES - 1)) * 100).toFixed(2)},${(100 - data[i]).toFixed(2)}`); + } + line.setAttribute("points", pts.join(" ")); +} + +// Playhead: one rAF loop drives the scanning bar across every waveform while +// the pattern plays. +let headRaf = null; +function playheadFrame() { + headRaf = null; + const heads = document.querySelectorAll(".wave-head"); + if (!patternEngine.isPlaying()) { + for (const h of heads) h.setAttribute("visibility", "hidden"); + return; + } + const x = (patternEngine.phase() * 100).toFixed(2); + for (const h of heads) { + h.setAttribute("visibility", "visible"); + h.setAttribute("x1", x); + h.setAttribute("x2", x); + } + headRaf = requestAnimationFrame(playheadFrame); +} + +function ensurePlayhead() { + if (headRaf === null) headRaf = requestAnimationFrame(playheadFrame); +} + +function updateTransport() { + const playing = patternEngine.isPlaying(); + $("pat-play").classList.toggle("active", playing); + $("pat-pause").disabled = !playing; + ensurePlayhead(); +} + +$("pat-play").addEventListener("click", () => { + runCommand(() => patternEngine.play()); + updateTransport(); +}); +$("pat-restart").addEventListener("click", () => { + runCommand(() => patternEngine.restart()); + updateTransport(); +}); +$("pat-pause").addEventListener("click", () => { + runCommand(() => patternEngine.pause()); + updateTransport(); +}); +$("pat-stop").addEventListener("click", () => { + runCommand(() => patternEngine.stop()); + updateTransport(); +}); +$("pat-loop").addEventListener("change", () => { + patternEngine.setLoopSeconds(Number($("pat-loop").value)); + $("pat-loop").value = String(patternEngine.loopSeconds()); + savePatternState(); +}); + // --- connection ---------------------------------------------------------- async function connect() { @@ -293,6 +565,7 @@ async function connect() { batteryText.clear(); stopBatteryPolling(); manager.setVibrators([]); + patternEngine.syncVibrators([]); manager.handleDisconnect(); setPill("bad", "disconnected"); scheduleReconnect(); @@ -345,6 +618,7 @@ function scheduleReconnect() { $("estop").addEventListener("click", () => { // Unlatched: stop and reset everything now, but keep the app operable. runCommand(() => manager.emergencyStop({ latch: false })); + updateTransport(); }); $("rescan").addEventListener("click", () => { if (client?.connected) client.startScanning().catch((e) => log(`scan: ${e.message}`)); @@ -358,6 +632,7 @@ document.addEventListener("visibilitychange", () => { } else { manager.handleVisible(); } + updateTransport(); }); window.addEventListener("pagehide", () => manager.handlePageHide()); // Last-resort net: any rejection that escapes every handler must still stop @@ -366,5 +641,6 @@ window.addEventListener("unhandledrejection", () => manager.emergencyStop()); // --- boot ---------------------------------------------------------------- +loadPatternState(); connect(); log(`webapp loaded; ws target ${wsURL()}`); diff --git a/tsbridge/webapp/index.html b/tsbridge/webapp/index.html index 90f7e44..d5dca05 100644 --- a/tsbridge/webapp/index.html +++ b/tsbridge/webapp/index.html @@ -16,12 +16,38 @@ + +
+ + +
diff --git a/tsbridge/webapp/logic.js b/tsbridge/webapp/logic.js index bac16f6..100bddb 100644 --- a/tsbridge/webapp/logic.js +++ b/tsbridge/webapp/logic.js @@ -358,3 +358,172 @@ export function createVibrationManager(ports) { 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, + }; +} diff --git a/tsbridge/webapp/style.css b/tsbridge/webapp/style.css index 2f6e8dd..ea2aeec 100644 --- a/tsbridge/webapp/style.css +++ b/tsbridge/webapp/style.css @@ -156,6 +156,119 @@ input[type="range"] { .hold.holding { filter: brightness(1.35); } .empty-note { padding: 0.5rem 0.2rem; } +/* --- mode tabs ----------------------------------------------------------- */ + +#mode-tabs { + display: flex; + gap: 0.4rem; +} +.tab { + flex: 1; + background: var(--card); + color: var(--muted); + padding: 0.6rem 0.4rem; + font-size: 0.95rem; + border-radius: var(--radius); +} +.tab.active { + background: var(--accent); + color: white; +} + +/* --- pattern mode --------------------------------------------------------- */ + +.transport { + display: flex; + gap: 0.4rem; + flex-wrap: wrap; +} +.transport button { flex: 1; padding: 0.6rem 0.4rem; font-size: 0.9rem; } +.transport button.active { filter: brightness(1.3); } +.loop-row { + display: flex; + align-items: center; + gap: 0.5rem; + margin-top: 0.6rem; + font-size: 0.9rem; +} +.loop-row input { + width: 5rem; + background: var(--bg); + color: var(--text); + border: 1px solid #33333c; + border-radius: 8px; + padding: 0.4rem; + font-size: 0.95rem; +} + +.prow { + display: flex; + align-items: stretch; + gap: 0.4rem; + background: var(--card); + border-radius: var(--radius); + padding: 0.25rem 0.4rem; +} +.prow + .prow { margin-top: 0.25rem; } +.pbtns { + display: flex; + flex-direction: column; + gap: 0.3rem; + justify-content: center; +} +.pbtns .glyph { + width: 2.4rem; + padding: 0.35rem 0; + font-size: 1rem; + line-height: 1; +} +.pwave-wrap { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 0.15rem; + position: relative; +} +.wave-tag { + position: absolute; + top: 4px; + left: 8px; + font-size: 0.7rem; + color: var(--muted); + pointer-events: none; + max-width: calc(100% - 16px); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.wave { + width: 100%; + /* Tall enough for fine vertical adjustments. */ + height: 9rem; + background: var(--bg); + border: 1px solid #33333c; + border-radius: 8px; + touch-action: none; /* drags edit the waveform instead of scrolling */ + cursor: crosshair; +} +.wave-zero { + stroke: #33333c; + stroke-width: 1; + vector-effect: non-scaling-stroke; +} +.wave-line { + fill: none; + stroke: var(--accent); + stroke-width: 2; + vector-effect: non-scaling-stroke; +} +.wave-head { + stroke: var(--warn); + stroke-width: 2; + vector-effect: non-scaling-stroke; +} + /* --- emergency stop dock ------------------------------------------------- */ /* Fixed to the bottom of the viewport in every view; nothing may cover it. */ diff --git a/tsbridge/webapp/test.html b/tsbridge/webapp/test.html index 765fb1f..e3890de 100644 --- a/tsbridge/webapp/test.html +++ b/tsbridge/webapp/test.html @@ -18,9 +18,12 @@