diff --git a/src/app.ts b/src/app.ts index a5f94c6..ab23bdb 100644 --- a/src/app.ts +++ b/src/app.ts @@ -148,12 +148,29 @@ export class App implements AppContext { document.body.append(busy); busy.querySelector(".busy-stop")!.addEventListener("click", () => this.stopWork()); let busyTimer = 0; + let busyWatch = 0; this.kernel.onBusy = (on) => { clearTimeout(busyTimer); + clearInterval(busyWatch); // Only for waits you would notice (not every quick preview while dragging). - if (on) busyTimer = window.setTimeout(() => (busy.hidden = false), 300); + if (on) + busyTimer = window.setTimeout(() => { + if (!this.kernel.busy) return; + busy.hidden = false; + // Shown only while there is work: looked at again as it stands, so it can never stay up over nothing + // (asked for: "sometimes the working icon still is showing even if there's nothing to work on"). + busyWatch = window.setInterval(() => { + if (this.kernel.busy) return; + busy.hidden = true; + clearInterval(busyWatch); + }, 400); + }, 300); else busy.hidden = true; }; + this.kernel.onLost = () => { + this.ui.toast("The geometry engine stopped and was started again - the last change may need doing again", "error"); + void this.regenerate(); + }; const cube = new ViewCube(this.view); document.getElementById("viewcube-host")!.append(cube.el); // The orbit centre button sits at the cube's bottom left (Views at its bottom right). diff --git a/src/doc/store.ts b/src/doc/store.ts index e59331e..5e4a389 100644 --- a/src/doc/store.ts +++ b/src/doc/store.ts @@ -355,7 +355,13 @@ export class DocStore { this.saveTimer = window.setTimeout(() => { const v = this.edits; const text = JSON.stringify(this.doc); - void idbSet("autosave", text).then(() => this.wrote(v)); + // (A write that failed is tried again: left, the name's mark said "Saving…" from then on.) + const write = (tries: number): void => + void idbSet("autosave", text).then( + () => this.wrote(v), + () => tries > 0 && v === this.edits && window.setTimeout(() => write(tries - 1), 2000), + ); + write(3); this.onSaved?.(text); // The undo steps less eagerly: they're bigger, and only matter after a reload. clearTimeout(this.historyTimer); diff --git a/src/doc/types.ts b/src/doc/types.ts index 183b132..3a9b3fd 100644 --- a/src/doc/types.ts +++ b/src/doc/types.ts @@ -411,6 +411,11 @@ export interface ImportFeature extends FeatureBase { fileName: string; /** Base64 of the file. */ data: string; + /** + * Each solid in the file is a body of its own (the first has this step's id, the others ":1", ":2"...). + * Missing (files put in before this): all of them one body, as they were - what was built on that body stays. + */ + apart?: boolean; } /** A reference image placed on a plane (for tracing). */ diff --git a/src/io/insert.ts b/src/io/insert.ts index 25db9cd..9b8a8b9 100644 --- a/src/io/insert.ts +++ b/src/io/insert.ts @@ -81,7 +81,7 @@ export async function insertFile(app: AppContext): Promise { const why = unreadable(bytes, format); if (why) return app.ui.toast(`Could not insert ${file.name}: ${why}`, "error"); app.ui.setStatus(`Importing ${file.name}…`); - app.store.add({ ...app.store.newIdentity("import"), type: "import", format, fileName: file.name, data: toBase64(bytes) }); + app.store.add({ ...app.store.newIdentity("import"), type: "import", format, fileName: file.name, data: toBase64(bytes), apart: true }); app.ui.setStatus(null); } catch (err) { app.ui.setStatus(null); diff --git a/src/kernel/client.ts b/src/kernel/client.ts index a6c3424..ed5f4bd 100644 --- a/src/kernel/client.ts +++ b/src/kernel/client.ts @@ -66,6 +66,15 @@ export class KernelClient { this.meshes = new Map(); this.worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" }); this.worker.onmessage = this.handler; + // The engine died without an answer (out of memory, a fault outside any step): what waits on it would wait for + // ever, and "Working…" with it. Everything waiting ends, and a fresh engine is started. + const worker = this.worker; + worker.onerror = (e) => { + if (worker !== this.worker) return; + console.error("The geometry engine stopped:", e.message); + this.stop(); + this.onLost?.(); + }; this.ready = this.call({ type: "init" }).then((r) => { if (r.type === "error") throw new Error(r.message); }); @@ -141,6 +150,12 @@ export class KernelClient { /** Told when the kernel starts and stops being busy (to show a busy indicator). */ onBusy: ((busy: boolean) => void) | null = null; + /** Told when the engine died and was started again (what was being made is not made). */ + onLost: (() => void) | null = null; + /** Is anything being worked on, or waiting to be? (What the busy indicator is checked against.) */ + get busy(): boolean { + return this.pending.size > 0 || this.regenRunning || !!this.regenQueued; + } private call(msg: Request): Promise { const id = this.nextId++; diff --git a/src/kernel/engine.ts b/src/kernel/engine.ts index e159325..f032552 100644 --- a/src/kernel/engine.ts +++ b/src/kernel/engine.ts @@ -1695,6 +1695,14 @@ async function apply(f: Feature, ctx: Ctx): Promise { if (isEmpty(shape)) throw new Error("The file contains no solid geometry"); importCache.set(f.data, shape); } + // A file of several solids (an assembly; this app's own STEP of two bodies): each a body of its own, to pick, + // hide, move and cut by itself. (They came in as one body of several pieces: the two bodies of a project + // saved as STEP and opened again were one, that nothing could take apart.) + const solids = f.apart && f.format === "step" ? subShapes(shape, "SOLID") : []; + if (solids.length > 1) { + solids.forEach((s, i) => bodies.set(i ? `${f.id}:${i}` : f.id, cast(s) as Shape3D)); + return; + } bodies.set(f.id, shape); return; } @@ -5418,7 +5426,9 @@ function bodyNames(features: Feature[], ids: string[], numbers: Map x.id === baseId(id)); if (f?.type === "import") { - out.set(id, f.fileName); + // (One of several solids of a file: the file's name and which.) + const part = /:(\d+)$/.exec(id); + out.set(id, part ? `${f.fileName} (${Number(part[1]) + 1})` : f.fileName); continue; } // A copy of a surface is a surface too (its id holds the original's). diff --git a/src/tools/select.ts b/src/tools/select.ts index 907ec4f..31d7e41 100644 --- a/src/tools/select.ts +++ b/src/tools/select.ts @@ -530,8 +530,12 @@ export class SelectTool implements Tool { // (Picks of different kinds: no one handle is for all of them.) if (!first || sel.some((x) => x.kind !== first.kind)) return; // The most likely next step gets a handle. + // Several picked: the handle is on the one picked last - where the hand and the eye are (asked for: "I want the + // arrow / fillet or chamfer circle ... to appear on the last element I selected. Now it stays on the first one + // and I have to navigate back to it"). The tool started from it works from there too. + const lastFirst = sel.length > 1 ? [sel[sel.length - 1], ...sel.slice(0, -1)] : sel; if (first.kind === "profile") { - const src = sourcesOf(this.app, sel)[0]; + const src = sourcesOf(this.app, lastFirst)[0]; if (src) this.showHandle(sourceFrame(this.app, src), "arrow", () => new ExtrudeOp(this.app, src)); } else if (first.kind === "face" && sel.length === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type)) { // Flat and round faces: drag the arrow to offset (round faces change radius). @@ -572,12 +576,13 @@ export class SelectTool implements Tool { this.copyToggle = new CopyToggle(this.app.view, () => g.origin); } } else if (first.kind === "edge") { - const e = this.edgeRefs()[0]; + const all = this.edgeRefs(); + const e = all[all.length - 1]; // An edge's most likely next step is rounding it: the fillet's dot is // ready to drag, and a number typed is the radius. Moving a straight // edge (its faces tilt to follow) is Move/Rotate Edge (M) in the list. // (A freeform's edges get neither: its shape comes from the cage.) - if (e && !this.freeformOf(first.body)) this.showHandle({ base: e.mid, normal: e.dir }, "dot", () => new EdgeOp(this.app, "fillet", this.edgeRefs()).grabFromEdge()); + if (e && !this.freeformOf(first.body)) this.showHandle({ base: e.mid, normal: e.dir }, "dot", () => new EdgeOp(this.app, "fillet", [e, ...all.slice(0, -1)]).grabFromEdge()); } } @@ -873,7 +878,11 @@ export class SelectTool implements Tool { // view) and its list stays open - the selection's edge numbers then point at the preview's // edges, and "Drag / type" picked two other edges (rounding the valve's creases failed). const picked = this.edgeRefs(); - const refs = () => picked.map((r) => ({ ...r })); + // (The edge picked last first: the tool's dot and its size are at that one.) + const refs = () => { + const all = picked.map((r) => ({ ...r })); + return all.length > 1 ? [all[all.length - 1], ...all.slice(0, -1)] : all; + }; const ref = picked[0]; // With variables defined, Fillet/Chamfer open a list: a free size, or one of the variables. const vars = app.store.doc.variables ?? []; diff --git a/tests/exports.test.ts b/tests/exports.test.ts new file mode 100644 index 0000000..ba06dce --- /dev/null +++ b/tests/exports.test.ts @@ -0,0 +1,159 @@ +// Run: npx tsx tests/exports.test.ts +// Every way a model leaves the app, made from one project (the flange built by hand, with a small block beside it) +// and read back: is the file what its format says, is it the same part, the same size, closed, in millimetres? +// STL - STEP - 3MF - GLB - one body of several - the project file itself. +// (A sketch as DXF and SVG, and a drawing's sheet: dxf, svgexport and drawing tests.) +import { readFileSync } from "node:fs"; +import { after, block, bodies, check, done, near, volume } from "./kit"; +import { parseProject } from "../src/doc/store"; +import { resolveDoc } from "../src/doc/params"; +import { exportBodies } from "../src/kernel/engine"; +import { glb, read3mf, unzip } from "../src/io/formats"; +import { exportThreeMF } from "../src/io/threemf"; +import type { Feature, ProjectDoc } from "../src/doc/types"; +import type { Shape3D } from "replicad"; + +const doc = JSON.parse(readFileSync(new URL("./fixtures/flange-variables.json", import.meta.url), "utf8")) as ProjectDoc; +resolveDoc(doc); +const features = [...(doc.features as Feature[]), ...block("Block", 20, 10, 5, [200, 0, 0])]; +const { errors } = await after(features); +const all = [...bodies().entries()] as [string, Shape3D][]; +const flangeId = all.find(([id]) => id !== "Block")![0]; +const V = { flange: volume(bodies().get(flangeId) as Shape3D), block: volume(bodies().get("Block") as Shape3D) }; +check("the model: a flange and a block, no errors", !errors.length && all.length === 2 && near(V.block, 1000, 1e-6) && near(V.flange, 429515.41, 0.05), `${all.length} bodies, ${V.flange.toFixed(2)} + ${V.block}`); + +// ---- what a mesh is worth: its volume, its box, whether it is closed +type Mesh = { p: number[]; t: number[] }; +function measure(m: Mesh) { + let vol = 0; + const lo = [Infinity, Infinity, Infinity]; + const hi = [-Infinity, -Infinity, -Infinity]; + const key = (i: number) => `${m.p[3 * i].toFixed(4)},${m.p[3 * i + 1].toFixed(4)},${m.p[3 * i + 2].toFixed(4)}`; + const edges = new Map(); + for (let k = 0; k < m.t.length; k += 3) { + const [a, b, c] = [m.t[k], m.t[k + 1], m.t[k + 2]]; + const P = (i: number) => [m.p[3 * i], m.p[3 * i + 1], m.p[3 * i + 2]]; + const [A, B, C] = [P(a), P(b), P(c)]; + vol += (A[0] * (B[1] * C[2] - B[2] * C[1]) - A[1] * (B[0] * C[2] - B[2] * C[0]) + A[2] * (B[0] * C[1] - B[1] * C[0])) / 6; + for (const q of [A, B, C]) for (let j = 0; j < 3; j++) (lo[j] = Math.min(lo[j], q[j])), (hi[j] = Math.max(hi[j], q[j])); + // Each side of each triangle, with its direction: a closed skin has every side once each way. + for (const [u, v] of [[a, b], [b, c], [c, a]]) { + const [ku, kv] = [key(u), key(v)]; + if (ku === kv) continue; + edges.set(`${ku}>${kv}`, (edges.get(`${ku}>${kv}`) ?? 0) + 1); + } + } + let open = 0; + for (const [e, n] of edges) { + const [u, v] = e.split(">"); + if ((edges.get(`${v}>${u}`) ?? 0) !== n) open++; + } + return { vol, lo, hi, open, tris: m.t.length / 3 }; +} +// (A mesh of flat facets inside a round body holds a little less than the body: within 0.01 mm of it everywhere.) +const sameVolume = (got: number, want: number) => got <= want + 1e-3 && got > want * 0.998; + +// ---- STL +function readSTL(bytes: Uint8Array): Mesh { + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const n = dv.getUint32(80, true); + if (bytes.length !== 84 + n * 50) throw new Error(`an STL of ${n} triangles is ${84 + n * 50} bytes, not ${bytes.length}`); + const p: number[] = []; + const t: number[] = []; + for (let i = 0; i < n; i++) { + const o = 84 + i * 50; + for (let k = 0; k < 9; k++) p.push(dv.getFloat32(o + 12 + k * 4, true)); + t.push(i * 3, i * 3 + 1, i * 3 + 2); + } + return { p, t }; +} +const bytesOf = async (b: Blob) => new Uint8Array(await b.arrayBuffer()); +{ + const stl = measure(readSTL(await bytesOf(await exportBodies(features, "stl")))); + check("STL: a binary file of the right length, both bodies in it", stl.tris > 1000, `${stl.tris} triangles`); + check("STL: the model's volume (the two together)", sameVolume(stl.vol, V.flange + V.block), `${stl.vol.toFixed(1)} / ${(V.flange + V.block).toFixed(1)}`); + check("STL: closed all over (every side of every triangle met by its neighbour's)", stl.open === 0, `${stl.open} sides unmatched`); + check("STL: millimetres, where the model is (the flange 160 across, the block out at 200 to 220)", near(stl.lo[0], -80, 0.02) && near(stl.hi[0], 220, 1e-3) && near(stl.lo[2], 0, 1e-3) && near(stl.hi[2], 65, 1e-3), `${stl.lo.map((v) => v.toFixed(2))} .. ${stl.hi.map((v) => v.toFixed(2))}`); + const one = measure(readSTL(await bytesOf(await exportBodies(features, "stl", ["Block"])))); + check("STL of one chosen body: that body alone (the block: 12 triangles, 1,000 mm³)", one.tris === 12 && near(one.vol, 1000, 1e-3) && one.open === 0, `${one.tris} triangles, ${one.vol}`); +} + +// ---- STEP: read back in as a model, it is the same solids +{ + const blob = await exportBodies(features, "step"); + const text = new TextDecoder().decode(await bytesOf(blob)); + check("STEP: a STEP file, with both bodies named", text.startsWith("ISO-10303-21;") && /END-ISO-10303-21;\s*$/.test(text) && text.includes("'Body 1'") && text.includes("'Body 2'"), `${text.length} characters`); + check("STEP: in millimetres", /SI_UNIT\(\s*\.MILLI\.\s*,\s*\.METRE\.\s*\)/.test(text)); + const back: Feature = { id: "In", name: "Imported", type: "import", format: "step", fileName: "x.step", data: Buffer.from(text, "utf8").toString("base64"), apart: true } as Feature; + const r = await after([back]); + const got = [...bodies().values()].map((b) => volume(b as Shape3D)).sort((a, b) => a - b); + check("STEP read back in: two bodies again, the same solids, exact (round faces still round)", !r.errors.length && got.length === 2 && near(got[0], V.block, 1e-3) && near(got[1], V.flange, 0.05), `${got.map((v) => v.toFixed(2))} ${r.errors.join("; ")}`); + // (A file put in before bodies came in apart: one body of the two pieces, as it was.) + const old = await after([{ ...back, apart: undefined } as Feature]); + check(" a file put in before that: still one body of both pieces", !old.errors.length && bodies().size === 1 && near(volume([...bodies().values()][0] as Shape3D), V.flange + V.block, 0.05)); + const one = new TextDecoder().decode(await bytesOf(await exportBodies(features, "step", [flangeId]))); + const oneBack = await after([{ ...back, data: Buffer.from(one, "utf8").toString("base64") } as Feature]); + check("STEP of one chosen body: that body alone", !oneBack.errors.length && bodies().size === 1 && near(volume([...bodies().values()][0] as Shape3D), V.flange, 0.05) && one.length < text.length); +} + +// ---- 3MF: the meshes, and the exact model packed with them +{ + const meshes = JSON.parse(await (await exportBodies(features, "mesh")).text()) as { id: string; positions: number[]; indices: number[] }[]; + check("the print mesh of each body: closed, the body's volume", meshes.length === 2 && meshes.every((m) => { + const x = measure({ p: m.positions, t: m.indices }); + return x.open === 0 && sameVolume(x.vol, m.id === "Block" ? V.block : V.flange); + }), meshes.map((m) => `${m.id.slice(0, 8)} ${measure({ p: m.positions, t: m.indices }).vol.toFixed(1)}`).join(", ")); + const file = await bytesOf(await exportThreeMF(meshes.map((m) => ({ name: m.id === "Block" ? "Block" : "Flange", positions: new Float32Array(m.positions), indices: new Uint32Array(m.indices), color: m.id === "Block" ? "#ff8800" : undefined })), "Flange & ", await exportBodies(features, "step"))); + check("3MF: a ZIP (starts PK)", file[0] === 0x50 && file[1] === 0x4b); + const parts = await unzip(file); + const model = new TextDecoder().decode(parts.get("3D/3dmodel.model") ?? new Uint8Array()); + check("3MF: its parts are there (types, relations, the model, the STEP attached)", ["[Content_Types].xml", "_rels/.rels", "3D/3dmodel.model", "Attachments/model.step"].every((n) => parts.has(n)), [...parts.keys()].join(", ")); + check("3MF: millimetres, a title that is safe to read, two objects built", /unit="millimeter"/.test(model) && model.includes("Flange & <block>") && (model.match(/]*name="([^"]*)"[^>]*>([\s\S]*?)<\/object>/g)].map((m) => { + const p = [...m[2].matchAll(/ [+v[1], +v[2], +v[3]]); + const t = [...m[2].matchAll(/ [+v[1], +v[2], +v[3]]); + return { name: m[1], ...measure({ p, t }), max: Math.max(...t), count: p.length / 3 }; + }); + check("3MF: each object closed, its volume the body's, every corner it names there", objects.every((o) => o.open === 0 && o.max < o.count && sameVolume(o.vol, o.name === "Block" ? V.block : V.flange)), objects.map((o) => `${o.name} ${o.vol.toFixed(1)} (${o.tris} triangles, ${o.open} open)`).join(", ")); + check("3MF: the block's colour is in it", /displaycolor="#FF8800FF"/.test(model) && /name="Block" pid="1" pindex="0"/.test(model)); + const inside = await read3mf(file); + check("3MF opened again in the app: the exact model inside is what is read", inside.format === "step" && new TextDecoder().decode(inside.bytes).startsWith("ISO-10303-21;")); +} + +// ---- GLB +{ + const meshes = JSON.parse(await (await exportBodies(features, "mesh")).text()) as { id: string; positions: number[]; indices: number[] }[]; + const out = glb(meshes.map((m) => ({ name: m.id === "Block" ? "Block" : "Flange", positions: new Float32Array(m.positions), indices: new Uint32Array(m.indices), color: "#3d8bff", opacity: m.id === "Block" ? 0.5 : 1 })), "Flange"); + const dv = new DataView(out.buffer, out.byteOffset, out.byteLength); + const jsonLen = dv.getUint32(12, true); + const json = JSON.parse(new TextDecoder().decode(out.subarray(20, 20 + jsonLen))); + const binAt = 20 + jsonLen; + const binLen = dv.getUint32(binAt, true); + check("GLB: glTF 2, as long as it says, its two parts on four-byte bounds", dv.getUint32(0, true) === 0x46546c67 && dv.getUint32(4, true) === 2 && dv.getUint32(8, true) === out.length && dv.getUint32(16, true) === 0x4e4f534a && dv.getUint32(binAt + 4, true) === 0x004e4942 && jsonLen % 4 === 0 && binLen % 4 === 0 && binAt + 8 + binLen === out.length, `${out.length} bytes`); + check("GLB: two meshes named, under a root that makes Z up into Y up and millimetres into metres", json.meshes.length === 2 && json.nodes[0].scale.every((s: number) => s === 0.001) && near(json.nodes[0].rotation[0], -Math.SQRT1_2, 1e-9) && json.nodes.slice(1).map((n: any) => n.name).join() === "Flange,Block"); + // Its numbers read back out of the binary part. + const bin = out.subarray(binAt + 8, binAt + 8 + binLen); + const read = (acc: number) => { + const a = json.accessors[acc]; + const v = json.bufferViews[a.bufferView]; + const n = a.count * (a.type === "VEC3" ? 3 : 1); + const at = bin.byteOffset + v.byteOffset; + return a.componentType === 5126 ? Array.from(new Float32Array(bin.buffer.slice(at, at + n * 4))) : Array.from(new Uint32Array(bin.buffer.slice(at, at + n * 4))); + }; + const got = json.meshes.map((m: any) => ({ name: m.name, ...measure({ p: read(m.primitives[0].attributes.POSITION), t: read(m.primitives[0].indices) }), normals: read(m.primitives[0].attributes.NORMAL), acc: json.accessors[m.primitives[0].attributes.POSITION] })); + check("GLB: each mesh closed, its volume the body's, its box as the file says", got.every((g: any) => g.open === 0 && sameVolume(g.vol, g.name === "Block" ? V.block : V.flange) && g.lo.every((v: number, j: number) => near(v, g.acc.min[j], 1e-4)) && g.hi.every((v: number, j: number) => near(v, g.acc.max[j], 1e-4))), got.map((g: any) => `${g.name} ${g.vol.toFixed(1)}`).join(", ")); + check("GLB: a normal of length 1 at every corner", got.every((g: any) => g.normals.length === g.acc.count * 3 && g.normals.every((_: number, i: number) => i % 3 || near(Math.hypot(g.normals[i], g.normals[i + 1], g.normals[i + 2]), 1, 1e-4)))); + check("GLB: the see-through block says so", json.materials[1].alphaMode === "BLEND" && near(json.materials[1].pbrMetallicRoughness.baseColorFactor[3], 0.5, 1e-9) && json.materials[0].alphaMode === undefined); +} + +// ---- the project file +{ + const saved = JSON.stringify({ ...doc, features }); + const opened = parseProject(saved); + check("the project saved and opened: every step and variable as it was", JSON.stringify(opened.features) === JSON.stringify(features) && JSON.stringify(opened.variables) === JSON.stringify(doc.variables) && opened.units === doc.units); + const again = await after(opened.features as Feature[]); + const vols = [...bodies().values()].map((b) => volume(b as Shape3D)).sort((a, b) => a - b); + check(" and built again: the same two bodies", !again.errors.length && near(vols[0], V.block, 1e-6) && near(vols[1], V.flange, 1e-6)); +} +done();