mirror of
https://github.com/juanjiant-bit/JIANT.git
synced 2026-12-05 12:24:42 +01:00
Studio Project SOUND: JIANT FM's own formula on a MATH track (V10.8.75, FORMULA 100): typed or generated, checked as typed (BYTE/FLOAT, size of 64 B, where an error is), drawn, heard here, sent and read back, ALGO USER and WAVE set; the editor's own compiler (FVM) taken from the published editor page; the text kept by its bytecode as the editor keeps it (#287)
Claude-Session: https://claude.ai/code/session_01UVqsRnhKjiABTzc6Ety3dd Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
2fffd14209
commit
278cb334f3
3 files changed
+92
-3
No files matched your search
@@ -267,7 +267,7 @@ jobs:
|
||||
# (studio) JIANT Studio: install, edit, the screen, the emulator and recording for JIANT FM and JIANT BYTE in one
|
||||
# page (web/studio; it shows JIANT BYTE's tools from /JIANT-BYTE/, the same origin)
|
||||
mkdir -p build/pages/studio
|
||||
cp web/studio/index.html web/studio/studio.js web/studio/studio-lib.js web/studio/daw.js web/studio/recorder-worklet.js web/studio/learn.js web/studio/wavetable.js web/studio/radio-vis.js web/studio/visgen.js web/studio/analysis.js web/studio/convert.js web/studio/learn-fm.json web/studio/learn-byte.json web/studio/live-fm.json web/studio/live-byte.json web/fm1backup.js build/pages/studio/
|
||||
cp web/studio/index.html web/studio/studio.js web/studio/studio-lib.js web/studio/daw.js web/studio/recorder-worklet.js web/studio/learn.js web/studio/wavetable.js web/studio/radio-vis.js web/studio/visgen.js web/studio/analysis.js web/studio/convert.js web/studio/fmformula.js web/studio/learn-fm.json web/studio/learn-byte.json web/studio/live-fm.json web/studio/live-byte.json web/fm1backup.js build/pages/studio/
|
||||
cp -r web/studio/smk37 build/pages/studio/smk37
|
||||
cp web/fm1pkg.js web/fm1ota.js build/pages/studio/smk37/
|
||||
cp -r LICENSE LICENSES LICENSING.md build/pages/studio/smk37/
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/* JIANT FM's MATH USER formula (V10.8.75, editor protocol 1.5) in Studio: the editor's own MATH code (between its
|
||||
* MATH-BEGIN / MATH-END markers: MathVM, FVM = JIANT BYTE's compiler ported, mathGenerate), taken from the published
|
||||
* editor page so there is one copy of it; a formula compiled to the device's bytecode, heard here, sent with FORMULA (100)
|
||||
* and read back. Its text is kept in this browser by its bytecode (the editor's own "jiantMathUser" store, same site)
|
||||
* const M = await mathLib(url) { FVM, MathVM, mathGenerate } or null
|
||||
* compile(M, text) { ok, code, fix, size, fn(t, a) -> 0..255 } or { ok: false, error, pos }
|
||||
* preview(M, text, secs) plays it (8 kHz, as a bytebeat is heard), returns a stop function
|
||||
*/
|
||||
let lib = null;
|
||||
export async function mathLib(url) {
|
||||
if (lib) return lib;
|
||||
const r = await fetch(url, { cache: "no-cache" }); if (!r.ok) return null;
|
||||
const h = await r.text(), a = h.indexOf("/*MATH-BEGIN*/"), b = h.indexOf("/*MATH-END*/");
|
||||
if (a < 0 || b < 0) return null;
|
||||
try { lib = new Function(h.slice(a, b) + "; return { FVM, MathVM, mathGenerate };")(); } catch (_) { return null; }
|
||||
return lib.FVM ? lib : null;
|
||||
}
|
||||
export function compile(M, src) {
|
||||
const f = M.FVM.compile(src);
|
||||
if (!f.ok) return { ok: false, error: f.error, pos: f.pos };
|
||||
const code = f.code;
|
||||
const fn = f.fix ? (t, a) => ((M.FVM.sample(code, M.FVM.run(code, t, (t << 11) >>> 0, a)) >> 8) + 128) & 255 : (t, a) => M.FVM.run(code, t, 0, a) & 255;
|
||||
return { ok: true, code, fix: !!f.fix, size: code.length, max: M.FVM.MAX, fn };
|
||||
}
|
||||
let ac = null;
|
||||
export function preview(c, secs = 4, a = 64) {
|
||||
ac = ac || new AudioContext();
|
||||
const sr = 8000, n = sr * secs, buf = ac.createBuffer(1, n, sr), d = buf.getChannelData(0);
|
||||
for (let t = 0; t < n; t++) { let v = 128; try { v = c.fn(t, a); } catch (_) {} d[t] = (v - 128) / 128 * 0.35; }
|
||||
const s = ac.createBufferSource(); s.buffer = buf; s.connect(ac.destination); ac.resume(); s.start();
|
||||
return () => { try { s.stop(); } catch (_) {} };
|
||||
}
|
||||
export function wave(c, w, a = 64) { // the first w samples, for a picture
|
||||
const out = []; for (let t = 0; t < w; t++) { try { out.push(c.fn(t * 8, a)); } catch (_) { out.push(128); } } return out;
|
||||
}
|
||||
const KEY = "jiantMathUser";
|
||||
export function keepText(code, src) { try { const m = JSON.parse(localStorage.getItem(KEY) || "{}"); m[code.join(",")] = src; const k = Object.keys(m); if (k.length > 200) delete m[k[0]]; localStorage.setItem(KEY, JSON.stringify(m)); } catch (_) {} }
|
||||
export function textOf(code) { try { return JSON.parse(localStorage.getItem(KEY) || "{}")[code.join(",")] ?? null; } catch (_) { return null; } }
|
||||
+53
-2
@@ -16,6 +16,7 @@ import { capture as anCapture, text as anText } from "./analysis.js";
|
||||
import { checker as cvChecker, classify as cvClassify, convert as cvConvert, putObject as cvPut, replaceInFile as cvReplace, projectName as cvName } from "./convert.js";
|
||||
import { Vis as VisEngine, Live as VisLive, forDrawing as visRecipe, VI_NAMES, VD_NAMES, VB_NAMES, VP_NAMES } from "./visgen.js";
|
||||
import { makeTable, toI16, pack as wtPack, unpack as wtUnpack, parseInfo as parseWtInfo, render as wtRender, wav as wtWav, WT, FRAMES, LEN, CHUNKS } from "./wavetable.js";
|
||||
import { mathLib, compile as fmCompile, preview as fmPreview, wave as fmWave, keepText as fmKeep, textOf as fmTextOf } from "./fmformula.js";
|
||||
import { captureBackup, restoreBackup, readBackup, songsNotRestored, BACKUP_IDS, bkU32, bkR32, bkCrc, bkPack, bkUnpack, bkManifestAll } from "./fm1backup.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
@@ -104,7 +105,7 @@ const TEXT = {
|
||||
peSoon_seq: "SEQ llega con el largo de nota, la probabilidad y el micro-timing en el firmware: un piano roll por pista.",
|
||||
peSoon_mod: "MOD · MIX llega en la próxima entrega: la matriz completa con montos ±200 %, niveles, paneo, envíos y efectos.",
|
||||
peSoon_gen: "GEN llega cuando el emulador pueda regenerar una pista o una sección: género, semilla, MOOD, ENERGY, y lo que cambiaste respecto del original.",
|
||||
peNoDev: "Conectá el FM-1 o prendé el emulador.", peAsk: "Leé las pistas del proyecto que está sonando.", peRead: "Leer el proyecto", peReading: "Leyendo…", peFail: "No se pudo completar", peTrackParams: "Pista (comunes)", peGenEmu: "GEN se maneja con el emulador: prendelo en la pestaña Emulador y elegilo arriba.", peGenOld: "Este emulador no tiene el generador para Studio todavía.", peGenNow: "LO QUE HIZO EL GENERADOR", peGenNew: "Nueva pieza", peGenTrack: "Regenerar solo la pista:", peGenSection: "Regenerar solo la sección:", peGenHelp: "Regenerar una pista o una sección deja el resto como está (la sección A rehace la pieza entera). Lo que generó queda guardado como original: al guardar el proyecto, el archivo lleva el original y tus cambios.", peGenHelpNoState: "Este emulador no devuelve el estado del generador: se puede regenerar, pero el archivo no puede llevar el original.", peGenBack: "Volver al original", peGenBackConfirm: "¿Volver a la pieza que generó el generador? Se pierden los cambios hechos con GEN.", peGenBackDone: "Volviste al original.", peGenChanged: "Cambiaste la pieza respecto del original.", peGenSame: "Es la pieza original.", peSeqPick: "Elegí una pista para leer sus pasos.", peSeqRefused: "El FM-1 no aceptó el cambio (¿está sonando la cadena de canción?).", peSeqHelp: "Clic en una celda: agrega o saca una nota (hasta 4 por paso). VEL, PROB y µTIME: clic a la altura que querés. µTIME (−32..+31 sesentaicuatroavos) es solo de la web: el FM-1 lo toca igual.", peSeqHelpOld: "Clic en una celda: agrega o saca una nota. VEL y PROB: clic a la altura que querés. El micro-timing, el largo y los componentes llegan con un firmware que los exponga.", peModMatrix: "MATRIZ MOD", peModMix: "MEZCLA (NIVEL DE CADA PISTA)", peModFx: "EFECTOS Y MASTER", peSongRead: "Leer la canción", peSongAsk: "Lee las secciones de las canciones del FM-1.", peSongOld: "El índice de canciones de este firmware es de otra versión: actualizá JIANT BYTE.", peSongN: "Proyecto", peSongEmpty: "Este proyecto no tiene filas de canción todavía.", peSongSec: "SECCIÓN", peSongCell: "Clic: mute · clic derecho: variación", peSongHelp: "Cada columna es una fila de la canción (su parte A–D y sus compases). Clic en una celda: mute de esa pista en esa fila; clic derecho: su variación (FILL, REV, OCT…). La letra en la celda es el patrón A–D de esa pista.", peSongApply: "Aplicar al FM-1", peSongUndo: "Deshacer", peSongConfirm: "Se escribe el índice de canciones del FM-1 (las filas, mutes y variaciones de los 6 proyectos). ¿Seguir?", peSongDone: "Canción aplicada.", peFormula: "FÓRMULA DE LA PISTA", peFormulaSend: "Mandar la fórmula", peFormulaOk: "Fórmula enviada.", peFormulaCut: "Enviada, pero cortada a 255 caracteres.", peOnlyChanged: "Ver solo las que cambiaron (las otras están en su valor de fábrica)",
|
||||
peNoDev: "Conectá el FM-1 o prendé el emulador.", peAsk: "Leé las pistas del proyecto que está sonando.", peRead: "Leer el proyecto", peReading: "Leyendo…", peFail: "No se pudo completar", peTrackParams: "Pista (comunes)", peGenEmu: "GEN se maneja con el emulador: prendelo en la pestaña Emulador y elegilo arriba.", peGenOld: "Este emulador no tiene el generador para Studio todavía.", peGenNow: "LO QUE HIZO EL GENERADOR", peGenNew: "Nueva pieza", peGenTrack: "Regenerar solo la pista:", peGenSection: "Regenerar solo la sección:", peGenHelp: "Regenerar una pista o una sección deja el resto como está (la sección A rehace la pieza entera). Lo que generó queda guardado como original: al guardar el proyecto, el archivo lleva el original y tus cambios.", peGenHelpNoState: "Este emulador no devuelve el estado del generador: se puede regenerar, pero el archivo no puede llevar el original.", peGenBack: "Volver al original", peGenBackConfirm: "¿Volver a la pieza que generó el generador? Se pierden los cambios hechos con GEN.", peGenBackDone: "Volviste al original.", peGenChanged: "Cambiaste la pieza respecto del original.", peGenSame: "Es la pieza original.", peSeqPick: "Elegí una pista para leer sus pasos.", peSeqRefused: "El FM-1 no aceptó el cambio (¿está sonando la cadena de canción?).", peSeqHelp: "Clic en una celda: agrega o saca una nota (hasta 4 por paso). VEL, PROB y µTIME: clic a la altura que querés. µTIME (−32..+31 sesentaicuatroavos) es solo de la web: el FM-1 lo toca igual.", peSeqHelpOld: "Clic en una celda: agrega o saca una nota. VEL y PROB: clic a la altura que querés. El micro-timing, el largo y los componentes llegan con un firmware que los exponga.", peModMatrix: "MATRIZ MOD", peModMix: "MEZCLA (NIVEL DE CADA PISTA)", peModFx: "EFECTOS Y MASTER", peSongRead: "Leer la canción", peSongAsk: "Lee las secciones de las canciones del FM-1.", peSongOld: "El índice de canciones de este firmware es de otra versión: actualizá JIANT BYTE.", peSongN: "Proyecto", peSongEmpty: "Este proyecto no tiene filas de canción todavía.", peSongSec: "SECCIÓN", peSongCell: "Clic: mute · clic derecho: variación", peSongHelp: "Cada columna es una fila de la canción (su parte A–D y sus compases). Clic en una celda: mute de esa pista en esa fila; clic derecho: su variación (FILL, REV, OCT…). La letra en la celda es el patrón A–D de esa pista.", peSongApply: "Aplicar al FM-1", peSongUndo: "Deshacer", peSongConfirm: "Se escribe el índice de canciones del FM-1 (las filas, mutes y variaciones de los 6 proyectos). ¿Seguir?", peSongDone: "Canción aplicada.", peFmTitle: "FÓRMULA PROPIA (MATH USER)", peFmGen: "Generar", peFmPlay: "▶ Escuchar", peFmStop: "■ Parar", peFmSend: "Mandar a la pista", peFmClear: "Borrar del equipo", peFmNoLib: "No se pudo cargar el compilador de fórmulas del editor de JIANT FM.", peFmOld: "Este firmware no recibe fórmulas propias: hace falta JIANT FM V10.8.75 o posterior.", peFmHelp: "Escribí una fórmula de t (un bytebeat como t*(t>>5|t>>8), o con sin(w) un floatbeat), o tocá Generar. Escuchala y mandala: la pista pasa a ALGO USER.", peFmUnknown: "La pista tiene una fórmula propia (%n bytes) que no se escribió en este navegador: escribí una nueva para reemplazarla.", peFmErr: "Error:", peFmRefused: "El equipo no aceptó la fórmula.", peFmSent: "Fórmula mandada a %s (ALGO USER). Guardá el proyecto para conservarla.", peFmCleared: "Fórmula borrada.", peFormula: "FÓRMULA DE LA PISTA", peFormulaSend: "Mandar la fórmula", peFormulaOk: "Fórmula enviada.", peFormulaCut: "Enviada, pero cortada a 255 caracteres.", peOnlyChanged: "Ver solo las que cambiaron (las otras están en su valor de fábrica)",
|
||||
peSaved: "Archivo guardado.", peLoaded: "Abierto: %s. Tocá «Enviar al FM-1» para cargarlo.", peBadFile: "Ese archivo no es un proyecto de Studio.", peNoFile: "Primero abrí un archivo de proyecto.",
|
||||
peSendConfirm: "Se va a reemplazar la música de %n por «%s». Antes queda un backup completo en este navegador. ¿Seguir?", peSending: "Enviando… ", peSent: "Listo: el proyecto está en el FM-1.", peBefore: "Antes de enviar un proyecto",
|
||||
tourV_peT: "Proyecto", tourV_pe: "El proyecto entero en grande: guardarlo, enviarlo y editar todo el sonido.", tourV_peH: "Hoy anda SONIDO; el resto llega con el firmware.",
|
||||
@@ -313,7 +314,7 @@ const TEXT = {
|
||||
peSoon_seq: "SEQ arrives with note length, probability and micro-timing in the firmware: a piano roll per track.",
|
||||
peSoon_mod: "MOD · MIX arrives in the next delivery: the full matrix with ±200 % amounts, levels, pan, sends and effects.",
|
||||
peSoon_gen: "GEN arrives when the emulator can regenerate one track or one section: genre, seed, MOOD, ENERGY, and what you changed from the original.",
|
||||
peNoDev: "Connect the FM-1 or switch the emulator on.", peAsk: "Read the tracks of the project playing.", peRead: "Read the project", peReading: "Reading…", peFail: "Could not complete", peTrackParams: "Track (common)", peGenEmu: "GEN works with the emulator: switch it on in the Emulator tab and pick it above.", peGenOld: "This emulator does not have the generator for Studio yet.", peGenNow: "WHAT THE GENERATOR MADE", peGenNew: "New piece", peGenTrack: "Regenerate only the track:", peGenSection: "Regenerate only the section:", peGenHelp: "Regenerating a track or a section leaves the rest as it is (section A remakes the whole piece). What it made is kept as the original: when you save the project, the file carries the original and your changes.", peGenHelpNoState: "This emulator does not return the generator's state: you can regenerate, but the file cannot carry the original.", peGenBack: "Back to the original", peGenBackConfirm: "Go back to the piece the generator made? Changes made with GEN are lost.", peGenBackDone: "Back to the original.", peGenChanged: "You changed the piece from the original.", peGenSame: "This is the original piece.", peSeqPick: "Pick a track to read its steps.", peSeqRefused: "The FM-1 did not take the change (is the song chain playing?).", peSeqHelp: "Click a cell: add or remove a note (up to 4 a step). VEL, PROB and µTIME: click at the height you want. µTIME (−32..+31 64ths) is web-only: the FM-1 plays it all the same.", peSeqHelpOld: "Click a cell: add or remove a note. VEL and PROB: click at the height you want. Micro-timing, length and components come with a firmware that exposes them.", peModMatrix: "MOD MATRIX", peModMix: "MIX (EACH TRACK'S LEVEL)", peModFx: "EFFECTS AND MASTER", peSongRead: "Read the song", peSongAsk: "Reads the sections of the FM-1's songs.", peSongOld: "This firmware's song index is another version: update JIANT BYTE.", peSongN: "Project", peSongEmpty: "This project has no song rows yet.", peSongSec: "SECTION", peSongCell: "Click: mute · right click: variation", peSongHelp: "Each column is a song row (its part A–D and its bars). Click a cell: mute that track in that row; right click: its variation (FILL, REV, OCT…). The letter in the cell is that track's pattern A–D.", peSongApply: "Apply to the FM-1", peSongUndo: "Undo", peSongConfirm: "The FM-1's song index is written (the rows, mutes and variations of all 6 projects). Go on?", peSongDone: "Song applied.", peFormula: "THE TRACK'S FORMULA", peFormulaSend: "Send the formula", peFormulaOk: "Formula sent.", peFormulaCut: "Sent, but cut at 255 characters.", peOnlyChanged: "Show only the changed ones (the rest are at their defaults)",
|
||||
peNoDev: "Connect the FM-1 or switch the emulator on.", peAsk: "Read the tracks of the project playing.", peRead: "Read the project", peReading: "Reading…", peFail: "Could not complete", peTrackParams: "Track (common)", peGenEmu: "GEN works with the emulator: switch it on in the Emulator tab and pick it above.", peGenOld: "This emulator does not have the generator for Studio yet.", peGenNow: "WHAT THE GENERATOR MADE", peGenNew: "New piece", peGenTrack: "Regenerate only the track:", peGenSection: "Regenerate only the section:", peGenHelp: "Regenerating a track or a section leaves the rest as it is (section A remakes the whole piece). What it made is kept as the original: when you save the project, the file carries the original and your changes.", peGenHelpNoState: "This emulator does not return the generator's state: you can regenerate, but the file cannot carry the original.", peGenBack: "Back to the original", peGenBackConfirm: "Go back to the piece the generator made? Changes made with GEN are lost.", peGenBackDone: "Back to the original.", peGenChanged: "You changed the piece from the original.", peGenSame: "This is the original piece.", peSeqPick: "Pick a track to read its steps.", peSeqRefused: "The FM-1 did not take the change (is the song chain playing?).", peSeqHelp: "Click a cell: add or remove a note (up to 4 a step). VEL, PROB and µTIME: click at the height you want. µTIME (−32..+31 64ths) is web-only: the FM-1 plays it all the same.", peSeqHelpOld: "Click a cell: add or remove a note. VEL and PROB: click at the height you want. Micro-timing, length and components come with a firmware that exposes them.", peModMatrix: "MOD MATRIX", peModMix: "MIX (EACH TRACK'S LEVEL)", peModFx: "EFFECTS AND MASTER", peSongRead: "Read the song", peSongAsk: "Reads the sections of the FM-1's songs.", peSongOld: "This firmware's song index is another version: update JIANT BYTE.", peSongN: "Project", peSongEmpty: "This project has no song rows yet.", peSongSec: "SECTION", peSongCell: "Click: mute · right click: variation", peSongHelp: "Each column is a song row (its part A–D and its bars). Click a cell: mute that track in that row; right click: its variation (FILL, REV, OCT…). The letter in the cell is that track's pattern A–D.", peSongApply: "Apply to the FM-1", peSongUndo: "Undo", peSongConfirm: "The FM-1's song index is written (the rows, mutes and variations of all 6 projects). Go on?", peSongDone: "Song applied.", peFmTitle: "YOUR OWN FORMULA (MATH USER)", peFmGen: "Generate", peFmPlay: "▶ Listen", peFmStop: "■ Stop", peFmSend: "Send to the track", peFmClear: "Clear from the device", peFmNoLib: "Could not load the JIANT FM editor's formula compiler.", peFmOld: "This firmware takes no formulas of one's own: it needs JIANT FM V10.8.75 or later.", peFmHelp: "Type a formula of t (a bytebeat such as t*(t>>5|t>>8), or with sin(w) a floatbeat), or press Generate. Listen to it and send it: the track becomes ALGO USER.", peFmUnknown: "The track holds a formula of its own (%n bytes) not written in this browser: type a new one to replace it.", peFmErr: "Error:", peFmRefused: "The device did not take the formula.", peFmSent: "Formula sent to %s (ALGO USER). Save the project to keep it.", peFmCleared: "Formula cleared.", peFormula: "THE TRACK'S FORMULA", peFormulaSend: "Send the formula", peFormulaOk: "Formula sent.", peFormulaCut: "Sent, but cut at 255 characters.", peOnlyChanged: "Show only the changed ones (the rest are at their defaults)",
|
||||
peSaved: "File saved.", peLoaded: "Opened: %s. Press “Send to the FM-1” to load it.", peBadFile: "That file is not a Studio project.", peNoFile: "Open a project file first.",
|
||||
peSendConfirm: "The music on %n will be replaced by “%s”. A full backup is kept in this browser first. Go on?", peSending: "Sending… ", peSent: "Done: the project is on the FM-1.", peBefore: "Before sending a project",
|
||||
tourV_peT: "Project", tourV_pe: "The whole project, big: keep it, send it and edit all of its sound.", tourV_peH: "SOUND works today; the rest comes with the firmware.",
|
||||
@@ -2156,6 +2157,7 @@ function peSound(body, L) {
|
||||
const row = el("div", "emuctl"); row.append(send, msg);
|
||||
box.append(el("p", "pegrp", tp("peFormula")), ta, row); body.append(box);
|
||||
}
|
||||
if (state.fw === "fm" && /MATH/i.test(pe.tracks[pe.trk].engine || "")) peFmFormula(body, L, P, el);
|
||||
const C = pe.desc.common, only = el("label", "chk"), cb = el("input");
|
||||
cb.type = "checkbox"; cb.checked = !!pe.onlyChanged; cb.onchange = () => { pe.onlyChanged = cb.checked; renderPe(); };
|
||||
only.append(cb, document.createTextNode(" " + tp("peOnlyChanged"))); body.append(only);
|
||||
@@ -2166,6 +2168,55 @@ function peSound(body, L) {
|
||||
sg("EDIT · NOISE · CRUSH · LIFE", sk.filter((id) => state.fw === "byte" && id >= 0x6d));
|
||||
group(tp("peTrackParams"), Object.keys(C).map(Number).filter((id) => !pe.onlyChanged || (C[id] && P.vals[id] !== C[id].def)), C);
|
||||
}
|
||||
/* ---- JIANT FM's MATH USER (V10.8.75, FORMULA 100): the track's own formula, typed or generated, heard here, sent and
|
||||
read back; then ALGO USER (-4) and WAVE 5 (INT, a bytebeat) or 6 (FIX, a floatbeat) on the track. Older firmware
|
||||
does not answer FORMULA: the box says so */
|
||||
async function peFmFormula(body, L, P, el) {
|
||||
const box = el("div"), ta = el("textarea"), msg = el("p", "dim"), cv = el("canvas"), row = el("div", "emuctl");
|
||||
const gen = el("button", "btn ghost", tp("peFmGen")), play = el("button", "btn ghost", tp("peFmPlay")), send = el("button", "btn", tp("peFmSend")), clr = el("button", "btn ghost", tp("peFmClear"));
|
||||
[gen, play, send, clr].forEach((b) => { b.type = "button"; });
|
||||
ta.rows = 3; ta.spellcheck = false; ta.maxLength = 400; ta.setAttribute("autocomplete", "off"); ta.setAttribute("autocorrect", "off"); ta.setAttribute("autocapitalize", "off");
|
||||
ta.style.cssText = "width:100%;font:15px/1.4 var(--mono);background:var(--field);color:var(--fg);border:var(--border) solid var(--line);padding:8px;box-sizing:border-box";
|
||||
cv.width = 600; cv.height = 90; cv.style.cssText = "width:100%;height:70px;background:var(--panel);border:var(--border) solid var(--line);margin-top:8px";
|
||||
row.append(gen, play, send, clr);
|
||||
box.append(el("p", "pegrp", tp("peFmTitle")), ta, cv, msg, row); body.append(box);
|
||||
const M = await mathLib(toolUrl("fm", "editor")).catch(() => null);
|
||||
if (!M) { msg.textContent = tp("peFmNoLib"); [gen, play, send, clr].forEach((b) => { b.disabled = true; }); return; }
|
||||
const k = pe.trk;
|
||||
if (P.fmf === undefined) { // what the track holds: FORMULA query (none on older firmware)
|
||||
try { const a = await L.link.request(100, [k, 0], 900, (r) => r[0] === k); const n = a[2] | 0, code = M.FVM.unpack7(Array.from(a.slice(3))).slice(0, n); P.fmf = n ? (fmTextOf(code) ?? "") : ""; P.fmfOld = false; P.fmfDev = n; }
|
||||
catch (_) { P.fmf = ""; P.fmfOld = true; }
|
||||
}
|
||||
if (P.fmfOld) { msg.textContent = tp("peFmOld"); [send, clr].forEach((b) => { b.disabled = true; }); }
|
||||
ta.value = P.fmf || "";
|
||||
let c = null, stop = null;
|
||||
const check = () => {
|
||||
const src = ta.value.trim(); P.fmf = ta.value;
|
||||
const g = cv.getContext("2d"); g.clearRect(0, 0, cv.width, cv.height);
|
||||
if (!src) { c = null; msg.textContent = P.fmfDev && !P.fmf ? tp("peFmUnknown").replace("%n", P.fmfDev) : P.fmfOld ? tp("peFmOld") : tp("peFmHelp"); send.disabled = true; return; }
|
||||
c = fmCompile(M, src);
|
||||
if (!c.ok) { msg.textContent = `${tp("peFmErr")} ${c.error} (${c.pos + 1}): ${src.slice(Math.max(0, c.pos - 10), c.pos)}▸${src.slice(c.pos, c.pos + 10)}`; send.disabled = true; return; }
|
||||
msg.textContent = `${c.fix ? "FLOAT" : "BYTE"} · ${c.size}/${c.max} B` + (P.fmfOld ? " · " + tp("peFmOld") : ""); send.disabled = P.fmfOld;
|
||||
const w = fmWave(c, cv.width); g.strokeStyle = getComputedStyle(document.documentElement).getPropertyValue("--accent") || "#a77bff"; g.lineWidth = 2; g.beginPath();
|
||||
w.forEach((v, x) => { const y = cv.height - v / 255 * cv.height; x ? g.lineTo(x, y) : g.moveTo(x, y); }); g.stroke();
|
||||
};
|
||||
ta.addEventListener("input", check); check();
|
||||
gen.onclick = () => { ta.value = M.mathGenerate((Math.random() * 1e9) >>> 0); check(); };
|
||||
play.onclick = () => { if (stop) { stop(); stop = null; play.textContent = tp("peFmPlay"); return; } if (!c || !c.ok) return; stop = fmPreview(c, 4); play.textContent = tp("peFmStop"); setTimeout(() => { if (stop) { stop = null; play.textContent = tp("peFmPlay"); } }, 4000); };
|
||||
send.onclick = async () => {
|
||||
if (!c || !c.ok) return;
|
||||
try {
|
||||
const r = await L.link.request(100, [k, 1, ...M.FVM.pack7(c.code)], 1500, (x) => x[0] === k);
|
||||
const back = M.FVM.unpack7(Array.from(r.slice(3))).slice(0, r[2] | 0);
|
||||
if (r[1] || back.join() !== c.code.join()) { peSay(tp("peFmRefused")); return; }
|
||||
fmKeep(c.code, ta.value.trim());
|
||||
const set = (id, v) => L.link.request(31, [k, id, (v + 8192) & 127, (v + 8192) >> 7], 800);
|
||||
await set(pe.pe0 + 1, c.fix ? 6 : 5); await set(pe.pe0 + 2, -4);
|
||||
P.fmfDev = c.size; peSay(tp("peFmSent").replace("%s", `T${k + 1}`));
|
||||
} catch (_) { peSay(tp("peFail")); }
|
||||
};
|
||||
clr.onclick = async () => { try { await L.link.request(100, [k, 2], 900, (x) => x[0] === k); ta.value = ""; P.fmfDev = 0; check(); peSay(tp("peFmCleared")); } catch (_) { peSay(tp("peFail")); } };
|
||||
}
|
||||
/* ---- a control for a described parameter (DESC): a slider or a list; set calls back as it moves */
|
||||
function peCtl(d, v, set) {
|
||||
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
|
||||
|
||||
Reference in new issue
Block a user