Public: anyone can read this; the crew can change it.
An .stl file opens in the browser as a 3D model you can turn, with its size and triangle count #12995
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/12990-an-stl-file-opens-in-the-browser-as-a-3d → main 5 commits fork 1 thread · 1 unresolved
7 files
changed +165
−7
docs/features/README.md +1
| @@ -223,6 +223,7 @@ Read with the guide page [Your apps](../guide-your-apps.md). | ||
| 223 | 223 | ### Files in the browser |
| 224 | 224 | |
| 225 | 225 | - [](mesh-files.md) |
| 226 | - [](file-stl.md) | |
| 226 | 227 | - [](file-dxf.md) |
| 227 | 228 | - [](psd.md) |
| 228 | 229 | - [](file-har.md) |
docs/features/file-stl.md added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | # An .stl file as a 3D model | |
| 2 | ||
| 3 | An `.stl` file (binary or ASCII) opens on its blob page as a part you can turn, with its facts above it: | |
| 4 | **Format**, **File** size, **Triangles** and the **Box** (its size in the file's own units: an STL carries none, so it reads `20 × 20 × 20 units`, not millimetres). | |
| 5 | The first paint carries the triangle count and box, read by the server, so they show with JavaScript off. | |
| 6 | ||
| 7 | - `src/web/render/stl.ts` reads and checks the bytes (`readStl`); `mesh.ts` holds the shared parser; `model3d.ts` | |
| 8 | draws the frame; `model3d-client.ts` is the viewer script (the vendored three.js, loaded only by this page). | |
| 9 | - Turn it with the pointer (drag to orbit, wheel to zoom) or the arrow keys once the canvas has focus; Wireframe and | |
| 10 | Axes are buttons beside the facts. | |
| 11 | - The header and triangle count are checked against the byte length before any triangle is read. A truncated or | |
| 12 | damaged file, one with no triangles or a coordinate that is not a number, is refused with a sentence and Download. | |
| 13 | - Over 20 MB: refused with a sentence and never fetched; Download still streams it. | |
| 14 | - The server reads the whole file, up to 20 MB, for the first paint, so the facts show with JavaScript off at any size the page opens. | |
| 15 | - Try it: commit a `.stl` to a repository and open its file page. | |
| 16 | ||
| 17 | Pinned by `test/render-stl.test.ts` and `test/model3d.test.ts`. The viewer's neighbours: [](mesh-files.md). |
src/view/local.ts +7 −2
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | * `canRead`; what is left is shape. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { STL_LIMIT } from "../web/render/stl.ts"; | |
| 11 | 12 | import { pullProposalOf } from "../core/proposal_token.ts"; |
| 12 | 13 | import { mayView, sealedScope } from "../core/sealed.ts"; |
| 13 | 14 | import type { App } from "../app.ts"; |
| @@ -61,8 +62,12 @@ import type { | ||
| 61 | 62 | |
| 62 | 63 | /** The same ceiling the contents route uses; a page is a page. */ |
| 63 | 64 | const MAX_BLOB_BYTES = 5_000_000; |
| 64 | /** A sliced G-code file is read whole, up to the cap its renderer draws. */ | |
| 65 | const blobCeiling = (path: string): number => (/\.(gcode|gco)$/i.test(path) ? RENDER_CAP.gcode : MAX_BLOB_BYTES); | |
| 65 | /** | |
| 66 | * A sliced G-code file is read whole, up to the cap its renderer draws; an STL | |
| 67 | * up to the size its facts are read. | |
| 68 | */ | |
| 69 | const blobCeiling = (path: string): number => | |
| 70 | /\.(gcode|gco)$/i.test(path) ? RENDER_CAP.gcode : /\.stl$/i.test(path) ? STL_LIMIT : MAX_BLOB_BYTES; | |
| 66 | 71 | const COMMIT_PAGE = 50; |
| 67 | 72 | |
| 68 | 73 | export function localSource( |
src/web/render/model3d-client.ts +1 −1
| @@ -263,7 +263,7 @@ function mount(figure: Element): void { | ||
| 263 | 263 | |
| 264 | 264 | stats.textContent = ""; |
| 265 | 265 | fact("[data-triangles]", triangles.toLocaleString("en")); |
| 266 | fact("[data-box]", sizeText(box.size)); | |
| 266 | fact("[data-box]", format === "stl" ? sizeText(box.size, "units") : sizeText(box.size)); | |
| 267 | 267 | for (const button of tools.querySelectorAll("button[value]")) { |
| 268 | 268 | button.addEventListener("click", () => { |
| 269 | 269 | const on = button.getAttribute("aria-pressed") !== "true"; |
src/web/render/model3d.ts +17 −4
| @@ -24,6 +24,7 @@ import { html, type Html } from "../html.ts"; | ||
| 24 | 24 | import { btn, empty, fileSize } from "../ui.ts"; |
| 25 | 25 | import { indexedRows } from "./mesh.ts"; |
| 26 | 26 | import { indexedMesh } from "./model-facts.ts"; |
| 27 | import { readStl, STL_LIMIT, STL_TOO_BIG } from "./stl.ts"; | |
| 27 | 28 | import type { Rendered, RenderInput } from "./renderers.ts"; |
| 28 | 29 | |
| 29 | 30 | const log = createLog("web"); |
| @@ -49,11 +50,23 @@ export function model3d(input: RenderInput): Rendered { | ||
| 49 | 50 | value === undefined |
| 50 | 51 | ? html`<div data-${key} hidden><dt>${label}</dt><dd></dd></div>` |
| 51 | 52 | : html`<div data-${key}><dt>${label}</dt><dd>${value}</dd></div>`; |
| 53 | // An STL the page read has its facts in the first paint; one over 20 MB is | |
| 54 | // refused with a sentence and never fetched by the viewer. | |
| 55 | const format = formatOf(input.path); | |
| 56 | const stl = | |
| 57 | format === "stl" && input.size <= STL_LIMIT && input.body.length > 0 ? readStl(input.body) : undefined; | |
| 58 | const stlFacts = stl !== undefined && !("error" in stl) ? stl : undefined; | |
| 59 | const refused = format === "stl" && input.size > STL_LIMIT; | |
| 60 | const note = refused | |
| 61 | ? STL_TOO_BIG | |
| 62 | : stl !== undefined && "error" in stl | |
| 63 | ? stl.error | |
| 64 | : "Turning it needs JavaScript and WebGL; Download opens it elsewhere."; | |
| 52 | 65 | return { |
| 53 | 66 | lines: 0, |
| 54 | 67 | content: html`<figure |
| 55 | 68 | class="model3d" |
| 56 | data-src="${input.media}" | |
| 69 | ${refused ? html`` : html`data-src="${input.media}"`} | |
| 57 | 70 | data-format="${formatOf(input.path)}" |
| 58 | 71 | data-label="3D view of ${name}" |
| 59 | 72 | data-module="${model3dAssetPath()}" |
| @@ -64,8 +77,8 @@ export function model3d(input: RenderInput): Rendered { | ||
| 64 | 77 | <div><dt>File</dt><dd>${fileSize(input.size)}</dd></div> |
| 65 | 78 | ${row("vertices", "Vertices", rows?.vertices)} |
| 66 | 79 | ${row("faces", "Faces", rows?.faces)} |
| 67 | ${row("triangles", "Triangles", rows?.triangles)} | |
| 68 | ${row("box", "Box", rows?.box)} | |
| 80 | ${row("triangles", "Triangles", rows?.triangles ?? stlFacts?.triangles.toLocaleString("en"))} | |
| 81 | ${row("box", "Box", rows?.box ?? stlFacts?.size)} | |
| 69 | 82 | </dl> |
| 70 | 83 | <span class="muted" data-stats aria-live="polite"></span> |
| 71 | 84 | <span class="spacer"></span> |
| @@ -77,7 +90,7 @@ export function model3d(input: RenderInput): Rendered { | ||
| 77 | 90 | ${empty({ |
| 78 | 91 | icon: "file", |
| 79 | 92 | title: "A 3D model", |
| 80 | note: "Turning it needs JavaScript and WebGL; Download opens it elsewhere.", | |
| 93 | note, | |
| 81 | 94 | action: btn("Download", { href: input.download, variant: "primary", icon: "download" }), |
| 82 | 95 | })} |
| 83 | 96 | </div> |
src/web/render/stl.ts added +48
| @@ -0,0 +1,48 @@ | ||
| 1 | /** | |
| 2 | * An STL file read for its facts: plain bytes in, plain data out. It checks the | |
| 3 | * header and the triangle count against the byte length before reading a | |
| 4 | * triangle, so a loop is always bounded by a count the file's own length | |
| 5 | * backs. The mesh itself is read by `mesh.ts`, the one parser the | |
| 6 | * viewer shares. | |
| 7 | */ | |
| 8 | ||
| 9 | import { bounds, MeshError, parseStl, sizeText, type Bounds } from "./mesh.ts"; | |
| 10 | ||
| 11 | /** The largest STL read or drawn: 20 MB. */ | |
| 12 | export const STL_LIMIT = 20_000_000; | |
| 13 | ||
| 14 | export const STL_TOO_BIG = "This STL is over 20 MB, more than is read here; download it to open it elsewhere."; | |
| 15 | ||
| 16 | export interface StlFacts { | |
| 17 | readonly triangles: number; | |
| 18 | readonly box: Bounds; | |
| 19 | /** `20 × 20 × 20`: the file's own units, which an STL does not name. */ | |
| 20 | readonly size: string; | |
| 21 | } | |
| 22 | ||
| 23 | /** The facts of an STL, or the sentence that says why they cannot be had. */ | |
| 24 | export function readStl(bytes: Uint8Array): StlFacts | { readonly error: string } { | |
| 25 | if (bytes.length === 0) return { error: "This file is empty." }; | |
| 26 | const claimed = | |
| 27 | bytes.length >= 84 ? new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(80, true) : -1; | |
| 28 | // A binary STL is an 80-byte header, a u32 count and 50 bytes a facet; its | |
| 29 | // length must say exactly so. One that opens with `solid` may be ASCII. | |
| 30 | const binary = claimed >= 0 && 84 + claimed * 50 === bytes.length; | |
| 31 | // ASCII has no NUL: a `solid` header with one is a binary file of the wrong length. | |
| 32 | const text = !bytes.subarray(0, 1024).includes(0) && /^\s*solid\b/.test(new TextDecoder().decode(bytes.subarray(0, 256))); | |
| 33 | if (!binary && !text) { | |
| 34 | if (claimed < 0) return { error: "This is not a readable STL file: it is shorter than a binary STL's header." }; | |
| 35 | return { | |
| 36 | error: `This STL is cut short or damaged: its header claims ${claimed.toLocaleString("en")} triangles, which ${(84 + claimed * 50).toLocaleString("en")} bytes would hold, and the file has ${bytes.length.toLocaleString("en")}.`, | |
| 37 | }; | |
| 38 | } | |
| 39 | try { | |
| 40 | const mesh = parseStl(bytes); | |
| 41 | if (mesh.triangles === 0) return { error: "This STL holds no triangles." }; | |
| 42 | for (const v of mesh.positions) if (!Number.isFinite(v)) return { error: "This STL holds a coordinate that is not a number." }; | |
| 43 | const box = bounds(mesh.positions); | |
| 44 | return { triangles: mesh.triangles, box, size: sizeText(box.size, "units") }; | |
| 45 | } catch (error) { | |
| 46 | return { error: `This is not a readable STL file${error instanceof MeshError ? `: ${error.message}` : ""}.` }; | |
| 47 | } | |
| 48 | } |
test/render-stl.test.ts added +74
| @@ -0,0 +1,74 @@ | ||
| 1 | /** An .stl file: facts in the first paint, a plain refusal when unreadable (#12990). */ | |
| 2 | ||
| 3 | import { describe, expect, test } from "bun:test"; | |
| 4 | import { model3d } from "../src/web/render/model3d.ts"; | |
| 5 | import { readStl, STL_LIMIT } from "../src/web/render/stl.ts"; | |
| 6 | ||
| 7 | const fixture = async (name: string): Promise<Uint8Array> => | |
| 8 | new Uint8Array(await Bun.file(new URL(`./fixtures/model3d/${name}`, import.meta.url)).arrayBuffer()); | |
| 9 | ||
| 10 | describe("readStl", () => { | |
| 11 | test("a cube is 12 triangles in a 20-unit box, in both forms, and the twins agree", async () => { | |
| 12 | const binary = readStl(await fixture("cube-binary.stl")); | |
| 13 | const ascii = readStl(await fixture("cube-ascii.stl")); | |
| 14 | if ("error" in binary || "error" in ascii) throw new Error("a cube must read"); | |
| 15 | expect(binary.triangles).toBe(12); | |
| 16 | expect(binary.size).toBe("20 × 20 × 20 units"); | |
| 17 | expect(ascii.triangles).toBe(binary.triangles); | |
| 18 | expect(ascii.box).toEqual(binary.box); | |
| 19 | expect(ascii.size).toBe(binary.size); | |
| 20 | }); | |
| 21 | ||
| 22 | test("a truncated binary file is refused with a sentence naming the claim", async () => { | |
| 23 | const bytes = await fixture("cube-binary.stl"); | |
| 24 | const cut = readStl(bytes.subarray(0, bytes.length - 20)); | |
| 25 | expect(cut).toEqual({ error: expect.stringContaining("header claims 12 triangles") }); | |
| 26 | expect(readStl(new Uint8Array(10))).toEqual({ error: expect.stringContaining("shorter") }); | |
| 27 | }); | |
| 28 | ||
| 29 | test("a header that claims far more than the bytes hold costs nothing", () => { | |
| 30 | const bytes = new Uint8Array(84); | |
| 31 | new DataView(bytes.buffer).setUint32(80, 0xffffffff, true); | |
| 32 | expect(readStl(bytes)).toEqual({ error: expect.stringContaining("cut short") }); | |
| 33 | }); | |
| 34 | ||
| 35 | test("a coordinate that is not a number is refused", () => { | |
| 36 | const bytes = new Uint8Array(84 + 50); | |
| 37 | const view = new DataView(bytes.buffer); | |
| 38 | view.setUint32(80, 1, true); | |
| 39 | view.setFloat32(84 + 12, NaN, true); | |
| 40 | expect(readStl(bytes)).toEqual({ error: expect.stringContaining("not a number") }); | |
| 41 | }); | |
| 42 | }); | |
| 43 | ||
| 44 | describe("the first paint", () => { | |
| 45 | const input = (path: string, size: number, body: Uint8Array) => ({ path, size, body, media: "/m", download: "/m?download=1" }); | |
| 46 | ||
| 47 | test("the summary reads without JavaScript, and the name is escaped", async () => { | |
| 48 | const body = await fixture("cube-binary.stl"); | |
| 49 | const text = model3d(input("a/<b>.stl", body.length, body)).content.text; | |
| 50 | expect(text).toContain("<dt>Triangles</dt><dd>12</dd>"); | |
| 51 | expect(text).toContain("20 × 20 × 20 units"); | |
| 52 | expect(text).not.toContain("<b>"); | |
| 53 | }); | |
| 54 | ||
| 55 | test("a 3 MB file, past the old 2 MB cap, still has its facts in the first paint", () => { | |
| 56 | const n = 60_000; | |
| 57 | const body = new Uint8Array(84 + n * 50); | |
| 58 | const view = new DataView(body.buffer); | |
| 59 | view.setUint32(80, n, true); | |
| 60 | for (let i = 0; i < n; i++) view.setFloat32(84 + i * 50 + 12, i % 7, true); | |
| 61 | expect(body.length).toBeGreaterThan(2_000_000); | |
| 62 | const text = model3d(input("big.stl", body.length, body)).content.text; | |
| 63 | expect(text).toContain("<dt>Triangles</dt><dd>60,000</dd>"); | |
| 64 | expect(text).toContain("units"); | |
| 65 | }); | |
| 66 | ||
| 67 | test("a damaged file says why in the frame; one over 20 MB is never fetched", async () => { | |
| 68 | const body = (await fixture("cube-binary.stl")).subarray(0, 100); | |
| 69 | expect(model3d(input("a.stl", body.length, body)).content.text).toContain("cut short"); | |
| 70 | const big = model3d(input("a.stl", STL_LIMIT + 1, new Uint8Array(0))).content.text; | |
| 71 | expect(big).toContain("over 20 MB"); | |
| 72 | expect(big).not.toContain("data-src"); | |
| 73 | }); | |
| 74 | }); |
new above
offline
Principle 2 and box 1: the first-paint facts are skipped when input.size > FACTS_CAP (2 MB), so a 5 MB STL shows an empty Triangles and Box row without JavaScript. Allow up to STL_LIMIT for stl (the parse is bounded by the byte-length check) and make sure the render input carries that much of the body. Test it.