Public: anyone can read this; the crew can change it.

A .obj mesh opens in the 3D viewer with its vertex and face counts #14095

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/14062-a-obj-mesh-opens-in-the-3d-viewer-with-i → main 5 commits fork 4 threads · 4 unresolved

  • Merged. scout/14062-a-obj-mesh-opens-in-the-3d-viewer-with-i was merged into main as 35b0b26.

Review

Sign in to review this change.
7 files changed +166 −12
docs/features/mesh-files.md +6 −3
@@ -1,23 +1,26 @@
11 # Open an .obj or .ply file
22
33 A `.obj` or `.ply` file in the code browser opens in the 3D viewer, the same one an `.stl` uses. Beside the view the
4 facts list **Vertices**, **Faces**, **Triangles** and the **Box** (its size in the file's own units, shown as mm).
4 facts list **Vertices**, **Faces**, (for an `.obj`) **Groups**, **Triangles** and the **Box** (its size in the file's own units, shown as mm).
55 The first paint carries them: the server reads the file (up to 2 MB) and renders the rows, so they show with
66 JavaScript off. For a larger file the viewer fills them in once it has fetched and read it.
77
88 - **Vertices** are the points the file lists; **Faces** are the polygons, before they are cut into triangles.
9 - **Groups** are the distinct named objects and groups (`o`, `g` lines) in an OBJ; a repeated or empty name counts once or not at all.
910 - **Dropped faces**: a face that names a vertex the file does not have is left out and counted, as
1011 `6 (1 face dropped)`.
1112 - **Over the cap**: a part of more than 5,000,000 triangles is counted but not drawn. The facts stay, and the view
1213 says "This part has more triangles than can be drawn here; download it to open it elsewhere." with a Download button.
1314 - **Not readable**: a truncated file, a big-endian PLY, or a header that claims more than the bytes hold is refused
1415 with a plain note and Download; nothing is partly drawn. Reading never spends time on a claimed count, only on bytes.
16 - **OBJ falls back to source**: an OBJ over 20 MB, or one that is not readable (a vertex that is not three numbers, bytes that are not text), is shown as source with one sentence,
17 and the viewer says the same sentence for a large file it fetched itself (`OBJ_TOO_BIG`, `OBJ_BROKEN` in `src/web/render/obj.ts`).
1518 - PLY: ASCII and binary little-endian; only `vertex` (x, y, z) and `face` (`vertex_indices`) are read.
1619
1720 The terminal (both doors): the workspace screen's file view shows the same file as
18 `3D model · OBJ` over `12 triangles · 1 × 1 × 1 mm · 8 vertices · 6 faces`, and `not a readable PLY file` for one it cannot read.
21 `3D model · OBJ` over `12 triangles · 1 × 1 × 1 mm · 8 vertices · 6 faces · 2 groups` (groups only when an OBJ names some), and `not a readable PLY file` for one it cannot read.
1922 The facts come from the same parsers as the page (`src/web/render/model-facts.ts`).
2023
2124 Try it: commit `part.obj` or `part.ply` to a repository and open it under Code.
2225
23 Pinned by `test/render-obj-ply.test.ts`.
26 Pinned by `test/render-obj-ply.test.ts` and `test/render-obj.test.ts`.
src/web/render/mesh.ts +12 −4
@@ -16,6 +16,8 @@ export interface Mesh {
1616 readonly vertices?: number;
1717 /** Faces kept, before they were cut into triangles. */
1818 readonly faces?: number;
19 /** Named objects and groups (`o`, `g`) in an OBJ; unset for other formats. */
20 readonly groups?: number;
1921 /** Faces dropped because they name a vertex that is not there. */
2022 readonly dropped?: number;
2123 /** More triangles than `TRIANGLE_LIMIT`: counted, but `positions` is empty. */
@@ -133,14 +135,19 @@ export function soupBuilder(vertices: number[], limit = TRIANGLE_LIMIT): {
133135 /**
134136 * Wavefront OBJ: `v` lines and `f` lines; a face of more than three corners
135137 * is a fan. Indices are 1-based, and a negative one counts back from the last
136 * vertex read. Normals, texture coordinates, groups and materials are skipped.
138 * vertex read. Named objects and groups (`o`, `g`) are counted; normals,
139 * texture coordinates and materials are skipped.
outdated

Ungrammatical and over-wrapped comment: 'Normals, texture coordinates, materials are skipped'. Reword it.

137140 */
138141 export function parseObj(text: string, limit = TRIANGLE_LIMIT): Mesh {
139142 const vertices: number[] = [];
140143 const soup = soupBuilder(vertices, limit);
144 const groups = new Set<string>();
141145 for (const line of text.split("\n")) {
142146 const parts = line.trim().split(/\s+/);
143 if (parts[0] === "v") {
147 if (parts[0] === "o" || parts[0] === "g") {
148 const name = parts.slice(1).join(" ");
149 if (name !== "") groups.add(`${parts[0]} ${name}`);
150 } else if (parts[0] === "v") {
144151 const [x, y, z] = [Number(parts[1]), Number(parts[2]), Number(parts[3])];
145152 if (![x, y, z].every(Number.isFinite)) throw new MeshError("a vertex that is not three numbers");
146153 vertices.push(x, y, z);
@@ -155,7 +162,7 @@ export function parseObj(text: string, limit = TRIANGLE_LIMIT): Mesh {
155162 );
156163 }
157164 }
158 return soup.done();
165 return { ...soup.done(), groups: groups.size };
159166 }
160167
161168 /** The axis-aligned box around every corner; all zeros for an empty mesh. */
@@ -189,11 +196,12 @@ function count(v: number, one: string, many: string): string {
189196 * The words for an indexed mesh's rows, shared by the page's first paint, the viewer and the
190197 * terminal.
191198 */
192 export function indexedRows(mesh: Mesh): { vertices: string; faces: string; triangles: string; box: string } {
199 export function indexedRows(mesh: Mesh): { vertices: string; faces: string; groups?: string; triangles: string; box: string } {
193200 const dropped = mesh.dropped ? ` (${count(mesh.dropped, "face", "faces")} dropped)` : "";
194201 return {
195202 vertices: (mesh.vertices ?? 0).toLocaleString("en"),
196203 faces: `${(mesh.faces ?? 0).toLocaleString("en")}${dropped}`,
204 ...(mesh.groups === undefined ? {} : { groups: mesh.groups.toLocaleString("en") }),
197205 triangles: mesh.triangles.toLocaleString("en"),
198206 box: sizeText((mesh.box ?? bounds(mesh.positions)).size),
199207 };
src/web/render/model-facts.ts +2 −1
@@ -77,7 +77,8 @@ function read(ext: string, bytes: Uint8Array): Facts {
7777 export function indexedWords(mesh: Mesh): string {
7878 const n = (v: number, one: string, many: string): string => `${v.toLocaleString("en")} ${v === 1 ? one : many}`;
7979 const dropped = mesh.dropped ? ` (${n(mesh.dropped, "face", "faces")} dropped)` : "";
80 return `${n(mesh.vertices ?? 0, "vertex", "vertices")} · ${n(mesh.faces ?? 0, "face", "faces")}${dropped}`;
80 const groups = !mesh.groups ? "" : ` · ${n(mesh.groups, "group", "groups")}`;
81 return `${n(mesh.vertices ?? 0, "vertex", "vertices")} · ${n(mesh.faces ?? 0, "face", "faces")}${dropped}${groups}`;
8182 }
8283
8384 /**
src/web/render/model3d-client.ts +8 −3
@@ -36,7 +36,8 @@ import { OrbitControls } from "three/addons/controls/OrbitControls.js";
3636 import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
3737 import { REFUSED_URI, withinModelDir } from "./gltf-uri.ts";
3838 import { parse3mf } from "./threemf.ts";
39 import { bounds, indexedRows, OVER_CAP_NOTE, parseObj, parseStl, sizeText, type Bounds, type Mesh as Parsed } from "./mesh.ts";
39 import { ObjFallback, objFromText } from "./obj.ts";
40 import { bounds, indexedRows, OVER_CAP_NOTE, parseStl, sizeText, type Bounds, type Mesh as Parsed } from "./mesh.ts";
4041 import { parsePly } from "./ply.ts";
4142
4243 /**
@@ -102,7 +103,7 @@ async function load(src: string, format: string): Promise<Loaded> {
102103 if (format === "stl" || format === "obj" || format === "ply" || format === "3mf") {
103104 const parsed: Parsed =
104105 format === "obj"
105 ? parseObj(await response.text())
106 ? objFromText(await response.text())
106107 : format === "3mf"
107108 ? await parse3mf(new Uint8Array(await response.arrayBuffer()))
108109 : format === "ply"
@@ -196,6 +197,7 @@ function mount(figure: Element): void {
196197 if (rows !== undefined) {
197198 fact("[data-vertices]", rows.vertices);
198199 fact("[data-faces]", rows.faces);
outdated

The viewer only gains the Groups fact. A big OBJ the page did not read is parsed here, and a malformed or over-cap one needs the same one-sentence source fallback (OBJ_BROKEN / OBJ_TOO_BIG) the page gives small files, or box 3 is only half met. Add a test for it.

200 if (rows.groups !== undefined) fact("[data-groups]", rows.groups);
199201 }
200202 if (overCap) {
201203 // Counted, not drawn: the facts stay, the note and Download with them.
@@ -291,7 +293,10 @@ function mount(figure: Element): void {
291293 (error: unknown) => {
292294 renderer.dispose();
293295 if (note !== null) note.hidden = false;
294 stats.textContent = `Could not draw this file: ${error instanceof Error ? error.message : String(error)}`;
296 stats.textContent =
297 error instanceof ObjFallback
298 ? error.message
299 : `Could not draw this file: ${error instanceof Error ? error.message : String(error)}`;
295300 },
296301 );
297302 }
src/web/render/model3d.ts +5 −1
@@ -23,6 +23,7 @@ import type { BuiltAsset } from "../asset.ts";
2323 import { html, type Html } from "../html.ts";
2424 import { btn, empty, fileSize } from "../ui.ts";
2525 import { indexedRows } from "./mesh.ts";
26 import { readObj } from "./obj.ts";
2627 import { indexedMesh } from "./model-facts.ts";
2728 import { readStl, STL_LIMIT, STL_TOO_BIG } from "./stl.ts";
2829 import type { Rendered, RenderInput } from "./renderers.ts";
@@ -44,7 +45,9 @@ export function model3d(input: RenderInput): Rendered {
4445 btn(label, { type: "button", size: "sm", variant: "outline", extra: "js-only", pressed: false, value });
4546 // An OBJ or PLY the page read has its counts in the first paint; the viewer
4647 // fills the same rows for a file it fetched itself.
47 const mesh = indexedMesh(input.path, input.body, input.size);
48 const obj = readObj(input.path, input.body, input.size);

readObj parses the whole body, then indexedMesh on the next line parses it again. Parse once and share the mesh.

49 if (obj !== null && "fallback" in obj) return { lines: 0, content: html``, fallback: obj.fallback };
50 const mesh = obj !== null ? (obj.mesh ?? null) : indexedMesh(input.path, input.body, input.size);
4851 const rows = mesh === null ? undefined : indexedRows(mesh);
4952 const row = (key: string, label: string, value: string | undefined): Html =>
5053 value === undefined
@@ -77,6 +80,7 @@ export function model3d(input: RenderInput): Rendered {
7780 <div><dt>File</dt><dd>${fileSize(input.size)}</dd></div>
7881 ${row("vertices", "Vertices", rows?.vertices)}
7982 ${row("faces", "Faces", rows?.faces)}
83 ${formatOf(input.path) === "obj" ? row("groups", "Groups", rows?.groups) : html``}
8084 ${row("triangles", "Triangles", rows?.triangles ?? stlFacts?.triangles.toLocaleString("en"))}
8185 ${row("box", "Box", rows?.box ?? stlFacts?.size)}
8286 </dl>
src/web/render/obj.ts added +46
@@ -0,0 +1,46 @@
1 /**
2 * An OBJ the viewer will open, or the one sentence for why it shows as source.
3 * The counts come from `mesh.ts`'s `parseObj`, the parser the browser runs
4 * too; this module only decides, at the page, whether the file is drawn.
5 */
6
7 import { parseObj, type Mesh } from "./mesh.ts";
8
9 /** An OBJ over this is not drawn: the page offers the source and Download. */
10 export const OBJ_LIMIT = 20_000_000;
11
12 /** The page reads a body this small itself; a bigger one is the viewer's to fetch. */
13 const PAGE_READ_CAP = 2_000_000;
14
15 export const OBJ_TOO_BIG = "This OBJ is over 20 MB, so it is shown as source; Download opens it elsewhere.";
16 export const OBJ_BROKEN = "This file is not a readable OBJ mesh, so it is shown as source.";
17
18 const isObj = (path: string): boolean => path.toLowerCase().endsWith(".obj");
19
20 /** An OBJ that is not drawn, with the one sentence that says why. */
21 export class ObjFallback extends Error {}
22
23 /** The mesh of an OBJ's text; an ObjFallback with its sentence when it is too big or not an OBJ. */
24 export function objFromText(text: string): Mesh {
25 if (text.length > OBJ_LIMIT) throw new ObjFallback(OBJ_TOO_BIG);
26 try {
27 return parseObj(text);
28 } catch {
29 throw new ObjFallback(OBJ_BROKEN);
30 }
31 }
32
33 /**
34 * Null for a file that is not an OBJ. Over the cap or unreadable: the reason it shows as source.
35 * Otherwise its mesh, or none when the page did not read the body (the viewer parses it).
36 */
37 export function readObj(path: string, body: Uint8Array, size: number): { fallback: string } | { mesh?: Mesh } | null {
38 if (!isObj(path)) return null;
39 if (size > OBJ_LIMIT) return { fallback: OBJ_TOO_BIG };
40 if (body.length === 0 || size > PAGE_READ_CAP) return {};
41 try {
42 return { mesh: objFromText(new TextDecoder("utf-8", { fatal: true }).decode(body)) };
43 } catch {
44 return { fallback: OBJ_BROKEN };
45 }
46 }
test/render-obj.test.ts added +87
@@ -0,0 +1,87 @@
1 /** An OBJ opens in the 3D frame with its counts, or falls back to source with one sentence. */
2
3 import { describe, expect, test } from "bun:test";
4 import { indexedRows, parseObj } from "../src/web/render/mesh.ts";
5 import { model3d } from "../src/web/render/model3d.ts";
6 import { indexedWords, modelFacts } from "../src/web/render/model-facts.ts";
7 import { OBJ_BROKEN, OBJ_LIMIT, OBJ_TOO_BIG, ObjFallback, objFromText, readObj } from "../src/web/render/obj.ts";
8
9 const enc = (s: string): Uint8Array => new TextEncoder().encode(s);
10 const CUBE =
11 "o cube\ng top\n" +
12 "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nv 0 0 1\nv 1 0 1\nv 1 1 1\nv 0 1 1\n" +
13 "f 1 4 3 2\nf 5 6 7 8\nf 1 2 6 5\nf 3 4 8 7\nf 2 3 7 6\nf 4 1 5 8\n";
14
15 const input = (path: string, body: Uint8Array, size = body.length) => ({
16 path,
17 size,
18 body,
19 media: `/a/b/media/main/${path}`,
20 download: `/a/b/media/main/${path}?download=1`,
21 });
22
23 describe("a cube", () => {
24 test("counts vertices, faces and groups", () => {
25 const mesh = parseObj(CUBE);
26 expect([mesh.vertices, mesh.faces, mesh.groups]).toEqual([8, 6, 2]);
27 expect(indexedRows(mesh).groups).toBe("2");
28 });
29
30 test("the frame shows the three counts in the first paint, above the viewer", () => {
31 const out = model3d(input("cube.obj", enc(CUBE)));
32 expect(out.fallback).toBeUndefined();
33 const text = out.content.text;
34 expect(text).toContain("<div data-vertices><dt>Vertices</dt><dd>8</dd>");
35 expect(text).toContain("<div data-faces><dt>Faces</dt><dd>6</dd>");
36 expect(text).toContain("<div data-groups><dt>Groups</dt><dd>2</dd>");
37 expect(text.indexOf("data-groups")).toBeLessThan(text.indexOf("data-stage"));
38 expect(text).toContain('data-format="obj"');
39 });
40
41 test("a file the page did not read still gets a frame with a Groups slot for the viewer", () => {
42 const out = model3d(input("big.obj", new Uint8Array(0), 10_000_000));
43 expect(out.fallback).toBeUndefined();
44 expect(out.content.text).toContain("data-groups hidden");
45 });
46
47 test("a PLY has no Groups row", () => {
48 expect(model3d(input("a.ply", new Uint8Array(0), 10)).content.text).not.toContain("data-groups");
49 });
50 });
51
52 describe("a file that cannot be drawn shows as source with one sentence", () => {
53 test("over the size cap", () => {
54 expect(model3d(input("huge.obj", new Uint8Array(0), OBJ_LIMIT + 1)).fallback).toBe(OBJ_TOO_BIG);
55 });
56
57 test("hostile: a vertex that is not numbers", () => {
58 expect(model3d(input("bad.obj", enc("v 0 0 0\nv nan x 1\nf 1 1 1\n"))).fallback).toBe(OBJ_BROKEN);
59 });
60
61 test("hostile: bytes that are not text", () => {
62 expect(readObj("bin.obj", new Uint8Array([0xff, 0xfe, 0x00, 0x80]), 4)).toEqual({ fallback: OBJ_BROKEN });
63 });
64
65 test("hostile: faces naming missing vertices are dropped, not fatal", () => {
66 const out = model3d(input("x.obj", enc("v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\nf 1 2 9999999999\nf -5 1 2\n")));
67 expect(out.fallback).toBeUndefined();
68 expect(out.content.text).toContain("(2 faces dropped)");
69 });
70
71 test("the viewer's reader gives the same sentences for a large file the page did not read", () => {
outdated

Vacuous: group names are never printed, so this passes without any escaping. Test something the change can break.

72 expect(() => objFromText("v 0 0 0\nv x y z\n")).toThrow(OBJ_BROKEN);
73 expect(() => objFromText("v 0 0 0\n".repeat(OBJ_LIMIT / 8 + 1))).toThrow(OBJ_TOO_BIG);
74 expect(objFromText(CUBE).groups).toBe(2);
75 expect(() => objFromText("v a b c")).toThrow(ObjFallback);
76 });
77
78 test("a group is counted once however often it recurs, and a nameless one not at all", () => {
79 expect(parseObj("g a\ng a\ng\no a\nv 0 0 0\n").groups).toBe(2);
80 });
81 });
82
83 test("the terminal's words carry the groups, when there are any", () => {
84 expect(indexedWords(parseObj(CUBE))).toBe("8 vertices · 6 faces · 2 groups");
85 expect(modelFacts("c.obj", enc(CUBE), 100).facts).toContain("· 2 groups");
86 expect(indexedWords(parseObj("v 0 0 0\n"))).toBe("1 vertex · 0 faces");
87 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs