Public: anyone can read this; the crew can change it.
A Collada .dae file opens in the 3D viewer, drawn from its mesh #14469
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/14448-a-collada-dae-file-opens-in-the-3d-viewe → main 5 commits fork 1 thread · 1 unresolved
9 files
changed +346
−17
docs/features/file-kinds.md +1 −1
| @@ -17,7 +17,7 @@ The forge draws a file on its page when its kind is below and it is within the s | ||
| 17 | 17 | - **Table (CSV, TSV, JSON lines)**, drawn up to 10 MB: `.csv`, `.tsv`, `.jsonl`, `.ndjson` |
| 18 | 18 | - **SQLite database**, drawn up to 5 MB: `.db`, `.sqlite`, `.sqlite3` |
| 19 | 19 | - **Parquet**, drawn up to 5 MB: `.parquet` |
| 20 | - **3D model**, drawn up to 100 MB: `.stl`, `.3mf`, `.ply`, `.glb`, `.gltf`, `.obj` | |
| 20 | - **3D model**, drawn up to 100 MB: `.stl`, `.3mf`, `.ply`, `.glb`, `.gltf`, `.obj`, `.dae` | |
| 21 | 21 | - **Archive**, drawn up to 50 MB: `.zip`, `.tar`, `.tgz`, `.tar.gz` |
| 22 | 22 | - **Spreadsheet**, drawn up to 10 MB: `.xlsx` |
| 23 | 23 | - **Word document**, drawn up to 10 MB: `.docx` |
docs/features/mesh-files.md +10
| @@ -28,3 +28,13 @@ The facts come from the same parsers as the page (`src/web/render/model-facts.ts | ||
| 28 | 28 | Try it: commit `part.obj` or `part.ply` to a repository and open it under Code. |
| 29 | 29 | |
| 30 | 30 | Pinned by `test/render-obj-ply.test.ts` and `test/render-obj.test.ts`. |
| 31 | ||
| 32 | ## Collada (.dae) | |
| 33 | ||
| 34 | A `.dae` file opens in the same viewer. Every `<mesh>`'s `<triangles>`, `<polylist>` and `<polygons>` are read as one mesh, | |
| 35 | with the same Vertices, Faces, Triangles and Box rows beside it (`<unit meter>` is applied; the box is shown as mm). | |
| 36 | A file over 20 MB, one without a `<COLLADA>` root, or one with no triangles is shown as source with one sentence | |
| 37 | (`DAE_TOO_BIG`, `DAE_BROKEN` in `src/web/render/collada.ts`); it never errors the page. Not read: scene-graph transforms, | |
| 38 | materials, lines, and the up axis. | |
| 39 | ||
| 40 | Pinned by `test/render-collada.test.ts`. |
src/web/render/collada.ts added +212
| @@ -0,0 +1,212 @@ | ||
| 1 | /** | |
| 2 | * A Collada `.dae` file (XML) as one triangle soup, in millimetres, with no | |
| 3 | * library and no DOM. Every `<mesh>` is read: its `<source>` float arrays, the | |
| 4 | * `<vertices>` that name the POSITION source, and the `<triangles>`, | |
| 5 | * `<polylist>` and `<polygons>` that index them. All of them become one mesh | |
| 6 | * through `soupBuilder` (`mesh.ts`), so a polygon is fanned and a face naming | |
| 7 | * a missing vertex is dropped and counted. Scene-graph transforms, materials, | |
| 8 | * lines and the up axis are not applied; `<unit meter>` is. | |
| 9 | * | |
| 10 | * Untrusted bytes: the text is refused over `DAE_LIMIT` before it is looked at, | |
| 11 | * every scan is a forward-only `indexOf` walk (`elements`), so an opener with no | |
| 12 | * closer ends the scan instead of rescanning, and no count in the file sizes an | |
| 13 | * allocation. Nothing from the file is ever echoed: names and ids are only | |
| 14 | * used as lookup keys. | |
| 15 | */ | |
| 16 | ||
| 17 | import { MeshError, soupBuilder, type Mesh } from "./mesh.ts"; | |
| 18 | import { ObjFallback } from "./obj.ts"; | |
| 19 | ||
| 20 | /** A Collada file over this is not drawn: the page offers the source and Download. */ | |
| 21 | export const DAE_LIMIT = 20_000_000; | |
| 22 | /** The page reads a body this small itself; a bigger one is the viewer's to fetch. */ | |
| 23 | const PAGE_READ_CAP = 2_000_000; | |
| 24 | ||
| 25 | export const DAE_TOO_BIG = "This Collada file is over 20 MB, so it is shown as source; Download opens it elsewhere."; | |
| 26 | export const DAE_BROKEN = "This file is not a readable Collada mesh, so it is shown as source."; | |
| 27 | ||
| 28 | /** The text with every `open … close` span removed; an unclosed opener leaves the rest. */ | |
| 29 | const strip = (text: string, open: string, close: string): string => { | |
| 30 | let out = ""; | |
| 31 | let at = 0; | |
| 32 | for (;;) { | |
| 33 | const a = text.indexOf(open, at); | |
| 34 | const b = a === -1 ? -1 : text.indexOf(close, a + open.length); | |
| 35 | if (b === -1) return out + text.slice(at); | |
| 36 | out += text.slice(at, a); | |
| 37 | at = b + close.length; | |
| 38 | } | |
| 39 | }; | |
| 40 | ||
| 41 | interface Element { | |
| 42 | readonly attrs: string; | |
| 43 | readonly body: string; | |
| 44 | } | |
| 45 | ||
| 46 | /** | |
| 47 | * Every `<name …>body</name>` in order, found by walking forward once: the | |
| 48 | * scan resumes after each closer, and stops at the first opener with no | |
| 49 | * closer (or no `>`), so hostile text cannot make it quadratic. | |
| 50 | */ | |
| 51 | function* elements(text: string, name: string): Generator<Element> { | |
| 52 | const open = `<${name}`; | |
| 53 | const close = `</${name}>`; | |
| 54 | let at = 0; | |
| 55 | for (;;) { | |
| 56 | const a = text.indexOf(open, at); | |
| 57 | if (a === -1) return; | |
| 58 | const next = text.charCodeAt(a + open.length); | |
| 59 | // Not this element: a longer name (`<meshes`), so move past the match. | |
| 60 | if (!(next === 62 || next === 47 || next === 32 || next === 9 || next === 10 || next === 13)) { | |
| 61 | at = a + open.length; | |
| 62 | continue; | |
| 63 | } | |
| 64 | const gt = text.indexOf(">", a); | |
| 65 | if (gt === -1) return; | |
| 66 | const attrs = text.slice(a + open.length, gt); | |
| 67 | if (text.charCodeAt(gt - 1) === 47) { | |
| 68 | yield { attrs, body: "" }; | |
| 69 | at = gt + 1; | |
| 70 | continue; | |
| 71 | } | |
| 72 | const end = text.indexOf(close, gt + 1); | |
| 73 | if (end === -1) return; | |
| 74 | yield { attrs, body: text.slice(gt + 1, end) }; | |
| 75 | at = end + close.length; | |
| 76 | } | |
| 77 | } | |
| 78 | ||
| 79 | const attr = (tag: string, name: string): string | undefined => { | |
| 80 | const m = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(tag); | |
| 81 | return m === null ? undefined : (m[1] ?? m[2]); | |
| 82 | }; | |
| 83 | ||
| 84 | const numbers = (text: string): number[] => { | |
| 85 | const out: number[] = []; | |
| 86 | for (const word of text.split(/\s+/)) if (word !== "") out.push(Number(word)); | |
| 87 | return out; | |
| 88 | }; | |
| 89 | ||
| 90 | const idOf = (ref: string | undefined): string => (ref ?? "").replace(/^#/, ""); | |
| 91 | ||
| 92 | interface Input { | |
| 93 | readonly semantic: string; | |
| 94 | readonly source: string; | |
| 95 | readonly offset: number; | |
| 96 | } | |
| 97 | ||
| 98 | const inputsOf = (block: string): Input[] => | |
| 99 | [...elements(block, "input")].map((e) => ({ | |
| 100 | semantic: attr(e.attrs, "semantic") ?? "", | |
| 101 | source: idOf(attr(e.attrs, "source")), | |
| 102 | offset: Number(attr(e.attrs, "offset") ?? 0), | |
| 103 | })); | |
| 104 | ||
| 105 | /** The mesh of a Collada document's text; a MeshError when it holds no triangles. */ | |
| 106 | export function parseCollada(text: string, limit?: number): Mesh { | |
| 107 | if (!/<COLLADA[\s>]/.test(text.slice(0, 4096))) throw new MeshError("not a Collada document"); | |
| 108 | const clean = strip(strip(text, "<!--", "-->"), "<![CDATA[", "]]>"); | |
| 109 | const meter = Number(attr(elements(clean, "unit").next().value?.attrs ?? "", "meter") ?? 1); | |
| 110 | const scale = (Number.isFinite(meter) && meter > 0 ? meter : 1) * 1000; | |
| 111 | const vertices: number[] = []; | |
| 112 | const soup = soupBuilder(vertices, limit); | |
| 113 | let any = false; | |
| 114 | for (const mesh of elements(clean, "mesh")) { | |
| 115 | const body = mesh.body; | |
| 116 | const sources = new Map<string, { data: number[]; stride: number }>(); | |
| 117 | for (const s of elements(body, "source")) { | |
| 118 | const id = attr(s.attrs, "id"); | |
| 119 | const array = elements(s.body, "float_array").next().value?.body; | |
| 120 | if (id === undefined || array === undefined) continue; | |
| 121 | const stride = Number(attr(elements(s.body, "accessor").next().value?.attrs ?? "", "stride") ?? 3); | |
| 122 | sources.set(id, { data: numbers(array), stride: Number.isInteger(stride) && stride >= 3 ? stride : 3 }); | |
| 123 | } | |
| 124 | const vertexSource = new Map<string, string>(); | |
| 125 | for (const v of elements(body, "vertices")) { | |
| 126 | const position = inputsOf(v.body).find((i) => i.semantic === "POSITION"); | |
| 127 | const id = attr(v.attrs, "id"); | |
| 128 | if (position !== undefined && id !== undefined) vertexSource.set(id, position.source); | |
| 129 | } | |
| 130 | // The positions this mesh uses, appended once, and where each source starts. | |
| 131 | const base = new Map<string, { start: number; count: number }>(); | |
| 132 | const place = (id: string): { start: number; count: number } | undefined => { | |
| 133 | const known = base.get(id); | |
| 134 | if (known !== undefined) return known; | |
| 135 | const src = sources.get(id); | |
| 136 | if (src === undefined) return undefined; | |
| 137 | const start = vertices.length / 3; | |
| 138 | const count = Math.floor(src.data.length / src.stride); | |
| 139 | for (let i = 0; i < count; i++) { | |
| 140 | const xyz = [src.data[i * src.stride]!, src.data[i * src.stride + 1]!, src.data[i * src.stride + 2]!]; | |
| 141 | if (!xyz.every(Number.isFinite)) throw new MeshError("a vertex that is not three numbers"); | |
| 142 | vertices.push(xyz[0]! * scale, xyz[1]! * scale, xyz[2]! * scale); | |
| 143 | } | |
| 144 | const entry = { start, count }; | |
| 145 | base.set(id, entry); | |
| 146 | return entry; | |
| 147 | }; | |
| 148 | const prims = ["triangles", "polylist", "polygons"].flatMap((kind) => | |
| 149 | [...elements(body, kind)].filter((e) => e.body !== "").map((e) => ({ kind, body: e.body })), | |
| 150 | ); | |
| 151 | for (const prim of prims) { | |
| 152 | const inputs = inputsOf(prim.body); | |
| 153 | const vertex = inputs.find((i) => i.semantic === "VERTEX"); | |
| 154 | const positionId = vertex === undefined ? undefined : vertexSource.get(vertex.source); | |
| 155 | const at = positionId === undefined ? undefined : place(positionId); | |
| 156 | if (vertex === undefined || at === undefined) continue; | |
| 157 | const stride = Math.max(...inputs.map((i) => i.offset)) + 1; | |
| 158 | if (!Number.isInteger(stride) || stride < 1) continue; | |
| 159 | const corner = (list: number[], k: number): number => { | |
| 160 | const local = list[k * stride + vertex.offset]; | |
| 161 | return local !== undefined && Number.isInteger(local) && local >= 0 && local < at.count ? at.start + local : -1; | |
| 162 | }; | |
| 163 | const ps = [...elements(prim.body, "p")].map((p) => numbers(p.body)); | |
| 164 | any = true; | |
| 165 | if (prim.kind === "triangles") { | |
| 166 | for (const list of ps) | |
| 167 | for (let t = 0; t + 2 < list.length / stride; t += 3) soup.face([corner(list, t), corner(list, t + 1), corner(list, t + 2)]); | |
| 168 | } else if (prim.kind === "polygons") { | |
| 169 | for (const list of ps) { | |
| 170 | const n = Math.floor(list.length / stride); | |
| 171 | soup.face(Array.from({ length: n }, (_, k) => corner(list, k))); | |
| 172 | } | |
| 173 | } else { | |
| 174 | const counts = numbers(elements(prim.body, "vcount").next().value?.body ?? ""); | |
| 175 | const list = ps[0] ?? []; | |
| 176 | let k = 0; | |
| 177 | for (const c of counts) { | |
| 178 | if (!Number.isInteger(c) || c < 0 || (k + c) * stride > list.length) break; | |
| 179 | soup.face(Array.from({ length: c }, (_, j) => corner(list, k + j))); | |
| 180 | k += c; | |
| 181 | } | |
| 182 | } | |
| 183 | } | |
| 184 | } | |
| 185 | const result = soup.done(); | |
| 186 | if (!any || (result.faces ?? 0) === 0) throw new MeshError("the file holds no triangles"); | |
| 187 | return result; | |
| 188 | } | |
| 189 | ||
| 190 | /** | |
| 191 | * The mesh of a Collada file's text; an ObjFallback with its sentence when too big or unreadable. | |
| 192 | */ | |
| 193 | export function daeFromText(text: string): Mesh { | |
| 194 | if (text.length > DAE_LIMIT) throw new ObjFallback(DAE_TOO_BIG); | |
| 195 | try { | |
| 196 | return parseCollada(text); | |
| 197 | } catch { | |
| 198 | throw new ObjFallback(DAE_BROKEN); | |
| 199 | } | |
| 200 | } | |
| 201 | ||
| 202 | /** Null for a file that is not a `.dae`; otherwise as `readObj` answers. */ | |
| 203 | export function readDae(path: string, body: Uint8Array, size: number): { fallback: string } | { mesh?: Mesh } | null { | |
| 204 | if (!path.toLowerCase().endsWith(".dae")) return null; | |
| 205 | if (size > DAE_LIMIT) return { fallback: DAE_TOO_BIG }; | |
| 206 | if (body.length === 0 || size > PAGE_READ_CAP) return {}; | |
| 207 | try { | |
| 208 | return { mesh: daeFromText(new TextDecoder("utf-8", { fatal: true }).decode(body)) }; | |
| 209 | } catch { | |
| 210 | return { fallback: DAE_BROKEN }; | |
| 211 | } | |
| 212 | } |
src/web/render/kinds.ts +3
| @@ -256,6 +256,7 @@ const TEXTUAL: Readonly<Record<string, FileKind>> = { | ||
| 256 | 256 | ndjson: "csv", |
| 257 | 257 | gltf: "model3d", |
| 258 | 258 | obj: "model3d", |
| 259 | dae: "model3d", | |
| 259 | 260 | json: "config", |
| 260 | 261 | jsonc: "config", |
| 261 | 262 | yaml: "config", |
| @@ -481,6 +482,8 @@ export function fileKind(path: string, head: Uint8Array): FileKind { | ||
| 481 | 482 | if (isWorkflowName(path)) return "workflow"; |
| 482 | 483 | if (isComposeName(path)) return "compose"; |
| 483 | 484 | const ext = extension(path); |
| 485 | // Collada opens on a `<COLLADA` root: a `.dae` that does not is only text. | |
| 486 | if (ext === "dae") return /<COLLADA[\s>]/.test(new TextDecoder().decode(head)) ? "model3d" : "text"; | |
| 484 | 487 | if (ext === "step" || ext === "stp") return isStepHead(head) ? "step" : "text"; |
| 485 | 488 | // RTF opens on `{\rtf`: a `.rtf` whose bytes say otherwise is only text. |
| 486 | 489 | if (ext === "rtf") return /^\uFEFF?\s*\{\\rtf/.test(new TextDecoder().decode(head.subarray(0, 16))) ? "rtf" : "text"; |
src/web/render/model-facts.ts +10 −3
| @@ -13,6 +13,7 @@ | ||
| 13 | 13 | import { inflateRawSync } from "node:zlib"; |
| 14 | 14 | import { kindByName } from "./kinds.ts"; |
| 15 | 15 | import { bounds, parseObj, parseStl, sizeText, type Mesh } from "./mesh.ts"; |
| 16 | import { daeFromText } from "./collada.ts"; | |
| 16 | 17 | import { parsePly } from "./ply.ts"; |
| 17 | 18 | import { INFLATE_LIMIT, locateModel, parseModelXml } from "./threemf.ts"; |
| 18 | 19 | |
| @@ -69,7 +70,7 @@ function read(ext: string, bytes: Uint8Array): Facts { | ||
| 69 | 70 | const mesh = parseStl(bytes); |
| 70 | 71 | return { triangles: mesh.triangles, size: bounds(mesh.positions).size }; |
| 71 | 72 | } |
| 72 | if (ext === "obj" || ext === "ply") return indexedFacts(ext === "obj" ? parseObj(new TextDecoder().decode(bytes)) : parsePly(bytes)); | |
| 73 | if (ext === "obj" || ext === "ply" || ext === "dae") return indexedFacts(indexedParse(ext, bytes)); | |
| 73 | 74 | return gltfFacts(ext === "glb" ? glbJson(bytes) : new TextDecoder().decode(bytes)); |
| 74 | 75 | } |
| 75 | 76 | |
| @@ -87,14 +88,20 @@ export function indexedWords(mesh: Mesh): string { | ||
| 87 | 88 | */ |
| 88 | 89 | export function indexedMesh(path: string, bytes: Uint8Array, size: number): Mesh | null { |
| 89 | 90 | const ext = extension(path); |
| 90 | if ((ext !== "obj" && ext !== "ply") || size > FACTS_CAP || bytes.length === 0) return null; | |
| 91 | if ((ext !== "obj" && ext !== "ply" && ext !== "dae") || size > FACTS_CAP || bytes.length === 0) return null; | |
| 91 | 92 | try { |
| 92 | return ext === "obj" ? parseObj(new TextDecoder().decode(bytes)) : parsePly(bytes); | |
| 93 | return indexedParse(ext, bytes); | |
| 93 | 94 | } catch { |
| 94 | 95 | return null; |
| 95 | 96 | } |
| 96 | 97 | } |
| 97 | 98 | |
| 99 | function indexedParse(ext: string, bytes: Uint8Array): Mesh { | |
| 100 | if (ext === "ply") return parsePly(bytes); | |
| 101 | const text = new TextDecoder().decode(bytes); | |
| 102 | return ext === "dae" ? daeFromText(text) : parseObj(text); | |
| 103 | } | |
| 104 | ||
| 98 | 105 | function indexedFacts(mesh: Mesh): Facts { |
| 99 | 106 | return { |
| 100 | 107 | triangles: mesh.triangles, |
src/web/render/model3d-client.ts +12 −9
| @@ -36,6 +36,7 @@ import { OrbitControls } from "three/addons/controls/OrbitControls.js"; | ||
| 36 | 36 | import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"; |
| 37 | 37 | import { REFUSED_URI, withinModelDir } from "./gltf-uri.ts"; |
| 38 | 38 | import { parse3mf } from "./threemf.ts"; |
| 39 | import { daeFromText } from "./collada.ts"; | |
| 39 | 40 | import { ObjFallback, objFromText } from "./obj.ts"; |
| 40 | 41 | import { bounds, indexedRows, OVER_CAP_NOTE, parseStl, sizeText, type Bounds, type Mesh as Parsed } from "./mesh.ts"; |
| 41 | 42 | import { parsePly } from "./ply.ts"; |
| @@ -97,18 +98,20 @@ function soup(positions: Float32Array): Mesh { | ||
| 97 | 98 | return new Mesh(geometry, material()); |
| 98 | 99 | } |
| 99 | 100 | |
| 101 | async function parseFormat(format: string, response: Response): Promise<Parsed> { | |
| 102 | if (format === "obj") return objFromText(await response.text()); | |
| 103 | if (format === "dae") return daeFromText(await response.text()); | |
| 104 | const bytes = new Uint8Array(await response.arrayBuffer()); | |
| 105 | if (format === "3mf") return parse3mf(bytes); | |
| 106 | if (format === "ply") return parsePly(bytes); | |
| 107 | return parseStl(bytes); | |
| 108 | } | |
| 109 | ||
| 100 | 110 | async function load(src: string, format: string): Promise<Loaded> { |
| 101 | 111 | const response = await fetch(src, { credentials: "same-origin" }); |
| 102 | 112 | if (!response.ok) throw new Error(`the file answered ${response.status}`); |
| 103 | if (format === "stl" || format === "obj" || format === "ply" || format === "3mf") { | |
| 104 | const parsed: Parsed = | |
| 105 | format === "obj" | |
| 106 | ? objFromText(await response.text()) | |
| 107 | : format === "3mf" | |
| 108 | ? await parse3mf(new Uint8Array(await response.arrayBuffer())) | |
| 109 | : format === "ply" | |
| 110 | ? parsePly(new Uint8Array(await response.arrayBuffer())) | |
| 111 | : parseStl(new Uint8Array(await response.arrayBuffer())); | |
| 113 | if (format === "stl" || format === "obj" || format === "dae" || format === "ply" || format === "3mf") { | |
| 114 | const parsed = await parseFormat(format, response); | |
| 112 | 115 | const mesh = soup(parsed.positions); |
| 113 | 116 | // A printed part is modelled Z-up; three.js stands Y-up. |
| 114 | 117 | if (format === "stl" || format === "3mf") mesh.rotation.x = -Math.PI / 2; |
src/web/render/model3d.ts +5 −4
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | /** |
| 2 | * An STL, OBJ, PLY or glTF file as a part you can turn: a server-rendered frame, | |
| 2 | * An STL, OBJ, PLY, Collada or glTF file as a part you can turn: a server-rendered frame, | |
| 3 | 3 | * and the viewer (`model3d-client.ts`, with the vendored three.js) loaded |
| 4 | 4 | * only by the pages that carry one. |
| 5 | 5 | * |
| @@ -23,6 +23,7 @@ import type { BuiltAsset } from "../asset.ts"; | ||
| 23 | 23 | import { html, type Html } from "../html.ts"; |
| 24 | 24 | import { btn, empty, fileSize } from "../ui.ts"; |
| 25 | 25 | import { indexedRows } from "./mesh.ts"; |
| 26 | import { readDae } from "./collada.ts"; | |
| 26 | 27 | import { readObj } from "./obj.ts"; |
| 27 | 28 | import { indexedMesh } from "./model-facts.ts"; |
| 28 | 29 | import { readStl, STL_LIMIT, STL_TOO_BIG } from "./stl.ts"; |
| @@ -34,7 +35,7 @@ const ENTRY = Bun.fileURLToPath(new URL("./model3d-client.ts", import.meta.url)) | ||
| 34 | 35 | const VENDOR = join(import.meta.dir, "vendor", "three"); |
| 35 | 36 | |
| 36 | 37 | /** What the viewer reads each extension as. */ |
| 37 | const FORMATS: Readonly<Record<string, string>> = { stl: "stl", obj: "obj", ply: "ply", glb: "glb", gltf: "gltf", "3mf": "3mf" }; | |
| 38 | const FORMATS: Readonly<Record<string, string>> = { stl: "stl", obj: "obj", dae: "dae", ply: "ply", glb: "glb", gltf: "gltf", "3mf": "3mf" }; | |
| 38 | 39 | |
| 39 | 40 | const formatOf = (path: string): string => |
| 40 | 41 | FORMATS[path.slice(path.lastIndexOf(".") + 1).toLowerCase()] ?? "stl"; |
| @@ -45,7 +46,7 @@ export function model3d(input: RenderInput): Rendered { | ||
| 45 | 46 | btn(label, { type: "button", size: "sm", variant: "outline", extra: "js-only", pressed: false, value }); |
| 46 | 47 | // An OBJ or PLY the page read has its counts in the first paint; the viewer |
| 47 | 48 | // fills the same rows for a file it fetched itself. |
| 48 | const obj = readObj(input.path, input.body, input.size); | |
| 49 | const obj = readObj(input.path, input.body, input.size) ?? readDae(input.path, input.body, input.size); | |
| 49 | 50 | if (obj !== null && "fallback" in obj) return { lines: 0, content: html``, fallback: obj.fallback }; |
| 50 | 51 | const mesh = obj !== null ? (obj.mesh ?? null) : indexedMesh(input.path, input.body, input.size); |
| 51 | 52 | const rows = mesh === null ? undefined : indexedRows(mesh); |
| @@ -108,7 +109,7 @@ function sources(): string[] { | ||
| 108 | 109 | readdirSync(dir, { withFileTypes: true }) |
| 109 | 110 | .flatMap((e) => (e.isDirectory() ? walk(join(dir, e.name)) : [join(dir, e.name)])) |
| 110 | 111 | .sort(); |
| 111 | return [ENTRY, join(import.meta.dir, "mesh.ts"), join(import.meta.dir, "ply.ts"), ...walk(VENDOR)]; | |
| 112 | return [ENTRY, join(import.meta.dir, "mesh.ts"), join(import.meta.dir, "collada.ts"), join(import.meta.dir, "ply.ts"), ...walk(VENDOR)]; | |
| 112 | 113 | } |
| 113 | 114 | |
| 114 | 115 | let path: string | null = null; |
test/render-collada.test.ts added +92
| @@ -0,0 +1,92 @@ | ||
| 1 | /** Collada: a cube drawn from triangles and a polylist, the registry, and the fallbacks. */ | |
| 2 | ||
| 3 | import { describe, expect, test } from "bun:test"; | |
| 4 | import { DAE_BROKEN, DAE_LIMIT, DAE_TOO_BIG, daeFromText, parseCollada } from "../src/web/render/collada.ts"; | |
| 5 | import { fileKind } from "../src/web/render/kinds.ts"; | |
| 6 | import { FACTS_CAP, modelFacts } from "../src/web/render/model-facts.ts"; | |
| 7 | import { model3d } from "../src/web/render/model3d.ts"; | |
| 8 | ||
| 9 | const enc = (s: string): Uint8Array => new TextEncoder().encode(s); | |
| 10 | ||
| 11 | const CUBE = "0 0 0 1 0 0 1 1 0 0 1 0 0 0 1 1 0 1 1 1 1 0 1 1"; | |
| 12 | const dae = (primitives: string, extra = ""): string => | |
| 13 | `<?xml version="1.0"?><COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1"> | |
| 14 | <asset>${extra}</asset><library_geometries><geometry id="g"><mesh> | |
| 15 | <source id="pos"><float_array id="pa" count="24">${CUBE}</float_array> | |
| 16 | <technique_common><accessor source="#pa" count="8" stride="3"/></technique_common></source> | |
| 17 | <vertices id="vtx"><input semantic="POSITION" source="#pos"/></vertices> | |
| 18 | ${primitives} | |
| 19 | </mesh></geometry></library_geometries></COLLADA>`; | |
| 20 | ||
| 21 | const TRIS = `<triangles count="2"><input semantic="VERTEX" source="#vtx" offset="0"/><p>0 1 2 0 2 3</p></triangles>`; | |
| 22 | const POLY = `<polylist count="1"><input semantic="VERTEX" source="#vtx" offset="0"/><input semantic="NORMAL" source="#n" offset="1"/><vcount>4</vcount><p>4 0 5 0 6 0 7 0</p></polylist>`; | |
| 23 | ||
| 24 | const input = (path: string, body: Uint8Array, size = body.length) => | |
| 25 | ({ path, body, size, media: "/m", download: "/d" }) as unknown as Parameters<typeof model3d>[0]; | |
| 26 | ||
| 27 | describe("parseCollada", () => { | |
| 28 | test("triangles and a polylist are one mesh", () => { | |
| 29 | const m = parseCollada(dae(TRIS + POLY)); | |
| 30 | expect([m.vertices, m.faces, m.triangles, m.dropped]).toEqual([8, 3, 4, 0]); | |
| 31 | expect(m.box?.size).toEqual([1000, 1000, 1000]); | |
| 32 | }); | |
| 33 | test("unit meter scales to millimetres", () => { | |
| 34 | expect(parseCollada(dae(TRIS, '<unit meter="0.01"/>')).box?.size).toEqual([10, 10, 10]); | |
| 35 | }); | |
| 36 | test("a hostile index is dropped, not read", () => { | |
| 37 | const m = parseCollada(dae(TRIS.replace("0 2 3", "0 2 99"))); | |
| 38 | expect([m.faces, m.dropped]).toEqual([1, 1]); | |
| 39 | }); | |
| 40 | test("malformed input throws a MeshError, never anything else", () => { | |
| 41 | for (const bad of ["", "<COLLADA>", "plain text", dae(""), dae(TRIS).replace(/<\/mesh>/, ""), dae(TRIS).replace("0 0 0 1", "x 0 0 1")]) | |
| 42 | expect(() => parseCollada(bad)).toThrow(); | |
| 43 | }); | |
| 44 | }); | |
| 45 | ||
| 46 | describe("registry and page", () => { | |
| 47 | test("the kind needs a COLLADA root", () => { | |
| 48 | expect(fileKind("a.dae", enc(dae(TRIS)))).toBe("model3d"); | |
| 49 | expect(fileKind("a.dae", enc("hello"))).toBe("text"); | |
| 50 | }); | |
| 51 | test("the page carries the counts, escaped, in the first paint", () => { | |
| 52 | const out = model3d(input("x.dae", enc(dae(TRIS)))).content.text; | |
| 53 | expect(out).toContain('data-format="dae"'); | |
| 54 | expect(out).toContain("<dd>8</dd>"); | |
| 55 | expect(out).toContain("<dd>2</dd>"); | |
| 56 | }); | |
| 57 | test("a broken or oversized file keeps the source view", () => { | |
| 58 | expect(model3d(input("x.dae", enc("<COLLADA>"))).fallback).toBe(DAE_BROKEN); | |
| 59 | expect(model3d(input("x.dae", new Uint8Array(0), DAE_LIMIT + 1)).fallback).toBe(DAE_TOO_BIG); | |
| 60 | }); | |
| 61 | test("the terminal's facts", () => { | |
| 62 | expect(modelFacts("x.dae", enc(dae(TRIS)), 100).facts).toContain("2 triangles"); | |
| 63 | expect(modelFacts("x.dae", enc("nope"), 4).facts).toBe("not a readable DAE file"); | |
| 64 | }); | |
| 65 | }); | |
| 66 | ||
| 67 | describe("hostile and oversize input", () => { | |
| 68 | test("100k unclosed openers finish fast and fall back", () => { | |
| 69 | for (const tag of ["<mesh>", "<source>", "<vertices>", "<triangles>", "<p>", "<input ", "<!--", "<![CDATA["]) { | |
| 70 | const body = `<COLLADA>${tag.repeat(100_000)}`; | |
| 71 | const t = performance.now(); | |
| 72 | expect(() => parseCollada(body)).toThrow(); | |
| 73 | expect(performance.now() - t).toBeLessThan(500); | |
| 74 | } | |
| 75 | const inner = dae("").replace("</mesh>", "") + "<source>".repeat(100_000); | |
| 76 | const t = performance.now(); | |
| 77 | expect(() => parseCollada(inner)).toThrow(); | |
| 78 | expect(performance.now() - t).toBeLessThan(500); | |
| 79 | }); | |
| 80 | ||
| 81 | test("daeFromText refuses over the limit and junk", () => { | |
| 82 | expect(() => daeFromText("x".repeat(DAE_LIMIT + 1))).toThrow(DAE_TOO_BIG); | |
| 83 | expect(() => daeFromText("junk")).toThrow(DAE_BROKEN); | |
| 84 | expect(daeFromText(dae(TRIS)).faces).toBe(2); | |
| 85 | }); | |
| 86 | ||
| 87 | test("the terminal states the size and does not parse a file over its cap", () => { | |
| 88 | const big = enc("x".repeat(FACTS_CAP + 1)); | |
| 89 | expect(modelFacts("x.dae", big, big.length).facts).not.toContain("triangles"); | |
| 90 | expect(modelFacts("x.dae", enc(`<COLLADA>${"<mesh>".repeat(100_000)}`), 600_000).facts).toBe("not a readable DAE file"); | |
| 91 | }); | |
| 92 | }); |
test/render-kinds.test.ts +1
| @@ -51,6 +51,7 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = { | ||
| 51 | 51 | ndjson: [enc("{\"a\":1}\n"), "csv", "application/octet-stream"], |
| 52 | 52 | gltf: [enc('{"asset":{}}'), "model3d", "application/octet-stream"], |
| 53 | 53 | obj: [enc("v 0 0 0\n"), "model3d", "application/octet-stream"], |
| 54 | dae: [enc("<?xml version=\"1.0\"?><COLLADA version=\"1.4.1\">"), "model3d", "application/octet-stream"], | |
| 54 | 55 | json: [enc("{}"), "config", "application/octet-stream"], |
| 55 | 56 | jsonc: [enc("{}"), "config", "application/octet-stream"], |
| 56 | 57 | yaml: [enc("a: 1\n"), "config", "application/octet-stream"], |
new above
offline
Quadratic on unclosed <mesh> openers (and the same for the <source>, <vertices> and primitive scans below). The header's claim that every scan walks the text once is false. Use a forward-only scanner and add a hostile-input timing test.