WIP ring code: qr-anchored prototype, encoder, bench, lab pages

This commit is contained in:
2026-08-16 18:00:24 +01:00
parent 07137d8b15
commit d507190b11
12 changed files with 811 additions and 0 deletions
+113
View File
@@ -0,0 +1,113 @@
<!doctype html>
<html lang="fr">
<head><meta charset="utf-8"><title>Ring code bench</title>
<script src="/static/vendor/qr-scanner.umd.min.js"></script>
<script type="module">
import { render, decode, grayOf, homography, DISC } from "/static/js/ringcode.js";
// warps canvas `src` onto a new w x h canvas so that src's unit square maps to quad `dst` (perspective)
function warp(src, dst, w, h, bg) {
const s = src.getContext("2d").getImageData(0, 0, src.width, src.height);
const sw = src.width, sh = src.height;
// homography from dst quad back to src rect corners
const srcPts = [[0, 0], [sw, 0], [sw, sh], [0, sh]];
const A = [], B = [];
for (let i = 0; i < 4; i++) {
const [x, y] = dst[i], [u, v] = srcPts[i];
A.push([x, y, 1, 0, 0, 0, -u * x, -u * y]); B.push(u);
A.push([0, 0, 0, x, y, 1, -v * x, -v * y]); B.push(v);
}
for (let i = 0; i < 8; i++) {
let p = i;
for (let r = i + 1; r < 8; r++) if (Math.abs(A[r][i]) > Math.abs(A[p][i])) p = r;
[A[i], A[p]] = [A[p], A[i]]; [B[i], B[p]] = [B[p], B[i]];
for (let r = 0; r < 8; r++) if (r !== i) { const f = A[r][i] / A[i][i]; for (let k = i; k < 8; k++) A[r][k] -= f * A[i][k]; B[r] -= f * B[i]; }
}
const hm = B.map((b, i) => b / A[i][i]);
const out = document.createElement("canvas"); out.width = w; out.height = h;
const octx = out.getContext("2d"), od = octx.createImageData(w, h);
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
const ww = hm[6] * x + hm[7] * y + 1, u = (hm[0] * x + hm[1] * y + hm[2]) / ww, v = (hm[3] * x + hm[4] * y + hm[5]) / ww;
const o = (y * w + x) * 4;
if (u >= 0 && v >= 0 && u < sw - 1 && v < sh - 1) {
const x0 = u | 0, y0 = v | 0, fx = u - x0, fy = v - y0, i = (y0 * sw + x0) * 4;
for (let c = 0; c < 3; c++) {
od.data[o + c] = (s.data[i + c] * (1 - fx) + s.data[i + 4 + c] * fx) * (1 - fy) + (s.data[i + sw * 4 + c] * (1 - fx) + s.data[i + sw * 4 + 4 + c] * fx) * fy;
}
} else { od.data[o] = bg[0]; od.data[o + 1] = bg[1]; od.data[o + 2] = bg[2]; }
od.data[o + 3] = 255;
}
octx.putImageData(od, 0, 0);
return out;
}
// square of the code area, centred at (cx, cy) with diameter d, tilted by `tilt` deg around an axis at angle `axis`
function quad(cx, cy, d, tilt, axis) {
const t = tilt * Math.PI / 180, a = axis * Math.PI / 180, f = 1.6 * d;
const pts = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([x, y]) => {
// rotate into axis frame, tilt around that axis, rotate back, perspective project
let X = x * Math.cos(a) + y * Math.sin(a), Y = -x * Math.sin(a) + y * Math.cos(a), Z = 0;
const Y2 = Y * Math.cos(t), Z2 = Y * Math.sin(t);
const xr = X * Math.cos(a) - Y2 * Math.sin(a), yr = X * Math.sin(a) + Y2 * Math.cos(a);
const s = f / (f + Z2 * d / 2);
return [cx + xr * d / 2 * s, cy + yr * d / 2 * s];
});
return pts;
}
window.runBench = async (cfg) => {
const engine = await QrScanner.createQrEngine();
QrScanner._disableBarcodeDetector = !!cfg.noBarcodeDetector;
const results = [];
const A = document.createElement("canvas"); A.width = A.height = 800;
const actx = A.getContext("2d");
for (const trial of cfg.trials) {
const side = A.width / (2 * DISC);
actx.fillStyle = "#f5f6fa"; actx.fillRect(0, 0, A.width, A.height);
render(actx, A.width / 2, A.height / 2, side, trial.theta, trial.bits, cfg.modules);
const q = quad(480 + trial.dx, 360 + trial.dy, trial.d, trial.tilt, trial.axis);
let B = warp(A, q, 960, 720, [60, 62, 74]);
const C = document.createElement("canvas"); C.width = 960; C.height = 720;
const cctx = C.getContext("2d");
cctx.filter = `blur(${trial.blur}px) contrast(${trial.contrast}) brightness(${trial.bright})`;
cctx.drawImage(B, 0, 0);
cctx.filter = "none";
if (trial.noise) {
const id = cctx.getImageData(0, 0, 960, 720);
for (let i = 0; i < id.data.length; i += 4) { const n = (Math.random() - 0.5) * 2 * trial.noise; id.data[i] += n; id.data[i + 1] += n; id.data[i + 2] += n; }
cctx.putImageData(id, 0, 0);
}
const t0 = performance.now();
let res = null, qr = false;
try { res = await QrScanner.scanImage(C, { qrEngine: engine, returnDetailedScanResult: true }); qr = true; } catch { /* no qr */ }
let out = { qr, token: null, score: null };
if (res) {
const d = decode(grayOf(cctx.getImageData(0, 0, 960, 720)), res.cornerPoints);
if (d) {
out = { qr, token: d.token, score: +d.score.toFixed(3), scale: d.scale };
if (d.bits) {
const truth = trial.bits.slice(24);
let k = 0; out.errs = [];
for (const n of [28, 32, 36]) { let e = 0; for (let j = 0; j < n; j++) e += d.bits[k + j] !== truth[k + j]; out.errs.push(e); k += n; }
}
}
}
// same decode with the exact qr corners, to tell corner error from decoder bugs
{
const Hq = homography(q.map(([x, y]) => ({ x, y })));
const hs = side / 2 / A.width;
const tc = [[-hs, -hs], [hs, -hs], [hs, hs], [-hs, hs]].map(([u, v]) => { const [x, y] = Hq(u, v); return { x, y }; });
const dt = decode(grayOf(cctx.getImageData(0, 0, 960, 720)), tc);
out.truthOk = !!dt && dt.token === trial.token;
if (res) out.cornerErr = +Math.max(...res.cornerPoints.map((p, i) => Math.hypot(p.x - tc[i].x, p.y - tc[i].y))).toFixed(2);
}
out.ms = Math.round(performance.now() - t0);
out.ok = out.token === trial.token;
results.push({ ...trial, bits: undefined, ...out });
if (cfg.keep && results.length <= cfg.keep) results[results.length - 1].png = C.toDataURL("image/jpeg", 0.8);
}
return results;
};
window.benchReady = true;
</script></head>
<body></body></html>
+14
View File
@@ -0,0 +1,14 @@
html, body { margin: 0; height: 100%; background: #f5f6fa; color: #1c2036; font: 16px/1.4 system-ui, -apple-system, sans-serif; }
#stage { position: fixed; inset: 0; width: 100%; height: 100%; }
.bar { position: fixed; left: 12px; bottom: 12px; display: flex; gap: 8px; flex-wrap: wrap; font-size: 13px; color: #8a8fa3; }
.bar a { color: #1c2036; background: #fff; border-radius: 99px; padding: 6px 12px; text-decoration: none; }
.bar a.on { background: #1c2036; color: #fff; }
.phone { padding: 16px; max-width: 520px; margin: 0 auto; }
.phone video { width: 100%; border-radius: 16px; background: #1c2036; aspect-ratio: 3/4; object-fit: cover; }
.big { font-size: 44px; font-weight: 800; letter-spacing: -.02em; margin: 6px 0; }
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin: 12px 0; }
.grid div { background: #fff; border-radius: 12px; padding: 10px 12px; }
.grid b { display: block; font-size: 22px; }
button { font: 600 16px system-ui; padding: 12px 18px; border-radius: 99px; border: 0; background: #ffcc00; color: #1c2036; width: 100%; margin-top: 8px; }
button.ghost { background: #fff; }
.hist { font-size: 14px; color: #4a4f66; }
File diff suppressed because one or more lines are too long
+20
View File
@@ -0,0 +1,20 @@
<!doctype html>
<html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Labo code circulaire, téléphone</title><link rel="stylesheet" href="/static/ringlab/lab.css">
<script src="/static/vendor/qr-scanner.umd.min.js"></script>
<script type="module" src="/static/ringlab/phone.js"></script></head>
<body><main class="phone">
<video id="v" playsinline muted></video>
<div class="big" id="state">Prêt</div>
<div class="grid">
<div>Images analysées<b id="frames">0</b></div>
<div>Images par seconde<b id="fps">0</b></div>
<div>QR central détecté<b id="qr">0 %</b></div>
<div>Anneaux lus (si QR vu)<b id="ring">0 %</b></div>
<div>Codes distincts<b id="count">0 / 5</b></div>
<div>Mode vu<b id="mode">aucun</b></div>
</div>
<button id="go">Démarrer la caméra</button>
<button id="again" class="ghost">Nouvel essai</button>
<p class="hist" id="hist"></p>
</main></body></html>
+66
View File
@@ -0,0 +1,66 @@
import { decode, grayOf } from "/static/js/ringcode.js";
const $ = (id) => document.getElementById(id);
const video = $("v"), canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true });
let engine, running = false, frames = 0, qr = 0, ring = 0, t0 = 0, fpsT = performance.now(), fpsN = 0;
let tokens = new Set(), mode = "aucun";
const history = [];
function reset() {
tokens = new Set(); t0 = performance.now(); frames = qr = ring = 0;
$("state").textContent = "Visez l'écran";
}
async function start() {
engine = await QrScanner.createQrEngine();
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: { ideal: "environment" }, width: { ideal: 1920 }, height: { ideal: 1080 } },
});
video.srcObject = stream;
await video.play();
running = true;
reset();
loop();
}
async function loop() {
if (!running) return;
if (video.readyState >= 2) {
const k = Math.min(1, 1280 / video.videoWidth);
canvas.width = Math.round(video.videoWidth * k);
canvas.height = Math.round(video.videoHeight * k);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
frames++; fpsN++;
let res = null;
try { res = await QrScanner.scanImage(canvas, { qrEngine: engine, returnDetailedScanResult: true }); } catch { /* none */ }
if (res) {
qr++;
if (res.data.includes("#")) {
mode = "QR classique";
tokens.add(res.data.split("#")[1]);
} else {
mode = "anneaux";
const d = decode(grayOf(ctx.getImageData(0, 0, canvas.width, canvas.height)), res.cornerPoints);
if (d && d.token) { ring++; tokens.add(d.token); }
}
}
if (tokens.size >= 5 && t0) {
const s = (performance.now() - t0) / 1000;
history.push(s.toFixed(1));
$("state").textContent = `5 codes en ${s.toFixed(1)} s`;
$("hist").textContent = `Essais : ${history.join(" s, ")} s`;
t0 = 0;
}
const now = performance.now();
if (now - fpsT > 1000) { $("fps").textContent = (fpsN * 1000 / (now - fpsT)).toFixed(1); fpsT = now; fpsN = 0; }
$("frames").textContent = frames;
$("qr").textContent = `${Math.round((100 * qr) / Math.max(1, frames))} %`;
$("ring").textContent = mode === "anneaux" ? `${Math.round((100 * ring) / Math.max(1, qr))} %` : "–";
$("count").textContent = `${Math.min(tokens.size, 5)} / 5`;
$("mode").textContent = mode;
}
setTimeout(loop, 0);
}
$("go").addEventListener("click", () => start().catch((e) => { $("state").textContent = `Caméra : ${e.message}`; }));
$("again").addEventListener("click", reset);
+8
View File
@@ -0,0 +1,8 @@
<!doctype html>
<html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Labo code circulaire, écran</title><link rel="stylesheet" href="/static/ringlab/lab.css">
<script type="module" src="/static/ringlab/screen.js"></script></head>
<body><canvas id="stage"></canvas>
<div class="bar"><a id="m-ring" href="?mode=ring">Anneaux</a><a id="m-qr" href="?mode=qr">QR classique</a>
<a id="i-1000" href="#">1 s</a><a id="i-500" href="#">0,5 s</a><span id="info"></span></div>
</body></html>
+42
View File
@@ -0,0 +1,42 @@
import { render, rsEncode, dataBits, SYNC, DISC } from "/static/js/ringcode.js";
const params = new URLSearchParams(location.search);
const MS = +params.get("ms") || 1000, MODE = params.get("mode") || "ring";
const lab = await fetch("/static/ringlab/lab.json").then((r) => r.json());
const cv = document.getElementById("stage"), ctx = cv.getContext("2d");
document.getElementById(`m-${MODE}`)?.classList.add("on");
for (const ms of [1000, 500]) {
const a = document.getElementById(`i-${ms}`);
a.href = `?mode=${MODE}&ms=${ms}`;
if (ms === MS) a.classList.add("on");
}
let slot = 0, bits = "", idx = 0;
function tick() {
slot = (slot + 1) & 0xffff;
const mac = [...crypto.getRandomValues(new Uint8Array(4))];
bits = SYNC + dataBits(rsEncode([(slot >> 8) & 255, slot & 255, ...mac]));
idx = (idx + 1) % lab.classic.length;
document.getElementById("info").textContent = MODE === "ring" ? `code ${slot}` : `code ${lab.classic[idx].token.split(".")[0].slice(-4)}`;
}
tick();
setInterval(tick, MS);
function frame(t) {
const dpr = devicePixelRatio || 1, w = innerWidth * dpr, h = innerHeight * dpr;
if (cv.width !== w || cv.height !== h) { cv.width = w; cv.height = h; }
ctx.fillStyle = "#f5f6fa"; ctx.fillRect(0, 0, w, h);
const size = Math.min(w, h) * 0.9;
if (MODE === "ring") {
// one full turn every 45 s
render(ctx, w / 2, h / 2, size / (2 * DISC), (t / 1000) * (2 * Math.PI / 45), bits, lab.center);
} else {
const m = lab.classic[idx].modules, n = m.length, s = Math.floor(size / (n + 8));
const x0 = (w - n * s) / 2, y0 = (h - n * s) / 2;
ctx.fillStyle = "#fff"; ctx.fillRect(x0 - 4 * s, y0 - 4 * s, (n + 8) * s, (n + 8) * s);
ctx.fillStyle = "#000";
for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) if (m[y][x] === "1") ctx.fillRect(x0 + x * s, y0 + y * s, s, s);
}
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);