Files

171 lines
9.7 KiB
JavaScript

// synthetic camera frames of a projected ring code: a washed-out screen in a room, seen by a phone sensor
import { render, DISC } from "/static/js/ringcode.js";
import { render as renderV1 } from "/static/ringlab/ringcode_v1.js";
// v1: draw the code as it was before the far-reading work, for baselines
export const design = { v1: false };
export function lcg(seed) {
let s = (seed >>> 0) || 1;
return () => ((s = (Math.imul(s, 1103515245) + 12345) & 0x7fffffff) / 0x7fffffff);
}
// 8 coefs of the homography sending src[i] to dst[i]
function homography(src, dst) {
const A = [], B = [];
for (let i = 0; i < 4; i++) {
const [x, y] = src[i], [u, v] = dst[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]; }
}
return B.map((b, i) => b / A[i][i]);
}
const applyH = (h, x, y) => { const w = h[6] * x + h[7] * y + 1; return [(h[0] * x + h[1] * y + h[2]) / w, (h[3] * x + h[4] * y + h[5]) / w]; };
export function makeRoom(W, H, kind, rnd) {
const c = document.createElement("canvas"); c.width = W; c.height = H;
const ctx = c.getContext("2d");
// dark room: lights off for the projector. bright: daylight, full range clutter around the screen
const lmax = kind === "dark" ? 28 : 95, lmin = kind === "dark" ? 2 : 15;
const L = () => lmin + rnd() * (lmax - lmin);
const g = ctx.createLinearGradient(0, 0, W, H);
g.addColorStop(0, `hsl(${rnd() * 360}, 15%, ${L()}%)`); g.addColorStop(1, `hsl(${rnd() * 360}, 20%, ${L()}%)`);
ctx.fillStyle = g; ctx.fillRect(0, 0, W, H);
const k = W / 960;
for (let i = 0; i < 22; i++) {
ctx.fillStyle = `hsl(${rnd() * 360}, ${rnd() * 40}%, ${L()}%)`;
const t = rnd();
if (t < 0.4) ctx.fillRect(rnd() * W, rnd() * H, (20 + rnd() * 200) * k, (10 + rnd() * 120) * k);
else if (t < 0.65) { ctx.beginPath(); ctx.arc(rnd() * W, rnd() * H, (6 + rnd() * 60) * k, 0, 7); ctx.fill(); } // decoy discs (heads, lamps)
else if (t < 0.8) { ctx.font = `${(14 + rnd() * 40) * k}px system-ui`; ctx.fillText("Assemblée générale 2026", rnd() * W, rnd() * H); }
else { ctx.lineWidth = (2 + rnd() * 10) * k; ctx.strokeStyle = ctx.fillStyle; ctx.beginPath(); ctx.moveTo(rnd() * W, rnd() * H); ctx.lineTo(rnd() * W, rnd() * H); ctx.stroke(); }
}
return c;
}
// the projector page around the code: light page, title, the small entry qr, a few text lines
function page(pw, ph, d, t, rnd) {
const c = document.createElement("canvas"); c.width = pw; c.height = ph;
const ctx = c.getContext("2d", { willReadFrequently: true });
ctx.fillStyle = "#f5f6fa"; ctx.fillRect(0, 0, pw, ph);
const cx = pw * 0.36, cy = ph * 0.54, unit = (d / 2 / DISC);
if (!t.nocode) (design.v1 ? renderV1 : render)(ctx, cx, cy, unit, t.theta, t.bits, t.anim, t.fade || null);
ctx.fillStyle = "#1c2036";
ctx.font = `700 ${d * 0.11}px system-ui`; ctx.fillText("Inscription", pw * 0.66, ph * 0.2);
ctx.font = `${d * 0.05}px system-ui`;
for (let i = 0; i < 3; i++) ctx.fillText("Ouvrez la page de vote", pw * 0.66, ph * (0.3 + i * 0.07));
const m = 25, q = d * 0.36, qx = pw * 0.68, qy = ph * 0.52, r2 = lcg(t.qseed || 7);
for (let i = 0; i < m; i++) for (let j = 0; j < m; j++) if (r2() < 0.5) ctx.fillRect(qx + (i * q) / m, qy + (j * q) / m, q / m + 0.5, q / m + 0.5);
if (t.nocode && t.decoy) {
// things a projector may show instead: a plain dark disc, a pie chart
ctx.beginPath(); ctx.arc(cx, cy, unit * (0.4 + rnd() * 0.8), 0, 7); ctx.fill();
if (t.decoy > 1) for (let i = 0; i < 5; i++) { ctx.lineWidth = unit * 0.1; ctx.strokeStyle = `rgba(28,32,54,${rnd()})`; ctx.beginPath(); ctx.arc(cx, cy, unit * (0.9 + i * 0.15), rnd() * 7, rnd() * 7); ctx.stroke(); }
}
// washed projection: raised black, lower white, colour cast. only the screen is affected
const [b0, w0] = t.wash || [0, 255], cast = t.cast || [1, 1, 1];
const id = ctx.getImageData(0, 0, pw, ph), px = id.data;
for (let i = 0; i < px.length; i += 4) for (let ch = 0; ch < 3; ch++) px[i + ch] = (b0 + (px[i + ch] / 255) * (w0 - b0)) * cast[ch];
ctx.putImageData(id, 0, 0);
return { canvas: c, id, cx, cy, unit };
}
// one sensor frame. t: W H frac tilt axis dist wash cast oblur pblur motion noise band gain dx dy theta bits anim fade
// glare: [dx, dy, radius, strength 0..1, tint] around the code centre, in code diameters
// returns { canvas, truth } where truth maps code space to pixel index coordinates of the frame
export function frame(room, t, rnd) {
const { W, H } = t, ss = 2;
const d = t.frac * W; // code disc diameter in sensor px
const sw = 2.3 * d, sh = 1.5 * d; // projected page in sensor px, before tilt
const P = page(Math.round(sw * ss), Math.round(sh * ss), d * ss, t, rnd);
const pw = P.canvas.width, ph = P.canvas.height;
const tl = (t.tilt * Math.PI) / 180, a = (t.axis * Math.PI) / 180, f = (t.dist || 3.5) * d;
// keep the code itself near the frame centre, the page hangs around it
const ox = W / 2 + (t.dx || 0) + (0.5 - 0.36) * sw, oy = H / 2 + (t.dy || 0) + (0.5 - 0.54) * sh;
const corner = (x, y) => {
const X = x * Math.cos(a) + y * Math.sin(a), Y = -x * Math.sin(a) + y * Math.cos(a);
const Y2 = Y * Math.cos(tl), Z2 = Y * Math.sin(tl);
const xr = X * Math.cos(a) - Y2 * Math.sin(a), yr = X * Math.sin(a) + Y2 * Math.cos(a), s = f / (f + Z2);
return [ox + xr * s, oy + yr * s];
};
const quad = [[-sw / 2, -sh / 2], [sw / 2, -sh / 2], [sw / 2, sh / 2], [-sw / 2, sh / 2]].map(([x, y]) => corner(x, y));
const src = [[0, 0], [pw, 0], [pw, ph], [0, ph]];
const inv = homography(quad, src), fwd = homography(src, quad);
const x0 = Math.max(0, Math.floor(Math.min(...quad.map((p) => p[0])))), x1 = Math.min(W, Math.ceil(Math.max(...quad.map((p) => p[0]))));
const y0 = Math.max(0, Math.floor(Math.min(...quad.map((p) => p[1])))), y1 = Math.min(H, Math.ceil(Math.max(...quad.map((p) => p[1]))));
const bw = (x1 - x0) * ss, bh = (y1 - y0) * ss;
const scene = document.createElement("canvas"); scene.width = W; scene.height = H;
const sctx = scene.getContext("2d");
sctx.drawImage(room, 0, 0);
if (bw > 0 && bh > 0) {
// warp at 2x then box-downscale, so small codes are area-sampled instead of aliased
const B = document.createElement("canvas"); B.width = bw; B.height = bh;
const bctx = B.getContext("2d"), od = bctx.createImageData(bw, bh), s = P.id.data;
for (let Y = 0; Y < bh; Y++) for (let X = 0; X < bw; X++) {
const [pu, pv] = applyH(inv, x0 + (X + 0.5) / ss, y0 + (Y + 0.5) / ss), u = pu - 0.5, v = pv - 0.5, o = (Y * bw + X) * 4;
if (u >= 0 && v >= 0 && u < pw - 1 && v < ph - 1) {
const ix = u | 0, iy = v | 0, fx = u - ix, fy = v - iy, i = (iy * pw + ix) * 4;
for (let ch = 0; ch < 3; ch++) od.data[o + ch] = (s[i + ch] * (1 - fx) + s[i + 4 + ch] * fx) * (1 - fy) + (s[i + pw * 4 + ch] * (1 - fx) + s[i + pw * 4 + 4 + ch] * fx) * fy;
od.data[o + 3] = 255;
}
}
bctx.putImageData(od, 0, 0);
sctx.imageSmoothingQuality = "high";
sctx.drawImage(B, x0, y0, x1 - x0, y1 - y0);
}
if (t.glare) {
// reflection of a window or lamp on the screen: a tinted bright veil over part of the code
const [gx, gy, gr, gs, tint] = t.glare, [ccx, ccy] = applyH(fwd, P.cx, P.cy);
const x = ccx + gx * d, y = ccy + gy * d, g = sctx.createRadialGradient(x, y, 0, x, y, gr * d);
const [tr, tg, tb] = tint || [255, 235, 245];
g.addColorStop(0, `rgba(${tr},${tg},${tb},${gs})`); g.addColorStop(0.5, `rgba(${tr},${tg},${tb},${gs * 0.6})`); g.addColorStop(1, `rgba(${tr},${tg},${tb},0)`);
sctx.globalCompositeOperation = "screen";
sctx.fillStyle = g; sctx.fillRect(0, 0, W, H);
sctx.globalCompositeOperation = "source-over";
}
const out = document.createElement("canvas"); out.width = W; out.height = H;
const octx = out.getContext("2d", { willReadFrequently: true });
// optical blur is angular (scales with sensor resolution), pixel softness is not
const sigma = Math.hypot((t.oblur || 0) * (W / 1280), t.pblur || 0);
octx.filter = `blur(${sigma}px) brightness(${t.gain || 1})`;
const [mx, my] = (t.motion || [0, 0]).map((v) => v * (W / 1280)), steps = Math.max(1, Math.ceil(Math.hypot(mx, my)));
for (let i = 0; i < steps; i++) {
const k = steps > 1 ? i / (steps - 1) - 0.5 : 0;
octx.globalAlpha = 1 / (i + 1);
octx.drawImage(scene, mx * k, my * k);
}
octx.globalAlpha = 1; octx.filter = "none";
if (t.noise || t.band) {
const id = octx.getImageData(0, 0, W, H), px = id.data, period = (t.bandPeriod || 90) * (H / 720), ph0 = rnd() * 7;
for (let y = 0, i = 0; y < H; y++) {
// rolling shutter vs projector/lamp flicker: horizontal brightness bands
const g = 1 + (t.band || 0) * Math.sin((y / period) * 2 * Math.PI + ph0);
for (let x = 0; x < W; x++, i += 4) {
const n = (rnd() + rnd() + rnd() - 1.5) * 2 * (t.noise || 0);
px[i] = px[i] * g + n; px[i + 1] = px[i + 1] * g + n; px[i + 2] = px[i + 2] * g + n;
}
}
octx.putImageData(id, 0, 0);
}
const truth = (x, y) => {
const [u, v] = applyH(fwd, P.cx + x * P.unit, P.cy + y * P.unit);
return [u - 0.5, v - 0.5];
};
return { canvas: out, truth, d };
}
// lossy video path of cheap phones: jpeg round trip
export async function jpeg(canvas, q) {
const img = new Image();
img.src = canvas.toDataURL("image/jpeg", q);
await img.decode();
const c = document.createElement("canvas"); c.width = canvas.width; c.height = canvas.height;
c.getContext("2d", { willReadFrequently: true }).drawImage(img, 0, 0);
return c;
}