FOSFENO/web/panel/panel.js
hacklab 8dd58bb293 Mapping in-browser (Fase 1) + trabajo en curso
Projection mapping editable desde el navegador, sin herramientas externas:
- web/stage/mapper.js (nuevo): compositor WebGL que texturiza el motor activo
  sobre superficies deformables (homografia por vertice: keystone correcto).
- Editor con raton en el escenario (crear, arrastrar esquinas, mover, borrar)
  y previsualizacion arrastrable en el panel (raton/tactil) para editar desde
  el movil sin tocar la ventana de visuales.
- Backend: estado "mapping" + evento set_mapping, persistido en data/mapping.json
  (ignorado en git). Seccion "Mapping" en el panel + texto de ayuda.
- Solo motores web (butterchurn/hydra/shaders/mixer); projectM no se mapea.
- .gitignore: excluye config de runtime (mapping.json, pm-favoritos.json).

Incluye ademas trabajo en curso previo sin commitear (server.py, stage.js,
panel.js/css, ayuda.json, hydra-sketches.json, problemas.md,
start-projectm.sh), subido junto a peticion del autor.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-27 00:19:30 +02:00

843 lines
33 KiB
JavaScript

/*
* FOSFENO :: Panel de control
* Conecta con el servidor, refleja el estado y envia ordenes.
* Incluye editor de codigo, mezclador VJ, ventana de ayuda y avisos.
*/
const socket = io();
let state = null;
let editorEngine = ""; // que motor tiene cargado el editor
let helpData = {}; // textos de ayuda
let lastNotifT = 0; // marca de tiempo del ultimo aviso mostrado
const $ = (s) => document.querySelector(s);
const $$ = (s) => document.querySelectorAll(s);
// Sliders del mezclador VJ (se generan dinamicamente)
const MIXER_SLIDERS = [
{ key: "mix", label: "Mezcla A/B", min: 0, max: 1, step: 0.01 },
{ key: "hue", label: "Tono (hue)", min: 0, max: 1, step: 0.01 },
{ key: "saturate", label: "Saturacion", min: 0, max: 3, step: 0.05 },
{ key: "contrast", label: "Contraste", min: 0, max: 3, step: 0.05 },
{ key: "brightness", label: "Brillo", min: -0.5, max: 0.5, step: 0.02 },
{ key: "colorama", label: "Colorama", min: 0, max: 1, step: 0.01 },
{ key: "posterize", label: "Posterizar", min: 0, max: 8, step: 1 },
{ key: "pixelate", label: "Pixelado", min: 0, max: 1, step: 0.02 },
{ key: "kaleid", label: "Caleidoscopio", min: 0, max: 12, step: 1 },
{ key: "rotate", label: "Rotacion", min: -3, max: 3, step: 0.05 },
{ key: "feedback", label: "Feedback", min: 0, max: 0.95, step: 0.01 },
];
// ==========================================================================
// Editor de codigo (CodeMirror)
// ==========================================================================
let editor = null;
if (typeof CodeMirror !== "undefined") {
editor = CodeMirror.fromTextArea($("#code"), {
lineNumbers: true, theme: "material-darker",
mode: "javascript", lineWrapping: true,
});
}
// ==========================================================================
// Librerias de codigo y de ayuda
// ==========================================================================
let hydraLib = [];
let shaderLib = [];
async function loadData() {
try {
const sketches = await fetch("/data/hydra-sketches.json").then((r) => r.json());
const snippets = await fetch("/data/hydra-snippets.json").then((r) => r.json());
const shaders = await fetch("/data/shaders.json").then((r) => r.json());
hydraLib = [];
for (const [id, v] of Object.entries(sketches)) {
hydraLib.push({ id: "s:" + id, name: "* " + (v.name || id), code: v.code });
}
for (const [id, v] of Object.entries(snippets.snippets || {})) {
hydraLib.push({ id: "x:" + id, name: v.name || id, code: v.code });
}
shaderLib = Object.entries(shaders).map(
([id, v]) => ({ id: id, name: v.name || id, code: v.code }));
} catch (err) {
console.error("[FOSFENO] No se pudieron cargar las librerias:", err);
}
try {
const ayuda = await fetch("/data/ayuda.json").then((r) => r.json());
helpData = ayuda.ayuda || {};
} catch (err) {
console.error("[FOSFENO] No se pudo cargar la ayuda:", err);
}
// Si el estado llego antes que las librerias, repinta para que aparezcan
if (state) { editorEngine = ""; render(); }
}
function fillLibrarySelect(lib) {
const sel = $("#lib-select");
sel.innerHTML = '<option value="">-- Cargar de la libreria --</option>';
lib.forEach((it, i) => {
const opt = document.createElement("option");
opt.value = String(i);
opt.textContent = it.name;
sel.appendChild(opt);
});
}
// ==========================================================================
// Ventana de informacion
// ==========================================================================
function openHelp(key) {
const h = helpData[key];
if (!h) return;
$("#modal-title").textContent = h.title || "Informacion";
const body = $("#modal-body");
body.innerHTML = "";
(h.body || []).forEach((par) => {
const p = document.createElement("p");
p.textContent = par;
body.appendChild(p);
});
$("#modal").hidden = false;
}
function closeHelp() { $("#modal").hidden = true; }
// ==========================================================================
// Avisos (banda superior)
// ==========================================================================
let notifTimer = null;
function showNotif(entry) {
if (!entry || !entry.message) return;
const n = $("#notif");
n.className = "notif " + (entry.level || "info");
$("#notif-msg").textContent = entry.message;
n.hidden = false;
clearTimeout(notifTimer);
if (entry.level === "info") {
notifTimer = setTimeout(() => { n.hidden = true; }, 6000);
}
if (entry.t) lastNotifT = entry.t;
}
// ==========================================================================
// Sliders del mezclador
// ==========================================================================
function fmt(v, step) {
return step >= 1 ? String(Math.round(v)) : Number(v).toFixed(2);
}
function buildMixerSliders() {
const cont = $("#mixer-sliders");
MIXER_SLIDERS.forEach((cfg) => {
const wrap = document.createElement("div");
wrap.className = "slider";
wrap.innerHTML =
`<div class="head"><span>${cfg.label}</span>` +
`<b id="mv-${cfg.key}">-</b></div>`;
const input = document.createElement("input");
input.type = "range";
input.min = cfg.min; input.max = cfg.max; input.step = cfg.step;
input.id = "ms-" + cfg.key;
input.addEventListener("input", () => {
$("#mv-" + cfg.key).textContent = fmt(input.value, cfg.step);
});
input.addEventListener("change", () => {
const patch = {};
patch[cfg.key] = parseFloat(input.value);
socket.emit("update_settings", { engine: "mixer", patch: patch });
});
wrap.appendChild(input);
cont.appendChild(wrap);
});
}
// ==========================================================================
// Render
// ==========================================================================
function render() {
if (!state) return;
$("#conn").className = "dot on";
const power = $("#power");
power.textContent = state.power ? "ON" : "OFF";
power.classList.toggle("off", !state.power);
$$(".engine").forEach((b) =>
b.classList.toggle("active", b.dataset.engine === state.engine));
fillSelectOnce($("#audio-device"), state.meta.audioDevices,
(d) => d.id, (d) => d.name);
if (state.audio.device) $("#audio-device").value = state.audio.device;
const source = state.audio.source || "mic";
$("#audio-src-mic").classList.toggle("active", source === "mic");
$("#audio-src-monitor").classList.toggle("active", source === "monitor");
$("#bpm").textContent = state.audio.bpm > 0 ? state.audio.bpm : "--";
$("#sens").value = state.sensitivity;
$("#sens-val").textContent = Number(state.sensitivity).toFixed(1);
$("#ctl-butterchurn").hidden = state.engine !== "butterchurn";
$("#ctl-editor").hidden = !(state.engine === "hydra" || state.engine === "shaders");
$("#ctl-mixer").hidden = state.engine !== "mixer";
$("#ctl-projectm").hidden = state.engine !== "projectm";
renderButterchurn();
renderEditor();
renderMixer();
renderProjectM();
renderMapping();
$("#now").textContent = nowText() || "-";
const net = state.network || {};
const port = (net.port && net.port !== 80) ? ":" + net.port : "";
$("#net-foot").textContent = "Panel: http://" +
(net.hostname || "fosfeno") + ".local" + port + "/" +
(net.ip ? " (" + net.ip + ")" : "");
// Aviso pendiente recibido antes de abrir el panel
const notes = state.notifications || [];
if (notes.length) {
const last = notes[notes.length - 1];
if (last.t !== lastNotifT) showNotif(last);
}
}
/* Texto unico de "que se esta viendo". Lo usan la tarjeta En pantalla y la
tarjeta de projectM, para que ambas cuenten exactamente lo mismo. Con
projectM se ensena con la misma taxonomia de las listas (Categoria /
Visual) y despues la variante concreta que rota dentro de ese look. */
function nowText() {
if (state.engine === "projectm") {
const pm = state.projectm || {};
if (!pm.nowPlaying) return "";
const sitio = (pm.nowCategory && pm.nowVisual)
? pm.nowCategory + " / " + pm.nowVisual + " · " : "";
return sitio + pm.nowPlaying + (pm.locked ? " [congelado]" : "");
}
return state.status.label || "";
}
function fillSelectOnce(sel, items, valFn, txtFn) {
items = items || [];
if (sel.dataset.count == items.length) return;
sel.dataset.count = items.length;
let keep = "";
if (sel.id === "mix-video") {
keep = '<option value="">-- sin video --</option>';
} else if (sel.id === "mix-camera" && items.length === 0) {
keep = '<option value="0">Camara por defecto</option>';
}
sel.innerHTML = keep;
items.forEach((it) => {
const opt = document.createElement("option");
opt.value = valFn(it);
opt.textContent = txtFn(it);
sel.appendChild(opt);
});
}
function renderButterchurn() {
if (state.engine !== "butterchurn") return;
const b = state.butterchurn;
fillSelectOnce($("#bc-preset"), state.meta.butterchurnPresets,
(n) => n, (n) => n);
if (b.preset) $("#bc-preset").value = b.preset;
$("#bc-shuffle").checked = b.shuffle;
$("#bc-mode-seconds").classList.toggle("active", b.intervalMode === "seconds");
$("#bc-mode-beats").classList.toggle("active", b.intervalMode === "beats");
$("#bc-interval").value = b.interval;
$("#bc-int-val").textContent = b.interval;
$("#bc-int-unit").textContent = b.intervalMode === "beats" ? "comp." : "s";
$("#bc-blend").value = b.blendTime;
$("#bc-blend-val").textContent = Number(b.blendTime).toFixed(1);
}
function renderEditor() {
if (state.engine !== "hydra" && state.engine !== "shaders") return;
$("#editor-info").dataset.help = state.engine;
if (state.engine !== editorEngine) {
editorEngine = state.engine;
const isHydra = state.engine === "hydra";
$("#editor-title").textContent = isHydra ? "Editor Hydra" : "Editor Shaders";
$("#editor-hint").textContent = isHydra
? "Variables: time, a.fft[0..4], bpm. Escribe o pega codigo Hydra."
: "Uniforms: u_time, u_bass, u_mid, u_treble, u_bpm, u_beat, u_fft.";
fillLibrarySelect(isHydra ? hydraLib : shaderLib);
if (editor) {
editor.setOption("mode", isHydra ? "javascript" : "text/x-csrc");
editor.setValue(state[state.engine].code || "");
setTimeout(() => editor.refresh(), 30);
}
}
}
function renderMixer() {
if (state.engine !== "mixer") return;
const m = state.mixer;
$$("#mixer-source .segbtn").forEach((b) =>
b.classList.toggle("active", b.dataset.src === m.source));
$("#mix-cam").checked = m.camOn;
fillSelectOnce($("#mix-camera"), state.meta.cameraDevices,
(d) => d.id, (d) => d.name);
$("#mix-camera").value = m.cameraId;
fillSelectOnce($("#mix-video"), (state.meta.videos || []).map((v) => ({ v })),
(o) => o.v, (o) => o.v);
$("#mix-video").value = m.video || "";
$("#mix-fondo").value = m.fondo || "cam";
$("#mix-blend").value = m.blendMode;
$("#mix-invert").checked = m.invert;
$("#mix-beat").checked = m.beatPulse;
MIXER_SLIDERS.forEach((cfg) => {
const input = $("#ms-" + cfg.key);
if (input && document.activeElement !== input) {
input.value = m[cfg.key];
$("#mv-" + cfg.key).textContent = fmt(m[cfg.key], cfg.step);
}
});
}
function renderProjectM() {
if (state.engine !== "projectm") return;
const pm = state.projectm || {};
const cats = state.meta.projectmPresets || {};
const catSel = $("#pm-category");
const catSig = Object.keys(cats).join("|");
if (catSel.dataset.sig !== catSig) {
catSel.dataset.sig = catSig;
catSel.innerHTML = '<option value="">Todas las categorias</option>';
Object.keys(cats).forEach((c) => {
const opt = document.createElement("option");
opt.value = c;
opt.textContent = c + " (" + cats[c].length + ")";
catSel.appendChild(opt);
});
}
catSel.value = pm.category || "";
// La lista de presets depende de la categoria elegida
const preSel = $("#pm-preset");
const presets = cats[pm.category] || [];
const preSig = (pm.category || "") + "|" + presets.length;
if (preSel.dataset.sig !== preSig) {
preSel.dataset.sig = preSig;
preSel.innerHTML = presets.length
? '<option value="">-- rotando (elige uno para fijarlo) --</option>'
: '<option value="">-- elige antes una categoria --</option>';
presets.forEach((p) => {
const opt = document.createElement("option");
opt.value = p;
opt.textContent = p.replace(/\.milk$/i, "");
preSel.appendChild(opt);
});
}
preSel.value = pm.preset || "";
// Tercer nivel: variantes (.milk) del visual elegido, para clavar una
// a dedo. La lista se pide al servidor al cambiar de visual.
const varSel = $("#pm-variante");
const varSig = (pm.category || "") + "|" + (pm.preset || "");
if (varSel.dataset.sig !== varSig) {
varSel.dataset.sig = varSig;
varSel.innerHTML = pm.category && pm.preset
? '<option value="">-- variantes: rotando (elige una a dedo) --</option>'
: '<option value="">-- elige antes un visual --</option>';
if (pm.category && pm.preset) {
fetch("/pm/variantes?categoria=" + encodeURIComponent(pm.category)
+ "&visual=" + encodeURIComponent(pm.preset))
.then((r) => r.json())
.then((d) => {
if (varSel.dataset.sig !== varSig) return; // cambio a medias
(d.variantes || []).forEach((v) => {
const opt = document.createElement("option");
opt.value = v;
opt.textContent = v;
varSel.appendChild(opt);
});
varSel.value = (state.projectm && state.projectm.variante) || "";
})
.catch(() => {});
}
} else {
varSel.value = pm.variante || "";
}
// Favoritos: una fila por visual guardado, para lanzarlo de un toque
const favList = $("#pm-fav-list");
const favs = pm.favoritos || [];
const favSig = favs.map((f) => f.categoria + "/" + f.visual + "/"
+ f.variante).join("|");
if (favList.dataset.sig !== favSig) {
favList.dataset.sig = favSig;
favList.innerHTML = "";
favs.forEach((f) => {
const row = document.createElement("div");
row.className = "row";
const play = document.createElement("button");
play.className = "cmd favplay";
play.textContent = "▶ " + f.variante;
play.title = f.categoria + " / " + f.visual;
play.addEventListener("click", () => socket.emit("pm_favorito", {
action: "play", categoria: f.categoria,
visual: f.visual, variante: f.variante,
}));
const del = document.createElement("button");
del.className = "cmd favdel";
del.textContent = "✕";
del.title = "Quitar de favoritos";
del.addEventListener("click", () => socket.emit("pm_favorito", {
action: "del", categoria: f.categoria,
visual: f.visual, variante: f.variante,
}));
row.appendChild(play);
row.appendChild(del);
favList.appendChild(row);
});
}
$("#pm-shuffle").checked = pm.shuffle !== false;
// Selector de pantalla: Auto + monitores detectados por el servidor
const monSel = $("#pm-monitor");
const mons = state.meta.monitors || [];
const monSig = mons.map((m) => m.id + m.name).join("|");
if (monSel.dataset.sig !== monSig) {
monSel.dataset.sig = monSig;
monSel.innerHTML = '<option value="auto">Auto (la del escenario)</option>';
mons.forEach((m) => {
const opt = document.createElement("option");
opt.value = m.id;
opt.textContent = "Pantalla " + m.id + " - " + m.name;
monSel.appendChild(opt);
});
}
monSel.value = String(pm.monitor || "auto");
const dur = $("#pm-duration");
if (document.activeElement !== dur) dur.value = pm.duration || 60;
$("#pm-dur-val").textContent = pm.duration || 60;
const lockBtn = $("#pm-lock");
lockBtn.classList.toggle("accent", !!pm.locked);
lockBtn.textContent = pm.locked ? "Congelado (soltar)" : "Congelar visual";
$("#pm-now").textContent = "En pantalla: " + (nowText() || "...");
}
// ==========================================================================
// Projection mapping: previsualizacion arrastrable + lista
// ==========================================================================
let mapSurfaces = []; // copia local (para editar sin parpadeos)
let mapSel = null; // indice de superficie seleccionada
let mapDrag = null; // { idx, corner|null, sx, sy, orig }
let mapEmitTimer = null;
const MAP_H = 15; // radio del tirador (px)
const cloneSurfaces = (arr) =>
(arr || []).map((s) => ({ id: s.id, corners: s.corners.map((p) => [p[0], p[1]]) }));
// interpolacion bilineal dentro del cuadrilatero (pts = TL,TR,BR,BL)
function bilerp(pts, u, v) {
const tx = pts[0][0] + (pts[1][0] - pts[0][0]) * u;
const ty = pts[0][1] + (pts[1][1] - pts[0][1]) * u;
const bx = pts[3][0] + (pts[2][0] - pts[3][0]) * u;
const by = pts[3][1] + (pts[2][1] - pts[3][1]) * u;
return [tx + (bx - tx) * v, ty + (by - ty) * v];
}
function drawMapPreview() {
const cv = $("#map-preview");
if (!cv) return;
const dpr = Math.min(2, window.devicePixelRatio || 1);
const w = cv.clientWidth, h = cv.clientHeight;
if (!w || !h) return;
const W = Math.round(w * dpr), H = Math.round(h * dpr);
if (cv.width !== W || cv.height !== H) { cv.width = W; cv.height = H; }
const ctx = cv.getContext("2d");
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, w, h);
ctx.strokeStyle = "#333"; ctx.lineWidth = 1; ctx.strokeRect(0.5, 0.5, w - 1, h - 1);
ctx.font = "600 13px system-ui, sans-serif";
ctx.textAlign = "center"; ctx.textBaseline = "middle";
if (!mapSurfaces.length) {
ctx.fillStyle = "rgba(255,255,255,0.4)";
ctx.fillText("Pulsa '+ Anadir superficie'", w / 2, h / 2);
return;
}
mapSurfaces.forEach((s, i) => {
const pts = s.corners.map(([x, y]) => [x * w, y * h]);
const sel = i === mapSel;
// rejilla interna: hace visible la deformacion
ctx.strokeStyle = sel ? "rgba(0,229,255,0.4)" : "rgba(180,255,0,0.22)";
ctx.lineWidth = 1;
const N = 4;
for (let g = 0; g <= N; g++) {
const t = g / N;
ctx.beginPath();
for (let k = 0; k <= N; k++) { const p = bilerp(pts, k / N, t); k ? ctx.lineTo(p[0], p[1]) : ctx.moveTo(p[0], p[1]); }
ctx.stroke();
ctx.beginPath();
for (let k = 0; k <= N; k++) { const p = bilerp(pts, t, k / N); k ? ctx.lineTo(p[0], p[1]) : ctx.moveTo(p[0], p[1]); }
ctx.stroke();
}
// contorno + relleno
ctx.beginPath(); ctx.moveTo(pts[0][0], pts[0][1]);
for (let k = 1; k < 4; k++) ctx.lineTo(pts[k][0], pts[k][1]);
ctx.closePath();
ctx.fillStyle = sel ? "rgba(0,229,255,0.08)" : "rgba(180,255,0,0.05)";
ctx.fill();
ctx.lineWidth = sel ? 2.5 : 1.5;
ctx.strokeStyle = sel ? "#00e5ff" : "#b4ff00";
ctx.stroke();
// numero
const cx = (pts[0][0] + pts[1][0] + pts[2][0] + pts[3][0]) / 4;
const cy = (pts[0][1] + pts[1][1] + pts[2][1] + pts[3][1]) / 4;
ctx.fillStyle = sel ? "#00e5ff" : "rgba(180,255,0,0.9)";
ctx.fillText(String(i + 1), cx, cy);
// tiradores
pts.forEach(([px, py]) => {
ctx.beginPath(); ctx.arc(px, py, MAP_H * 0.7, 0, Math.PI * 2);
ctx.fillStyle = sel ? "#00e5ff" : "#fff"; ctx.fill();
ctx.lineWidth = 2; ctx.strokeStyle = "#000"; ctx.stroke();
});
});
}
function mapLocalPt(ev) {
const r = $("#map-preview").getBoundingClientRect();
return { x: (ev.clientX - r.left) / r.width, y: (ev.clientY - r.top) / r.height, w: r.width, h: r.height };
}
function mapPointInQuad(x, y, c) {
let inside = false;
for (let i = 0, j = 3; i < 4; j = i++) {
const xi = c[i][0], yi = c[i][1], xj = c[j][0], yj = c[j][1];
if (((yi > y) !== (yj > y)) && (x < ((xj - xi) * (y - yi)) / ((yj - yi) || 1e-9) + xi)) inside = !inside;
}
return inside;
}
function onMapDown(ev) {
ev.preventDefault();
const p = mapLocalPt(ev);
const rx = (MAP_H + 8) / p.w, ry = (MAP_H + 8) / p.h;
for (let i = mapSurfaces.length - 1; i >= 0; i--) {
const c = mapSurfaces[i].corners;
for (let k = 0; k < 4; k++) {
const dx = (c[k][0] - p.x) / rx, dy = (c[k][1] - p.y) / ry;
if (dx * dx + dy * dy <= 1) {
mapSel = i; mapDrag = { idx: i, corner: k, sx: p.x, sy: p.y, orig: c.map((q) => q.slice()) };
drawMapPreview(); return;
}
}
}
for (let i = mapSurfaces.length - 1; i >= 0; i--) {
if (mapPointInQuad(p.x, p.y, mapSurfaces[i].corners)) {
mapSel = i; mapDrag = { idx: i, corner: null, sx: p.x, sy: p.y, orig: mapSurfaces[i].corners.map((q) => q.slice()) };
drawMapPreview(); return;
}
}
mapSel = null; mapDrag = null; drawMapPreview();
}
function onMapMove(ev) {
if (!mapDrag) return;
ev.preventDefault();
const p = mapLocalPt(ev);
const dx = p.x - mapDrag.sx, dy = p.y - mapDrag.sy;
const s = mapSurfaces[mapDrag.idx]; if (!s) return;
const cl = (v) => (v < 0 ? 0 : v > 1 ? 1 : v);
if (mapDrag.corner == null) {
for (let k = 0; k < 4; k++) {
s.corners[k][0] = cl(mapDrag.orig[k][0] + dx);
s.corners[k][1] = cl(mapDrag.orig[k][1] + dy);
}
} else {
s.corners[mapDrag.corner][0] = cl(mapDrag.orig[mapDrag.corner][0] + dx);
s.corners[mapDrag.corner][1] = cl(mapDrag.orig[mapDrag.corner][1] + dy);
}
drawMapPreview(); scheduleMapEmit();
}
function onMapUp() { if (mapDrag) { emitMapNow(); mapDrag = null; } }
function scheduleMapEmit() { if (!mapEmitTimer) mapEmitTimer = setTimeout(() => { mapEmitTimer = null; emitMapNow(); }, 60); }
function emitMapNow() {
if (mapEmitTimer) { clearTimeout(mapEmitTimer); mapEmitTimer = null; }
socket.emit("set_mapping", { surfaces: mapSurfaces });
}
// refleja estado, dibuja la previsualizacion y la lista de superficies
function renderMapping() {
const m = state.mapping || { enabled: false, edit: false, surfaces: [] };
const en = $("#map-enabled"), ed = $("#map-edit");
if (document.activeElement !== en) en.checked = !!m.enabled;
if (document.activeElement !== ed) ed.checked = !!m.edit;
ed.disabled = !m.enabled;
const surfaces = m.surfaces || [];
// previsualizacion (no piso la geometria mientras arrastro aqui)
if (!mapDrag) mapSurfaces = cloneSurfaces(surfaces);
if (mapSel != null && mapSel >= mapSurfaces.length) mapSel = null;
drawMapPreview();
// lista con boton de borrar (se reconstruye solo si cambia)
const list = $("#map-list");
const sig = surfaces.map((s) => s.id).join("|") + "#" + surfaces.length;
if (list.dataset.sig === sig) return;
list.dataset.sig = sig;
list.innerHTML = "";
if (!surfaces.length) return;
surfaces.forEach((s, i) => {
const row = document.createElement("div");
row.className = "row";
const lbl = document.createElement("span");
lbl.className = "label";
lbl.textContent = "Superficie " + (i + 1);
const del = document.createElement("button");
del.className = "cmd favdel";
del.textContent = "✕";
del.title = "Borrar superficie";
del.addEventListener("click", () => {
const rest = ((state.mapping && state.mapping.surfaces) || [])
.filter((x) => x.id !== s.id);
socket.emit("set_mapping", { surfaces: rest });
});
row.appendChild(lbl);
row.appendChild(del);
list.appendChild(row);
});
}
// ==========================================================================
// Eventos de la interfaz
// ==========================================================================
$("#power").addEventListener("click", () =>
socket.emit("set_power", { on: !state.power }));
// --- Mapping ---
$("#map-enabled").addEventListener("change", (e) =>
socket.emit("set_mapping", { enabled: e.target.checked }));
$("#map-edit").addEventListener("change", (e) =>
socket.emit("set_mapping", { edit: e.target.checked }));
$("#map-add").addEventListener("click", () => {
const cur = (state.mapping && state.mapping.surfaces) || [];
const s = 0.2, cx = 0.5, cy = 0.5;
const nueva = {
id: "s" + Date.now() + "_" + Math.floor(Math.random() * 1e4),
corners: [[cx - s, cy - s], [cx + s, cy - s], [cx + s, cy + s], [cx - s, cy + s]],
};
socket.emit("set_mapping",
{ enabled: true, edit: true, surfaces: cur.concat([nueva]) });
});
$("#map-reset").addEventListener("click", () => {
if (confirm("Borrar todas las superficies de mapping?"))
socket.emit("set_mapping", { surfaces: [] });
});
// Previsualizacion arrastrable (raton + tactil via pointer events)
(function () {
const mp = $("#map-preview");
if (!mp) return;
mp.addEventListener("pointerdown", (e) => { mp.setPointerCapture(e.pointerId); onMapDown(e); });
mp.addEventListener("pointermove", onMapMove);
mp.addEventListener("pointerup", onMapUp);
mp.addEventListener("pointercancel", onMapUp);
window.addEventListener("resize", () => { if (state) drawMapPreview(); });
})();
$$(".engine").forEach((b) =>
b.addEventListener("click", () =>
socket.emit("set_engine", { engine: b.dataset.engine })));
$$(".info").forEach((b) =>
b.addEventListener("click", () => openHelp(b.dataset.help)));
$("#modal-close").addEventListener("click", closeHelp);
$("#modal").addEventListener("click", (e) => {
if (e.target.id === "modal") closeHelp();
});
$("#notif-close").addEventListener("click", () => { $("#notif").hidden = true; });
// Eleccion de fuente: micro de la sala o audio del propio equipo (monitor).
// El cambio de 'source' ya hace que el escenario reconecte la captura; el
// boton "Aplicar entrada" queda como reintento manual.
$$("#audio-source .segbtn").forEach((b) =>
b.addEventListener("click", () =>
socket.emit("update_settings",
{ engine: "audio", patch: { source: b.dataset.src } })));
$("#audio-device").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "audio", patch: { device: e.target.value } }));
// Boton "Aplicar microfono": fija la entrada elegida y obliga al escenario
// a re-conectar la captura de audio (util tras enchufar o cambiar el micro).
$("#audio-apply").addEventListener("click", () => {
socket.emit("update_settings",
{ engine: "audio", patch: { device: $("#audio-device").value } });
socket.emit("reacquire_audio");
});
$("#sens").addEventListener("input", (e) =>
$("#sens-val").textContent = Number(e.target.value).toFixed(1));
$("#sens").addEventListener("change", (e) =>
socket.emit("set_sensitivity", { value: parseFloat(e.target.value) }));
// --- Butterchurn ---
$("#bc-preset").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "butterchurn", patch: { preset: e.target.value } }));
$("#bc-shuffle").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "butterchurn", patch: { shuffle: e.target.checked } }));
$("#bc-mode-seconds").addEventListener("click", () =>
socket.emit("update_settings",
{ engine: "butterchurn", patch: { intervalMode: "seconds" } }));
$("#bc-mode-beats").addEventListener("click", () =>
socket.emit("update_settings",
{ engine: "butterchurn", patch: { intervalMode: "beats" } }));
$("#bc-interval").addEventListener("input", (e) =>
$("#bc-int-val").textContent = e.target.value);
$("#bc-interval").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "butterchurn", patch: { interval: parseInt(e.target.value, 10) } }));
$("#bc-blend").addEventListener("input", (e) =>
$("#bc-blend-val").textContent = Number(e.target.value).toFixed(1));
$("#bc-blend").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "butterchurn", patch: { blendTime: parseFloat(e.target.value) } }));
// --- Editor de codigo ---
$("#run-code").addEventListener("click", () => {
if (!editor || !editorEngine) return;
socket.emit("run_code",
{ engine: editorEngine, code: editor.getValue(), label: "codigo personalizado" });
});
$("#clear-code").addEventListener("click", () => editor && editor.setValue(""));
$("#lib-select").addEventListener("change", (e) => {
const lib = editorEngine === "hydra" ? hydraLib : shaderLib;
const item = lib[parseInt(e.target.value, 10)];
if (!item || !editor) return;
editor.setValue(item.code);
socket.emit("run_code",
{ engine: editorEngine, code: item.code, label: item.name });
});
// --- Mezclador ---
$$("#mixer-source .segbtn").forEach((b) =>
b.addEventListener("click", () =>
socket.emit("update_settings",
{ engine: "mixer", patch: { source: b.dataset.src } })));
$("#mix-cam").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "mixer", patch: { camOn: e.target.checked } }));
$("#mix-camera").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "mixer", patch: { cameraId: parseInt(e.target.value, 10) } }));
$("#dev-rescan").addEventListener("click", () =>
socket.emit("rescan_devices"));
$("#mix-video").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "mixer", patch: { video: e.target.value } }));
$("#mix-fondo").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "mixer", patch: { fondo: e.target.value } }));
$("#mix-blend").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "mixer", patch: { blendMode: e.target.value } }));
$("#mix-rescan").addEventListener("click", () => socket.emit("rescan_videos"));
$("#mix-invert").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "mixer", patch: { invert: e.target.checked } }));
$("#mix-beat").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "mixer", patch: { beatPulse: e.target.checked } }));
// --- projectM ---
$("#pm-category").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "projectm",
patch: { category: e.target.value, preset: "", variante: "" } }));
$("#pm-preset").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "projectm", patch: { preset: e.target.value, variante: "" } }));
$("#pm-variante").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "projectm", patch: { variante: e.target.value } }));
$("#pm-fav-add").addEventListener("click", () =>
socket.emit("pm_favorito", { action: "add" }));
$("#pm-shuffle").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "projectm", patch: { shuffle: e.target.checked } }));
$("#pm-duration").addEventListener("input", (e) =>
$("#pm-dur-val").textContent = e.target.value);
$("#pm-duration").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "projectm", patch: { duration: parseInt(e.target.value, 10) } }));
$("#pm-monitor").addEventListener("change", (e) =>
socket.emit("update_settings",
{ engine: "projectm", patch: { monitor: e.target.value } }));
$("#pm-lock").addEventListener("click", () =>
socket.emit("engine_command", { action: "lock" }));
$("#pm-fix").addEventListener("click", () =>
socket.emit("engine_command", { action: "fix_current" }));
// --- Subida a la galeria del mezclador ---
$("#mix-upload-btn").addEventListener("click", () => $("#mix-upload").click());
$("#mix-upload").addEventListener("change", () => {
const f = $("#mix-upload").files[0];
if (!f) return;
const status = $("#mix-upload-status");
const fd = new FormData();
fd.append("file", f);
const xhr = new XMLHttpRequest();
xhr.open("POST", "/upload");
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) {
status.textContent = "subiendo " + Math.round(e.loaded / e.total * 100) + "%";
}
};
xhr.onload = () => {
let r = {};
try { r = JSON.parse(xhr.responseText); } catch (e) { /* respuesta rara */ }
status.textContent = r.ok ? "subido ✓" : "";
if (!r.ok) {
showNotif({ level: "error",
message: r.error || "La subida fallo (" + xhr.status + ")." });
}
$("#mix-upload").value = "";
setTimeout(() => { status.textContent = ""; }, 5000);
};
xhr.onerror = () => {
status.textContent = "";
$("#mix-upload").value = "";
showNotif({ level: "error", message: "La subida fallo: no hay conexion "
+ "con el servidor de FOSFENO." });
};
status.textContent = "subiendo 0%";
xhr.send(fd);
});
// --- Comandos siguiente/anterior ---
$$(".cmd[data-action]").forEach((b) =>
b.addEventListener("click", () =>
socket.emit("engine_command", { action: b.dataset.action })));
// --- Sistema ---
$("#reboot").addEventListener("click", () => {
if (confirm("Reiniciar la Raspberry Pi?")) socket.emit("system", { action: "reboot" });
});
$("#shutdown").addEventListener("click", () => {
if (confirm("Apagar la Raspberry Pi?")) socket.emit("system", { action: "shutdown" });
});
// ==========================================================================
// WebSocket
// ==========================================================================
// Al conectar, el panel se presenta para que el proyector deje de mostrar
// la pantalla del codigo QR.
socket.on("connect", () => socket.emit("hello", { role: "panel" }));
socket.on("state", (next) => { state = next; render(); });
socket.on("status", (s) => {
if (!state) return;
state.status.label = s.label;
state.audio.bpm = s.bpm;
$("#now").textContent = nowText() || "-";
$("#bpm").textContent = s.bpm > 0 ? s.bpm : "--";
});
socket.on("notify", (entry) => showNotif(entry));
socket.on("disconnect", () => { $("#conn").className = "dot off"; });
// ==========================================================================
// Arranque
// ==========================================================================
buildMixerSliders();
loadData();