turn-check.mjs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. import { spawn } from "node:child_process";
  2. import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  3. import { homedir, tmpdir } from "node:os";
  4. import { dirname, join, resolve } from "node:path";
  5. import { pathToFileURL } from "node:url";
  6. import { LINE_ENDS } from "./line-ends.mjs";
  7. function usage() {
  8. console.log(`Checks for 3D figures (turning groups).
  9. node turn-check.mjs build.mjs --fidelity [--angles 7,37,…]
  10. Node: every live prism against k.extrude / G.prismOf, every round and lathe against G.lathe(smooth) and every tube
  11. against tubePieces, at P'(θ). Control: one prism drawn 2° off must fail.
  12. node turn-check.mjs page.html [--order] [--pops] [--lines] [--perf] [--step 1] [--states states.json]
  13. [--width 1440] [--height 1100] [--scale 2] [--throttle 1] [--no-webgl] [--out dir]
  14. --order needs a --verify build: the recorded shapes in a WebGL z-buffer (part-ID colours, 2x) against the live
  15. layers' fills in DOM order. Fails on any live pair with 4 or more interior pixels. Static × live mismatches
  16. are listed (the layer proofs and the orbit audit own them). Control: each live layer's order reversed at
  17. 0, 90, 180 and 270 must give at least 1000 mismatched pixels.
  18. --pops first difference θ → θ+0.02° at every step, and second difference at 0.1° over a full turn; control: one
  19. part's fill hidden for one frame must fail. Run with --no-webgl and the tour held.
  20. --lines LINE_ENDS at 24 angles (run it on the light and the dark page); control: a planted floating line must fail.
  21. --perf 240 frames at 1.1° per frame driven through the controller inside requestAnimationFrame: script, task,
  22. style and layout per frame, frame interval median and p95, live elements, writes and moves per frame.
  23. --states a JSON list of value objects to visit instead of angles (gestures, a break-apart).
  24. The angle is the figure's first turn group (window.__isoTurn.set(θ)).`);
  25. }
  26. function playwrightShells() {
  27. const found = [];
  28. for (const root of [join(homedir(), ".cache/ms-playwright"), join(homedir(), "Library/Caches/ms-playwright")]) {
  29. if (!existsSync(root)) continue;
  30. for (const dir of readdirSync(root).filter((d) => d.startsWith("chromium_headless_shell-")).sort().reverse()) {
  31. for (const sub of ["chrome-headless-shell-linux64/chrome-headless-shell", "chrome-headless-shell-mac-arm64/chrome-headless-shell", "chrome-headless-shell-mac-x64/chrome-headless-shell"]) {
  32. found.push(join(root, dir, sub));
  33. }
  34. }
  35. }
  36. return found;
  37. }
  38. function chromePath() {
  39. const candidates = [process.env.CHROME_PATH, ...playwrightShells(), "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium", "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/usr/bin/chromium", "/usr/bin/chromium-browser"].filter(Boolean);
  40. const playwright = join(homedir(), "Library/Caches/ms-playwright");
  41. if (existsSync(playwright)) for (const dir of readdirSync(playwright).sort().reverse()) for (const sub of ["chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing", "chrome-mac/Chromium.app/Contents/MacOS/Chromium", "chrome-linux/chrome"]) candidates.push(join(playwright, dir, sub));
  42. return candidates.find((path) => existsSync(path));
  43. }
  44. async function browser(target, { width, height, scale, throttle, noWebgl }) {
  45. const profile = mkdtempSync(join(tmpdir(), "turn-check-"));
  46. const chrome = spawn(chromePath(), ["--headless=new", "--remote-debugging-port=0", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", "--hide-scrollbars", "--allow-file-access-from-files", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist", "about:blank"]);
  47. const port = await new Promise((done, fail) => {
  48. let text = "";
  49. const timer = setTimeout(() => fail(new Error("Chrome did not start")), 20000);
  50. chrome.stderr.on("data", (chunk) => {
  51. text += chunk;
  52. const match = text.match(/DevTools listening on ws:\/\/[^:]+:(\d+)\//);
  53. if (match) {
  54. clearTimeout(timer);
  55. done(Number(match[1]));
  56. }
  57. });
  58. });
  59. const page = await (await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: "PUT" })).json();
  60. const socket = new WebSocket(page.webSocketDebuggerUrl);
  61. let id = 0;
  62. const pending = new Map();
  63. const problems = [];
  64. socket.onmessage = (message) => {
  65. const data = JSON.parse(message.data);
  66. if (data.id && pending.has(data.id)) {
  67. pending.get(data.id)(data);
  68. pending.delete(data.id);
  69. } else if (data.method === "Runtime.consoleAPICalled" && (data.params.type === "error" || data.params.type === "warning")) problems.push(`console.${data.params.type}: ${data.params.args.map((arg) => arg.value ?? arg.description ?? "").join(" ").slice(0, 400)}`);
  70. else if (data.method === "Runtime.exceptionThrown") problems.push(`exception: ${data.params.exceptionDetails.exception?.description ?? data.params.exceptionDetails.text}`.slice(0, 400));
  71. };
  72. await new Promise((done) => (socket.onopen = done));
  73. const send = (method, params = {}) =>
  74. new Promise((done) => {
  75. const call = ++id;
  76. pending.set(call, done);
  77. socket.send(JSON.stringify({ id: call, method, params }));
  78. });
  79. const evaluate = async (expression) => {
  80. const result = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
  81. if (result.result?.exceptionDetails) throw new Error(JSON.stringify(result.result.exceptionDetails).slice(0, 800));
  82. return result.result?.result?.value;
  83. };
  84. await send("Runtime.enable");
  85. await send("Page.enable");
  86. const NO_GL = `(()=>{const get=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(kind,...rest){if(/webgl/.test(String(kind))&&!this.dataset.check)return null;return get.call(this,kind,...rest)}})();`;
  87. if (noWebgl) await send("Page.addScriptToEvaluateOnNewDocument", { source: NO_GL });
  88. await send("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor: scale, mobile: width < 600 });
  89. if (throttle > 1) await send("Emulation.setCPUThrottlingRate", { rate: throttle });
  90. const url = /^https?:|^file:/.test(target) ? target : pathToFileURL(resolve(target)).href;
  91. await send("Page.navigate", { url });
  92. await new Promise((done) => setTimeout(done, 1500));
  93. const close = () => {
  94. socket.close();
  95. chrome.kill("SIGKILL");
  96. try {
  97. rmSync(profile, { recursive: true, force: true });
  98. } catch {}
  99. };
  100. return { send, evaluate, close, problems };
  101. }
  102. const HELPERS = String.raw`(() => {
  103. const stage = document.querySelector(".iso-turn") || document.querySelector(".iso-stage");
  104. const svgs = [...stage.querySelectorAll(":scope > svg")];
  105. const hook = window.__isoTurn;
  106. const C = hook.controller;
  107. const vb = svgs[0].viewBox.baseVal;
  108. const W = vb.width;
  109. const H = vb.height;
  110. const css = [...document.querySelectorAll("style")].map((s) => s.textContent).join("\n");
  111. const theme = (stage.closest("[data-theme]") || document.body).getAttribute("data-theme") || "dark";
  112. const setState = (state) => (typeof state === "number" ? C.set(state) : C.set(state));
  113. const matrixOf = (el) => {
  114. const m = el.ownerSVGElement.getScreenCTM().inverse().multiply(el.getScreenCTM());
  115. return "matrix(" + m.a + " " + m.b + " " + m.c + " " + m.d + " " + m.e + " " + m.f + ")";
  116. };
  117. const decode = async (svg, w, h) => {
  118. const url = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" }));
  119. const image = new Image();
  120. await new Promise((done, fail) => { image.onload = done; image.onerror = fail; image.src = url; });
  121. const canvas = Object.assign(document.createElement("canvas"), { width: w, height: h });
  122. const ctx = canvas.getContext("2d", { willReadFrequently: true });
  123. ctx.drawImage(image, 0, 0, w, h);
  124. URL.revokeObjectURL(url);
  125. return ctx.getImageData(0, 0, w, h).data;
  126. };
  127. window.__tc = { stage, svgs, hook, C, W, H, css, theme, setState, matrixOf, decode };
  128. return { W, H, layers: svgs.map((s) => s.dataset.live || null), theme };
  129. })()`;
  130. const ZBUFFER = String.raw`(() => {
  131. const { svgs, C, W, H, setState, matrixOf, decode } = window.__tc;
  132. const V = window.__isoVerify;
  133. const SCALE = 2;
  134. const w = W * SCALE;
  135. const h = H * SCALE;
  136. const STATIC = 30000;
  137. const add3 = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
  138. const mul3 = (a, k) => [a[0] * k, a[1] * k, a[2] * k];
  139. const sub3 = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
  140. const dot3 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  141. const cross3 = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
  142. const unit3 = (a) => { const l = Math.hypot(a[0], a[1], a[2]) || 1; return [a[0] / l, a[1] / l, a[2] / l]; };
  143. const frameOf = (F) => {
  144. if (F.u && F.v) return F;
  145. const a = unit3(F.a);
  146. const helper = Math.abs(a[2]) > 0.9 ? [1, 0, 0] : [0, 0, 1];
  147. const u = unit3(cross3(helper, a));
  148. return { o: F.o, a, u, v: cross3(a, u) };
  149. };
  150. function meshOf(shape) {
  151. const tris = [];
  152. const quad = (a, b, c, d) => tris.push(a, b, c, a, c, d);
  153. if (shape.kind === "prism") {
  154. const F = frameOf(shape.F);
  155. const at = (s, [x, y]) => add3(add3(F.o, mul3(F.a, s)), add3(mul3(F.u, x), mul3(F.v, y)));
  156. const n = shape.poly.length;
  157. const centre = shape.poly.reduce((s, p) => [s[0] + p[0] / n, s[1] + p[1] / n], [0, 0]);
  158. for (const s of [shape.s0, shape.s1]) for (let i = 0; i < n; i++) tris.push(at(s, centre), at(s, shape.poly[i]), at(s, shape.poly[(i + 1) % n]));
  159. for (let i = 0; i < n; i++) quad(at(shape.s0, shape.poly[i]), at(shape.s0, shape.poly[(i + 1) % n]), at(shape.s1, shape.poly[(i + 1) % n]), at(shape.s1, shape.poly[i]));
  160. } else if (shape.kind === "body") {
  161. const F = frameOf(shape.F);
  162. const count = 72;
  163. const ring = (s, r) => Array.from({ length: count }, (_, j) => { const t = (j / count) * Math.PI * 2; return add3(add3(F.o, mul3(F.a, s)), add3(mul3(F.u, r * Math.cos(t)), mul3(F.v, r * Math.sin(t)))); });
  164. const poly = shape.poly;
  165. for (let i = 0; i < poly.length; i++) {
  166. const [s0, r0] = poly[i];
  167. const [s1, r1] = poly[(i + 1) % poly.length];
  168. if (r0 < 1e-9 && r1 < 1e-9) continue;
  169. const a = ring(s0, r0);
  170. const b = ring(s1, r1);
  171. for (let j = 0; j < count; j++) quad(a[j], a[(j + 1) % count], b[(j + 1) % count], b[j]);
  172. }
  173. } else if (shape.kind === "ball") {
  174. const rows = 32;
  175. const cols = 64;
  176. const flats = shape.flats || [];
  177. const at = (i, j) => {
  178. const phi = (i / rows) * Math.PI;
  179. const t = (j / cols) * Math.PI * 2;
  180. let n = [Math.sin(phi) * Math.cos(t), Math.sin(phi) * Math.sin(t), Math.cos(phi)];
  181. let p = mul3(n, shape.r);
  182. for (const [nx, ny, nz, d] of flats) {
  183. const k = nx * p[0] + ny * p[1] + nz * p[2];
  184. if (k > d) p = sub3(p, mul3([nx, ny, nz], k - d));
  185. }
  186. return add3(shape.o, p);
  187. };
  188. for (let i = 0; i < rows; i++) for (let j = 0; j < cols; j++) quad(at(i, j), at(i, j + 1), at(i + 1, j + 1), at(i + 1, j));
  189. } else if (shape.kind === "box") {
  190. const c = (sx, sy, sz) => add3(shape.o, add3(add3(mul3(shape.axes[0], sx * shape.half[0]), mul3(shape.axes[1], sy * shape.half[1])), mul3(shape.axes[2], sz * shape.half[2])));
  191. const v = [c(-1, -1, -1), c(1, -1, -1), c(1, 1, -1), c(-1, 1, -1), c(-1, -1, 1), c(1, -1, 1), c(1, 1, 1), c(-1, 1, 1)];
  192. for (const [a, b, cc, d] of [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]) quad(v[a], v[b], v[cc], v[d]);
  193. } else if (shape.kind === "tube") {
  194. const pts = [];
  195. const radii = [];
  196. shape.points.forEach((p, i) => {
  197. if (pts.length && Math.hypot(p[0] - pts[pts.length - 1][0], p[1] - pts[pts.length - 1][1], p[2] - pts[pts.length - 1][2]) < 1e-6) return;
  198. pts.push(p);
  199. radii.push(shape.radii[i]);
  200. });
  201. if (pts.length < 2) return tris;
  202. const count = 20;
  203. let u = null;
  204. const rings = pts.map((p, i) => {
  205. const t = unit3(sub3(pts[Math.min(pts.length - 1, i + 1)], pts[Math.max(0, i - 1)]));
  206. if (!u) { const helper = Math.abs(t[2]) > 0.9 ? [1, 0, 0] : [0, 0, 1]; u = unit3(cross3(helper, t)); } else u = unit3(sub3(u, mul3(t, dot3(u, t))));
  207. const v = cross3(t, u);
  208. const r = radii[i];
  209. return Array.from({ length: count }, (_, j) => { const a = (j / count) * Math.PI * 2; return add3(p, add3(mul3(u, r * Math.cos(a)), mul3(v, r * Math.sin(a)))); });
  210. });
  211. for (let i = 0; i < rings.length - 1; i++) for (let j = 0; j < count; j++) quad(rings[i][j], rings[i][(j + 1) % count], rings[i + 1][(j + 1) % count], rings[i + 1][j]);
  212. for (const [index, p] of [[0, pts[0]], [rings.length - 1, pts[pts.length - 1]]]) for (let j = 0; j < count; j++) tris.push(p, rings[index][j], rings[index][(j + 1) % count]);
  213. }
  214. return tris;
  215. }
  216. const canvas = Object.assign(document.createElement("canvas"), { width: w, height: h });
  217. canvas.dataset.check = "1";
  218. const gl = canvas.getContext("webgl", { antialias: false, preserveDrawingBuffer: true, alpha: false, depth: true });
  219. const vs = "attribute vec3 p;uniform vec3 uR0;uniform vec3 uR1;uniform vec3 uR2;uniform vec3 uT;uniform vec3 uM0;uniform vec3 uM1;uniform vec2 uO;uniform vec3 uV;uniform vec2 uView;uniform float uSpan;void main(){vec3 q=vec3(dot(uR0,p),dot(uR1,p),dot(uR2,p))+uT;vec2 s=uO+vec2(dot(uM0,q),dot(uM1,q));gl_Position=vec4(s.x/uView.x*2.-1.,1.-s.y/uView.y*2.,-dot(uV,q)/uSpan,1.);}";
  220. const fs = "precision highp float;uniform vec3 uId;void main(){gl_FragColor=vec4(uId,1.);}";
  221. const compile = (type, source) => { const sh = gl.createShader(type); gl.shaderSource(sh, source); gl.compileShader(sh); if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(sh)); return sh; };
  222. const program = gl.createProgram();
  223. gl.attachShader(program, compile(gl.VERTEX_SHADER, vs));
  224. gl.attachShader(program, compile(gl.FRAGMENT_SHADER, fs));
  225. gl.linkProgram(program);
  226. gl.useProgram(program);
  227. const loc = (name) => gl.getUniformLocation(program, name);
  228. const where = { p: gl.getAttribLocation(program, "p"), R0: loc("uR0"), R1: loc("uR1"), R2: loc("uR2"), T: loc("uT"), M0: loc("uM0"), M1: loc("uM1"), O: loc("uO"), V: loc("uV"), view: loc("uView"), span: loc("uSpan"), id: loc("uId") };
  229. const bufferOf = (shapes) => {
  230. const pos = [];
  231. for (const shape of shapes) for (const p of meshOf(shape)) pos.push(p[0], p[1], p[2]);
  232. const b = gl.createBuffer();
  233. gl.bindBuffer(gl.ARRAY_BUFFER, b);
  234. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(pos), gl.STATIC_DRAW);
  235. return { b, count: pos.length / 3 };
  236. };
  237. const parts = V.parts.map((part, index) => ({ index, group: part.group, name: part.name, mesh: bufferOf(part.shapes) }));
  238. const statics = V.statics.map((item) => ({ rank: item.rank, mesh: bufferOf(item.shapes) }));
  239. const colour = (id) => [((id + 1) & 255) / 255, (((id + 1) >> 8) & 255) / 255, 0];
  240. const zIds = () => {
  241. const cams = C.cams();
  242. const world = cams.world;
  243. gl.viewport(0, 0, w, h);
  244. gl.enable(gl.DEPTH_TEST);
  245. gl.depthFunc(gl.LESS);
  246. gl.clearColor(0, 0, 0, 1);
  247. gl.clearDepth(1);
  248. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  249. gl.uniform3f(where.M0, world.m[0], world.m[1], world.m[2]);
  250. gl.uniform3f(where.M1, world.m[3], world.m[4], world.m[5]);
  251. gl.uniform2f(where.O, world.ox, world.oy);
  252. gl.uniform3f(where.V, world.V[0], world.V[1], world.V[2]);
  253. gl.uniform2f(where.view, W, H);
  254. gl.uniform1f(where.span, 4000);
  255. const draw = (mesh, R, t, id) => {
  256. gl.uniform3f(where.R0, R[0], R[1], R[2]);
  257. gl.uniform3f(where.R1, R[3], R[4], R[5]);
  258. gl.uniform3f(where.R2, R[6], R[7], R[8]);
  259. gl.uniform3f(where.T, t[0], t[1], t[2]);
  260. gl.uniform3fv(where.id, colour(id));
  261. gl.bindBuffer(gl.ARRAY_BUFFER, mesh.b);
  262. gl.enableVertexAttribArray(where.p);
  263. gl.vertexAttribPointer(where.p, 3, gl.FLOAT, false, 0, 0);
  264. gl.drawArrays(gl.TRIANGLES, 0, mesh.count);
  265. };
  266. const eye = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  267. for (const item of statics) draw(item.mesh, eye, [0, 0, 0], STATIC + item.rank);
  268. for (const part of parts) {
  269. const cam = part.group >= 0 ? cams[part.group] : null;
  270. draw(part.mesh, cam ? cam.R : eye, cam ? cam.t : [0, 0, 0], part.index);
  271. }
  272. const pixels = new Uint8Array(w * h * 4);
  273. gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
  274. const ids = new Int32Array(w * h);
  275. for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const i = ((h - 1 - y) * w + x) * 4; ids[y * w + x] = pixels[i] + pixels[i + 1] * 256 - 1; }
  276. return ids;
  277. };
  278. const toId = (id) => "rgb(" + ((id + 1) & 255) + "," + (((id + 1) >> 8) & 255) + ",0)";
  279. const painterSvg = (reverse = false) => {
  280. const out = [];
  281. let rank = 0;
  282. for (const svg of svgs) {
  283. if (svg.dataset.live) {
  284. const nodes = [...svg.querySelectorAll("[data-p]")];
  285. if (reverse) nodes.reverse();
  286. for (const node of nodes) for (const el of node.querySelectorAll(".iso-fill, .tb-body")) out.push('<path d="' + el.getAttribute("d") + '" transform="' + matrixOf(el) + '" fill-rule="' + (el.getAttribute("fill-rule") || "nonzero") + '" fill="' + toId(Number(node.dataset.p)) + '"/>');
  287. } else {
  288. for (const el of svg.querySelectorAll(".iso-fill, .tb-body")) out.push('<path d="' + el.getAttribute("d") + '" transform="' + matrixOf(el) + '" fill-rule="' + (el.getAttribute("fill-rule") || "nonzero") + '" fill="' + toId(STATIC + rank) + '"/>');
  289. rank++;
  290. }
  291. }
  292. return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' + W + " " + H + '" width="' + w + '" height="' + h + '" shape-rendering="crispEdges"><rect width="100%" height="100%" fill="rgb(0,0,0)"/>' + out.join("") + "</svg>";
  293. };
  294. const pIds = async (reverse) => {
  295. const data = await decode(painterSvg(reverse), w, h);
  296. const ids = new Int32Array(w * h);
  297. for (let i = 0; i < w * h; i++) ids[i] = data[i * 4] + data[i * 4 + 1] * 256 - 1;
  298. return ids;
  299. };
  300. const nameOf = (id) => (id >= STATIC ? "static layer " + (id - STATIC) : id < 0 ? "empty" : V.parts[id].name);
  301. const joint = (a, b) => {
  302. const m = /^(.*):(\d+)$/;
  303. const x = a.match(m);
  304. const y = b.match(m);
  305. return Boolean(x && y && x[1] === y[1] && Math.abs(Number(x[2]) - Number(y[2])) <= 1);
  306. };
  307. async function check(state, { reverse = false } = {}) {
  308. setState(state);
  309. const Z = zIds();
  310. const P = await pIds(reverse);
  311. const tally = new Map();
  312. const interior = (ids, i, x, y) => {
  313. const v = ids[i];
  314. for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) { const xx = x + dx; const yy = y + dy; if (xx < 0 || yy < 0 || xx >= w || yy >= h || ids[yy * w + xx] !== v) return false; }
  315. return true;
  316. };
  317. let total = 0;
  318. for (let y = 1; y < h - 1; y++)
  319. for (let x = 1; x < w - 1; x++) {
  320. const i = y * w + x;
  321. const p = P[i];
  322. const z = Z[i];
  323. if (p === z || p < 0 || z < 0) continue;
  324. if (!interior(P, i, x, y) || !interior(Z, i, x, y)) continue;
  325. const key = p + "|" + z;
  326. tally.set(key, (tally.get(key) || 0) + 1);
  327. total++;
  328. }
  329. const live = [];
  330. const layers = [];
  331. for (const [key, px] of tally) {
  332. const [p, z] = key.split("|").map(Number);
  333. const a = nameOf(p);
  334. const b = nameOf(z);
  335. if (p >= STATIC || z >= STATIC) layers.push({ painter: a, truth: b, px });
  336. else if (!joint(a, b)) live.push({ painter: a, truth: b, px });
  337. }
  338. live.sort((x, y) => y.px - x.px);
  339. layers.sort((x, y) => y.px - x.px);
  340. return { total, live, layers, stats: C.stats() };
  341. }
  342. async function footprint(state, name) {
  343. setState(state);
  344. const index = V.parts.findIndex((part) => part.name === name);
  345. const Z = zIds();
  346. const P = await pIds(false);
  347. const boxOf = (ids) => {
  348. let n = 0, x0 = w, y0 = h, x1 = -1, y1 = -1;
  349. for (let i = 0; i < ids.length; i++) if (ids[i] === index) { n++; const x = i % w, y = (i / w) | 0; x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }
  350. return { px: n, box: n ? [x0 / SCALE, y0 / SCALE, x1 / SCALE, y1 / SCALE] : null };
  351. };
  352. return { painter: boxOf(P), truth: boxOf(Z) };
  353. }
  354. window.__tc.order = { check, footprint };
  355. return { parts: parts.length, statics: statics.length, w, h };
  356. })()`;
  357. const POPS = String.raw`(() => {
  358. const { stage, svgs, W, H, css, theme, setState, decode } = window.__tc;
  359. const SCALE = 2;
  360. const w = W * SCALE;
  361. const h = H * SCALE;
  362. let hidden = null;
  363. const svgString = () => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' + W + " " + H + '" width="' + w + '" height="' + h + '" class="iso iso-svg" data-theme="' + theme + '" style="--anatomy-paper:var(--anatomy-card)"><style>' + css + '</style><rect width="100%" height="100%" style="fill:var(--anatomy-card)"/>' + svgs.map((s) => '<g class="' + (s.getAttribute("class") || "") + '">' + s.innerHTML + "</g>").join("") + "</svg>";
  364. async function render(state, hide = null) {
  365. setState(state);
  366. if (hide !== null) {
  367. hidden = stage.querySelector('[data-p="' + hide + '"]');
  368. if (hidden) hidden.setAttribute("display", "none");
  369. }
  370. const data = await decode(svgString(), w, h);
  371. if (hidden) {
  372. hidden.removeAttribute("display");
  373. hidden = null;
  374. }
  375. const lum = new Float32Array(w * h);
  376. for (let i = 0; i < w * h; i++) lum[i] = 0.2126 * data[i * 4] + 0.7152 * data[i * 4 + 1] + 0.0722 * data[i * 4 + 2];
  377. return lum;
  378. }
  379. const erode = (mask) => {
  380. const out = new Uint8Array(w * h);
  381. for (let y = 1; y < h - 1; y++)
  382. for (let x = 1; x < w - 1; x++) {
  383. const i = y * w + x;
  384. if (!mask[i]) continue;
  385. let all = 1;
  386. for (let dy = -1; dy <= 1 && all; dy++) for (let dx = -1; dx <= 1; dx++) if (!mask[i + dy * w + dx]) { all = 0; break; }
  387. out[i] = all;
  388. }
  389. return out;
  390. };
  391. const regionOf = (mask) => {
  392. let n = 0;
  393. let x0 = w, y0 = h, x1 = -1, y1 = -1;
  394. for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (mask[y * w + x]) { n++; x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }
  395. return { n, box: n ? [x0 / SCALE, y0 / SCALE, x1 / SCALE, y1 / SCALE].map((v) => Math.round(v * 10) / 10) : null };
  396. };
  397. async function first(a, b, hide = null) {
  398. const A = await render(a);
  399. const B = await render(b, hide);
  400. let mask = new Uint8Array(w * h);
  401. for (let i = 0; i < w * h; i++) if (Math.abs(A[i] - B[i]) >= 5) mask[i] = 1;
  402. mask = erode(erode(mask));
  403. return regionOf(mask);
  404. }
  405. let cache = null;
  406. async function second(a, b, c) {
  407. const A = cache && cache.x === a ? cache.lum : await render(a);
  408. const B = cache && cache.y === b ? cache.mid : await render(b);
  409. const Cl = await render(c);
  410. cache = { x: b, lum: B, y: c, mid: Cl };
  411. let mask = new Uint8Array(w * h);
  412. for (let y = 1; y < h - 1; y++)
  413. for (let x = 1; x < w - 1; x++) {
  414. const i = y * w + x;
  415. const e = Math.abs(2 * B[i] - A[i] - Cl[i]);
  416. if (e <= 6) continue;
  417. let flat = true;
  418. for (let dy = -1; dy <= 1 && flat; dy++) for (let dx = -1; dx <= 1; dx++) if (Math.abs(B[i + dy * w + dx] - B[i]) > 4) { flat = false; break; }
  419. if (e > 56 || flat) mask[i] = 1;
  420. }
  421. mask = erode(mask);
  422. const region = regionOf(mask);
  423. if (window.__tcDump && region.n >= 6 && !window.__tcDumped) {
  424. window.__tcDumped = true;
  425. const png = (lum, scaleBy = 1) => {
  426. const canvas = Object.assign(document.createElement("canvas"), { width: w, height: h });
  427. const ctx = canvas.getContext("2d");
  428. const img = ctx.createImageData(w, h);
  429. for (let i = 0; i < w * h; i++) {
  430. const v = Math.max(0, Math.min(255, lum[i] * scaleBy));
  431. img.data[i * 4] = img.data[i * 4 + 1] = img.data[i * 4 + 2] = v;
  432. img.data[i * 4 + 3] = 255;
  433. }
  434. ctx.putImageData(img, 0, 0);
  435. return canvas.toDataURL("image/png").split(",")[1];
  436. };
  437. const diff = new Float32Array(w * h);
  438. for (let i = 0; i < w * h; i++) diff[i] = Math.abs(2 * B[i] - A[i] - Cl[i]);
  439. window.__tcDumped = { a: png(A), b: png(B), c: png(Cl), e: png(diff, 4) };
  440. }
  441. return region;
  442. }
  443. window.__tc.pops = { first, second, render };
  444. return { w, h };
  445. })()`;
  446. const PERF = String.raw`(async (frames, step, group) => {
  447. const { C, stage } = window.__tc;
  448. const name = group || C.scene().groups.find((g) => g.kind === "turn")?.name;
  449. const base = C.values[name] || 0;
  450. const ms = [];
  451. const writes = [];
  452. const moved = [];
  453. const times = [];
  454. await new Promise((done) => {
  455. let i = 0;
  456. const tick = (now) => {
  457. times.push(now);
  458. const s = C.set({ [name]: base + i * step });
  459. ms.push(s.ms);
  460. writes.push(s.writes);
  461. moved.push(s.moved);
  462. i++;
  463. if (i < frames) requestAnimationFrame(tick);
  464. else done();
  465. };
  466. requestAnimationFrame(tick);
  467. });
  468. const gaps = times.slice(1).map((t, i) => t - times[i]).sort((a, b) => a - b);
  469. const sorted = (list) => list.slice().sort((a, b) => a - b);
  470. const median = (list) => sorted(list)[Math.floor(list.length / 2)];
  471. const p95 = (list) => sorted(list)[Math.floor(list.length * 0.95)];
  472. const live = [...stage.querySelectorAll("svg[data-live] *")].length;
  473. return { frames, setMedian: median(ms), setP95: p95(ms), writes: median(writes), moved: median(moved), gapMedian: median(gaps), gapP95: p95(gaps), live };
  474. })`;
  475. async function main() {
  476. const argv = process.argv.slice(2);
  477. if (!argv.length || argv.includes("--help") || argv.includes("-h")) {
  478. usage();
  479. process.exit(argv.length ? 0 : 1);
  480. }
  481. const value = (flag, fallback) => {
  482. const at = argv.indexOf(flag);
  483. return at >= 0 ? argv[at + 1] : fallback;
  484. };
  485. const target = argv[0];
  486. let failed = 0;
  487. if (target.endsWith(".mjs")) {
  488. const F = await import("./turn-fidelity.mjs");
  489. const { T, P } = await import(pathToFileURL(resolve(target)).href);
  490. const angles = (value("--angles", "") || Array.from({ length: 12 }, (_, i) => 7 + i * 30).join(",")).split(",").map(Number);
  491. const plant = T.parts.find((part) => part.kind === "prism" && part.group && part.group.kind === "turn");
  492. if (plant) {
  493. const control = F.identity(T, P, angles.slice(0, 2), { plant: plant.name });
  494. console.log(`control (${plant.name} drawn 2° off): ${control.pass ? "did not fail: the check is broken" : "fails as it should"}`);
  495. if (control.pass) failed++;
  496. }
  497. for (const [name, run] of [["prisms", F.identity], ["rounds", F.rounds], ["tubes", F.tubes]]) {
  498. const result = run(T, P, angles);
  499. console.log(result.text);
  500. for (const line of result.worst) console.log(` ${line}`);
  501. if (!result.pass) {
  502. console.log(`${name} FAILED`);
  503. failed++;
  504. }
  505. }
  506. console.log(failed ? `fidelity failed: ${failed}` : "fidelity passed");
  507. process.exit(failed ? 1 : 0);
  508. }
  509. const options = { width: Number(value("--width", 1440)), height: Number(value("--height", 1100)), scale: Number(value("--scale", argv.includes("--perf") ? (Number(value("--width", 1440)) < 600 ? 3 : 2) : 1)), throttle: Number(value("--throttle", 1)), noWebgl: argv.includes("--no-webgl") };
  510. const step = Number(value("--step", 1));
  511. const out = value("--out", null);
  512. const statesFile = value("--states", null);
  513. const states = statesFile ? JSON.parse(readFileSync(statesFile, "utf8")) : null;
  514. const page = await browser(target, options);
  515. const labelOf = (state, index) => (typeof state === "number" ? `${state.toFixed(3)}°` : `state ${index}`);
  516. try {
  517. const info = await page.evaluate(HELPERS);
  518. console.log(`page ${info.W}×${info.H} · live layers ${info.layers.filter(Boolean).join(", ")} · theme ${info.theme}`);
  519. await page.evaluate(`window.__isoTurn.set(0) && 0`);
  520. const sweep = states ?? Array.from({ length: Math.round(360 / step) }, (_, i) => i * step);
  521. if (argv.includes("--order")) {
  522. const has = await page.evaluate("Boolean(window.__isoVerify)");
  523. if (!has) {
  524. console.log("order: this page has no window.__isoVerify; build it with --verify");
  525. failed++;
  526. } else {
  527. const z = await page.evaluate(ZBUFFER);
  528. console.log(`order: ${z.parts} live parts and ${z.statics} static items meshed, z-buffer ${z.w}×${z.h}`);
  529. let control = Infinity;
  530. for (const angle of [0, 90, 180, 270]) {
  531. const r = await page.evaluate(`window.__tc.order.check(${angle}, { reverse: true }).then((r) => r.live.reduce((s, p) => s + p.px, 0))`);
  532. control = Math.min(control, r);
  533. }
  534. console.log(`order control (each live layer reversed at 0, 90, 180, 270): least ${control} mismatched px ${control >= 1000 ? "· fails as it should" : "· did not fail: the check is broken"}`);
  535. if (control < 1000) failed++;
  536. const probe = value("--part", null);
  537. if (probe) for (const state of sweep.slice(0, 12)) console.log(` ${probe} at ${JSON.stringify(state)}: ${JSON.stringify(await page.evaluate(`window.__tc.order.footprint(${JSON.stringify(state)}, ${JSON.stringify(probe)})`))}`);
  538. let bad = 0;
  539. const layerNotes = new Map();
  540. let worst = 0;
  541. for (let index = 0; index < sweep.length; index++) {
  542. const state = sweep[index];
  543. const r = await page.evaluate(`window.__tc.order.check(${JSON.stringify(state)})`);
  544. const errors = r.live.filter((p) => p.px >= 4);
  545. worst = Math.max(worst, ...r.live.map((p) => p.px), 0);
  546. if (errors.length) {
  547. bad++;
  548. if (bad <= 30) console.log(` ${labelOf(state, index)}: ${errors.map((e) => `${e.painter} over ${e.truth} ${e.px} px`).join(" · ")}${r.stats.forced ? ` · forced ${r.stats.forced}` : ""}`);
  549. }
  550. for (const l of r.layers) if (l.px >= 16) layerNotes.set(`${l.painter} / ${l.truth}`, Math.max(layerNotes.get(`${l.painter} / ${l.truth}`) ?? 0, l.px));
  551. }
  552. console.log(`order: ${sweep.length} states · ${bad} with a live pair drawn out of order (4+ interior px at 2x) · worst live pair ${worst} px`);
  553. if (layerNotes.size) console.log(` static × live (recorded static shapes are stand-ins; the layer proofs own these): ${[...layerNotes].slice(0, 8).map(([k, v]) => `${k} ${v}px`).join(" · ")}`);
  554. if (bad) failed++;
  555. }
  556. }
  557. if (argv.includes("--pops")) {
  558. await page.evaluate(POPS);
  559. if (out) await page.evaluate("window.__tcDump = true");
  560. const plantPart = await page.evaluate(`(() => { const svgs = [...document.querySelectorAll("svg[data-live]")]; const parts = [...svgs[svgs.length - 1].querySelectorAll("[data-p]")]; let best = null; let area = 0; for (const el of parts) { const b = el.getBBox(); if (b.width * b.height > area) { area = b.width * b.height; best = el; } } return best ? Number(best.dataset.p) : null; })()`);
  561. const plantAt = typeof sweep[0] === "number" ? 37 : sweep[0];
  562. const control = await page.evaluate(`window.__tc.pops.first(${JSON.stringify(plantAt)}, ${JSON.stringify(typeof plantAt === "number" ? plantAt + 0.02 : plantAt)}, ${plantPart})`);
  563. console.log(`pops control (part ${plantPart} hidden for one frame): ${control.n ? `${control.n} px flagged · fails as it should` : "nothing flagged: the check is broken"}`);
  564. if (!control.n) failed++;
  565. let firstBad = 0;
  566. const firstStates = states ?? Array.from({ length: Math.round(360 / step) }, (_, i) => i * step);
  567. for (let index = 0; index < firstStates.length; index++) {
  568. const a = firstStates[index];
  569. const b = typeof a === "number" ? a + 0.02 : firstStates[index + 1];
  570. if (b === undefined) break;
  571. const r = await page.evaluate(`window.__tc.pops.first(${JSON.stringify(a)}, ${JSON.stringify(b)})`);
  572. if (r.n) {
  573. firstBad++;
  574. if (firstBad <= 20) console.log(` first difference ${labelOf(a, index)}: ${r.n} px survive two erosions in ${r.box.join(",")}`);
  575. }
  576. }
  577. console.log(`pops, first difference: ${firstStates.length} steps · ${firstBad} with a surviving region`);
  578. if (firstBad) failed++;
  579. if (!states) {
  580. let cores = 0;
  581. const small = [];
  582. const fine = Number(value("--fine", 0.1));
  583. for (let x = 0; x + 2 * fine <= 360 + 1e-9; x += fine) {
  584. const r = await page.evaluate(`window.__tc.pops.second(${x.toFixed(4)}, ${(x + fine).toFixed(4)}, ${(x + 2 * fine).toFixed(4)})`);
  585. if (r.n >= 6) {
  586. cores++;
  587. if (cores <= 20) console.log(` second difference at ${(x + fine).toFixed(2)}°: core of ${r.n} px in ${r.box.join(",")}`);
  588. } else if (r.n) small.push(`${(x + fine).toFixed(2)}° ${r.n} px in ${r.box.join(",")}`);
  589. }
  590. console.log(`pops, second difference at ${fine}° over a full turn: ${cores} cores of 6+ px · ${small.length} small cores to read${small.length ? `: ${small.slice(0, 12).join(" · ")}` : ""}`);
  591. const dumped = out ? await page.evaluate("window.__tcDumped && typeof window.__tcDumped === 'object' ? window.__tcDumped : null") : null;
  592. if (dumped) {
  593. mkdirSync(out, { recursive: true });
  594. for (const [key, data] of Object.entries(dumped)) writeFileSync(join(out, `pops-core-${key}.png`), Buffer.from(data, "base64"));
  595. console.log(` first core dumped to ${out}/pops-core-{a,b,c,e}.png`);
  596. }
  597. if (cores) failed++;
  598. }
  599. }
  600. if (argv.includes("--lines")) {
  601. const angles = Array.from({ length: 24 }, (_, i) => i * 15);
  602. const planted = await page.evaluate(`(() => { window.__isoTurn.set(0); const part = document.querySelector("svg[data-live] [data-p]"); const el = document.createElementNS("http://www.w3.org/2000/svg", "path"); el.setAttribute("class", "iso-line"); el.setAttribute("data-tone", "lo"); el.setAttribute("d", "M5 5L25 9"); el.setAttribute("data-plant", ""); part.appendChild(el); const r = (${LINE_ENDS})({ select: null, show: false }); el.remove(); return r ? r.problems.length : -1; })()`);
  603. console.log(`lines control (a planted floating line): ${planted > 0 ? "fails as it should" : "nothing flagged: the check is broken"}`);
  604. if (!(planted > 0)) failed++;
  605. let bad = 0;
  606. for (const angle of angles) {
  607. const r = await page.evaluate(`(() => { window.__isoTurn.set(${angle}); const r = (${LINE_ENDS})({ select: null, show: false }); return r ? { n: r.problems.length, list: r.problems.slice(0, 4).map((p) => p.what + " " + p.end + " " + p.gap.toFixed(2) + " px at " + p.at.join(",")) } : null; })()`);
  608. if (r && r.n) {
  609. bad += r.n;
  610. console.log(` ${angle}°: ${r.n} floating ends: ${r.list.join(" · ")}`);
  611. }
  612. }
  613. console.log(`lines: ${angles.length} angles · ${bad} floating ends`);
  614. if (bad) failed++;
  615. }
  616. if (argv.includes("--perf")) {
  617. await page.send("Performance.enable");
  618. const metrics = async () => Object.fromEntries((await page.send("Performance.getMetrics")).result.metrics.map((m) => [m.name, m.value]));
  619. const runs = [];
  620. for (let r = 0; r < 3; r++) {
  621. const before = await metrics();
  622. const result = await page.evaluate(`(${PERF})(240, 1.1, null)`);
  623. const after = await metrics();
  624. const per = (key) => ((after[key] - before[key]) * 1000) / result.frames;
  625. runs.push({ ...result, task: per("TaskDuration"), script: per("ScriptDuration"), style: per("RecalcStyleDuration"), layout: per("LayoutDuration") });
  626. }
  627. const med = (key) => runs.map((r) => r[key]).sort((a, b) => a - b)[1];
  628. console.log(`perf at ${options.width} px, DPR ${options.scale}, ${options.throttle}× CPU, median of 3 runs of 240 frames at 1.1°: set() ${med("setMedian").toFixed(2)} ms (p95 ${med("setP95").toFixed(2)}) · task ${med("task").toFixed(2)} ms · script ${med("script").toFixed(2)} ms · style ${med("style").toFixed(2)} ms · layout ${med("layout").toFixed(2)} ms per frame · frame interval ${med("gapMedian").toFixed(1)} ms (p95 ${med("gapP95").toFixed(1)}) · ${runs[0].live} live elements · ${med("writes")} writes and ${med("moved")} moves per frame`);
  629. if (out) {
  630. mkdirSync(out, { recursive: true });
  631. writeFileSync(join(out, `perf-${options.width}-${options.throttle}x.json`), JSON.stringify(runs, null, 1));
  632. }
  633. }
  634. console.log(page.problems.length ? page.problems.join("\n") : "console: clean");
  635. if (page.problems.length) failed++;
  636. } catch (error) {
  637. console.error(error);
  638. failed++;
  639. } finally {
  640. page.close();
  641. }
  642. console.log(failed ? `turn check failed: ${failed}` : "turn check passed");
  643. process.exit(failed ? 1 : 0);
  644. }
  645. if (typeof WebSocket === "undefined" && !process.execArgv.includes("--experimental-websocket")) {
  646. const child = spawn(process.execPath, ["--experimental-websocket", ...process.argv.slice(1)], { stdio: "inherit" });
  647. child.on("exit", (code) => process.exit(code ?? 1));
  648. } else {
  649. await main();
  650. }