diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 0f9928f4..3ceb0e1d 100755 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -52,7 +52,7 @@ jobs: strategy: fail-fast: false matrix: - target: [stepbom, swpart, nxpart, invpart, cadrefs, bomtable, thumbnail, scdesign, textindex, htmltext, mesh, mesh_step, cadformat, resultscan, solversummary] + target: [stepbom, swpart, nxpart, invpart, cadrefs, bomtable, thumbnail, scdesign, textindex, htmltext, mesh, mesh_step, e57, cadformat, resultscan, solversummary] steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master diff --git a/CHANGELOG.md b/CHANGELOG.md index f505b8ce..a5cca3fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,31 @@ see the notices in the README. ### Added +- **3D preview of E57 point clouds** (#373). Laser-scanner exports (`.e57`, + ASTM E2807) open in the viewer like LAS: every scan is placed by its pose + (rotation and translation), so multi-station scans line up; cartesian or + spherical coordinates, float or scaled-integer values, colours scaled by + `colorLimits`, otherwise the intensity as a colour-mapped field; points + marked invalid, embedded images and unknown fields are left out; metres + become millimetres. The CRC-32C of every 1 KiB page is checked first, so a + damaged file is refused with a message instead of shown wrong. Own bounded + reader in the isolated preview process (`src/mesh/e57.rs`, no new crate), + fuzz target `e57`; research page *3D preview of E57 point clouds*. +- **Thinned point clouds say so.** A cloud with more points than the preview + shows (3 million) is thinned evenly, and the line below the viewer now says + *thinned for the preview from N points* – E57, LAS, PTS/XYZ and point-only + OFF files (flag 8 of the `TCMESH01` mesh). Previews cached before keep + their old line until the cache is rebuilt. +- **E57 and large scans:** E57 shares `TEAMCRAFT_PREVIEW_MAX_MESH_MB` + (256 MB); the admin guide now says to raise it, and the preview memory limit + to about the file size plus 100 MB, to preview larger scans. + +### Fixed + +- PTS/XYZ files whose point count was underestimated from their first lines + failed with *point cloud not thinned out*; the reader now drops every second + kept point and doubles its stride when it reaches the budget, so the kept + points stay evenly spread over the whole file. - **Desktop: one *Local changes* list for the whole working folder** (#416): a worklist section next to *New on this computer* lists every file of the working folder that is modified, outdated, in conflict, new (a companion diff --git a/CLAUDE.md b/CLAUDE.md index 5311c7b5..d9fe2123 100755 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -142,7 +142,7 @@ src/assistant.rs built-in assistant ("Ask TeamCraft"): tool loop over src/llm src/pagecontext.rs the page the user is on (kind, ids, view, rule, query, rows shown): parsing and caps only – ids are hints src/vault.rs content-addressed file storage (objects/ab/cd/) src/httprange.rs Range / If-Range of file downloads (ETag = SHA-256, 206 / 416): resumable downloads -src/mesh.rs pure-Rust 3D readers (STL, OBJ, PLY, OFF, 3MF, AMF, glTF, 3DS, PTS/XYZ/LAS, STEP via truck, NX parts via their JT stream: mesh/jt.rs, SOLIDWORKS parts via their display lists: mesh/sw.rs, Inventor parts via their graphics segment: mesh/inventor.rs, CATIA V5 parts via their CGR data: mesh/catia.rs, Creo parts tessellated from their B-rep: mesh/creo/ (assemblies: mesh/creo/asm.rs, NeuAsmSld), Fusion designs via their display scene: mesh/f3d.rs, all + PN refinement mesh/pn.rs, +src/mesh.rs pure-Rust 3D readers (STL, OBJ, PLY, OFF, 3MF, AMF, glTF, 3DS, PTS/XYZ/LAS, E57 scans placed by their pose with page CRCs checked: mesh/e57.rs, STEP via truck, NX parts via their JT stream: mesh/jt.rs, SOLIDWORKS parts via their display lists: mesh/sw.rs, Inventor parts via their graphics segment: mesh/inventor.rs, CATIA V5 parts via their CGR data: mesh/catia.rs, Creo parts tessellated from their B-rep: mesh/creo/ (assemblies: mesh/creo/asm.rs, NeuAsmSld), Fusion designs via their display scene: mesh/f3d.rs, all + PN refinement mesh/pn.rs, Rhino .3dm: stored meshes, SubD subdivided, blocks placed: mesh/rhino.rs, SketchUp .skp: faces triangulated (mesh/earcut.rs), components placed: mesh/sketchup.rs, 3–2020 files via vendor/openskp, stand-alone JT 10 files with their scene graph: mesh/jt10.rs, JT 9.5 assemblies through the same diff --git a/README.md b/README.md index b5b70975..6dc4a6cd 100755 --- a/README.md +++ b/README.md @@ -218,6 +218,7 @@ end-to-end tests against a real PostgreSQL. Rhino models (`.3dm`, SubD included), SketchUp models (`.skp`, SketchUp 3 to today), JT files with their whole assembly, Fusion designs (`.f3d`), STL, OBJ, PLY, 3MF, glTF, point clouds + (PTS, XYZ, LAS and laser-scanner E57 with every scan placed by its pose) and more. - **CAD thumbnails** – the preview images stored in Inventor drawings and Solid Edge files; NX, SOLIDWORKS, Inventor, CATIA, Creo, Rhino, SketchUp, JT and diff --git a/desktop/README.md b/desktop/README.md index 0a422ef1..e11c5fd5 100755 --- a/desktop/README.md +++ b/desktop/README.md @@ -28,6 +28,7 @@ TeamCraft server – it is a client, not an offline copy. | Right-click menu | On items and files in the navigator, Home *Files* / *All items* / *Structure*, the worklist's check-outs and the Graph cards (rows with `data-item` + `data-rev`, one listener in `js/item-menu.js`): *Check out and open* / *Open in CAD*, *Check out*, *Check in…*, *Get…*, *Show in folder*, *Copy number*, *Where used*, *Request change…*, *Open in browser*; the entries and the tooltip of a disabled one come from the toolbar's rules (`js/item-menu-rules.js`, tested by `scripts/desktop-item-menu.test.mjs`); Shift+F10 / context-menu key, arrows, `Esc` – #417 | | Toolbar | Below the tab strip, acting on the active tab: grouped buttons that keep their place (revision: Lock · Work · Lifecycle · Collaborate; change: Review · Lifecycle · Collaborate; request: Triage · Requester · Collaborate), the **next step highlighted** (*Check out*, *Check in…* with local changes, *Release…* on a clean check-out, *Revise* when released, *Submit for review* / *Approve change* on a change), greyed-out buttons with a tooltip saying why (*Check in…* has an upload arrow, never the download arrow of *Get…*, #409; *Edit attributes* as in the web UI, #410), rare actions (*Pack and Go…*, *Open in browser*, *Refresh*, *Mark obsolete…*) in **More ▾** – keyboard: `Enter`/`Space`/`↓` open, arrows move, `Esc` closes | | Tab order | Drag a tab to move it (pointer events, an insertion bar shows the landing place, the strip scrolls at its edges, `Esc` cancels; a plain click still activates, a dragged tab keeps its state and is not activated). Keyboard: arrow keys, `Home`, `End` move the focus between the tabs (WAI-ARIA tabs, roving tabindex, `Enter`/`Space` activates), `Ctrl+Shift+PageUp/PageDown` move the active tab. Right click (or the menu key): *Move to start*, *Move to end*, *Close*, *Close others*, *Close tabs to the right*. The order is kept while the app runs (open tabs are not restored on start). Rules in `ui/js/tab-order.js`, tested by `scripts/desktop-tab-order.test.mjs` (`node`); the dragging itself is checked by hand | +| Revision tabs | Overview (with *At a glance*: the preview image from the CAD file, files, BOM lines, where used, references, change orders, open requests – and a link to the similar parts in the browser), Files (versions, restore, open), Structure (multi-level BOM, revision rules, roll-up), Where used, References, **Graph** (see below), Changes, History, **3D viewer** (STEP, meshes, point clouds incl. E57 scans – converted by the server; no *Export STL* for point clouds, a thinned cloud says so below the view), Workspace | | Revision tabs | Overview (with *At a glance*: the preview image from the CAD file, files, BOM lines, where used, references, change orders, open requests – and a link to the similar parts in the browser), Files (versions, restore, open), Structure (multi-level BOM, revision rules, roll-up; under your check-out *Add line…*, quantities and *Remove*), Where used, References, **Graph** (see below), Changes, History, **3D viewer** (STEP, meshes, point clouds – converted by the server), Workspace | | Graph | A navigable reference/BOM graph around the revision: the focused item in the middle, its BOM children and references below, the assemblies that use it above. Node **colour** = lifecycle state, **size** and the ⚙ badge = the item's own BOM complexity, **×n in the top-left corner** = how many instances of that part or sub-assembly the assembly contains (summed over its BOM lines, ×1 included). Every node is clickable and takes the tab to that item – a sub-assembly shows its own graph, anything else its overview, the item in the middle its own overview – with a **back control that stays in the same place** (the left of the sub-tab row) and leads back the way you came, one step per click; `Ctrl`/`⌘`+click opens a node in a tab of its own. Mouse-wheel zooms on the cursor; drag to pan; the view fits itself while details load until you zoom or pan, a double-click on the background fits it again. More than 8 neighbours on one side are laid out in rows; above 48 only the first 48 are fetched for preview and complexity (one request each), the rest keep a basic card. Preview images and filenames on the nodes; pure SVG, no external engine | | Working folder | One folder per project group that **mirrors the folder structure of the files** (`///`, the folder is stored with every file on the server), one copy of each file – the revision is metadata in `/.teamcraft/state.json` (item, revision, file id, version, SHA-256, checked out). Files you have not checked out are **read-only** on disk; *Check out* takes the lock and makes them writable; *Check in…* uploads the chosen files as new versions, releases the lock in one step and makes them read-only again (files above 32 MiB go first as chunked, resumable uploads, then join the same check-in transaction). The check-in dialog shows the progress, and **Cancel** stops the check-in until its last byte is sent – before the next STEP export, between two chunks (the upload sessions are discarded, `DELETE /uploads/{id}`) or half-way through the streamed request with the small files: nothing is stored, the revision stays checked out (`src/abortable.rs`). Every check-in names the version each file is based on, so the server refuses (409) to overwrite a version somebody else checked in meanwhile. The Workspace tab shows *up to date* / *modified* / *outdated* / *conflict* / *new* / *missing* / *name clash* per file (from the server's file status) with its path, read-only flag and the lock owner. Two items with the same folder and file name are reported, never overwritten. Lock and backup files of the CAD programs are skipped; a SolidCraft design that is open in SolidCraft (a fresh `.~.lock` beside it, `src/cadlock.rs`) is marked *Open in SolidCraft* with the computer and user, and the check-in dialog warns that unsaved changes there are not checked in; Creo iterations count as one file. A tracked revision the server no longer shows (you left a restricted project group) is listed as *No longer accessible*: its local copies stay untouched and are never synced again – delete them yourself if you must In *Check in…*, a new part or assembly file next to a revision that has a model already is offered unticked, with *New item from this file* (#359). *Update the BOM from the CAD file* in *Check in…* (#407): ticked by default every time, shown when the server reports a structure file (`bom_structure` of `file-status`), the item is an assembly, or a file is an assembly or a SolidCraft design (`js/checkin-bom.js`, tested by `scripts/desktop-checkin-bom.test.mjs`); sends `bom_from_references` with the check-in (never with *Park*) and adds the server's `bom` summary to the result | diff --git a/desktop/ui/js/revision.js b/desktop/ui/js/revision.js index 8aa54ecd..9b2e3488 100755 --- a/desktop/ui/js/revision.js +++ b/desktop/ui/js/revision.js @@ -330,7 +330,7 @@ export function revOverview(tab, el) { dt("Created"), dd(fmtDate(rev.created_at) + " · " + rev.created_by_name), dt("Last modified"), dd(fmtDate(rev.updated_at)), dt("Released"), dd(fmtDate(rev.released_at)), - dt("Similar parts"), dd(d.files.some(function (f) { var p = previewFormat(f); return p && ["pts", "xyz", "las"].indexOf(p) < 0; }) ? h("button.link", { type: "button", title: "Parts with a similar 3D shape (web UI)", on: { click: function () { call("open_web", { path: "/revisions/" + rev.id + "#similar" }).catch(function (e) { toast(errorText(e), "error"); }); } } }, "Compare the shape in the browser") : "— (no STEP or mesh file)") + dt("Similar parts"), dd(d.files.some(function (f) { var p = previewFormat(f); return p && ["pts", "xyz", "las", "e57"].indexOf(p) < 0; }) ? h("button.link", { type: "button", title: "Parts with a similar 3D shape (web UI)", on: { click: function () { call("open_web", { path: "/revisions/" + rev.id + "#similar" }).catch(function (e) { toast(errorText(e), "error"); }); } } }, "Compare the shape in the browser") : "— (no STEP or mesh file)") ]); var states = ["in_work", "in_review", "released", "obsolete"]; var next = { diff --git a/desktop/ui/js/workspace.js b/desktop/ui/js/workspace.js index fcf4be8e..294e1df9 100755 --- a/desktop/ui/js/workspace.js +++ b/desktop/ui/js/workspace.js @@ -46,7 +46,7 @@ export function revViewer(tab, el) { var resetBtn = h("button.small", { type: "button", title: "Back to the initial view (double-click)" }, "Reset view"); var upBtn = h("button.small", { type: "button", title: "Switch between Z-up and Y-up models" }, "Z up"); // STL export of STEP/3MF/… models (e.g. for 3D printing); saved through a native dialog in Rust. - var noExport = ["stl", "pts", "xyz", "las"].indexOf(previewFormat(current)) !== -1; + var noExport = ["stl", "pts", "xyz", "las", "e57"].indexOf(previewFormat(current)) !== -1; var stlBtn = noExport ? null : h("button.small", { type: "button", disabled: true, title: "Save the tessellated model as STL (units as in the file, usually mm)", on: { diff --git a/docs/OPEN_WORK.md b/docs/OPEN_WORK.md index 06834f4a..493b233d 100755 --- a/docs/OPEN_WORK.md +++ b/docs/OPEN_WORK.md @@ -589,8 +589,12 @@ real files and belong to section 3 once such files are at hand. - [ ] Test real STEP exports of the CAD programs, assembly placements (`mapped_item` – parts of an assembly can overlap) and length units -- [ ] Readers for IGES, BREP, Parasolid, FBX, DAE, USD and E57 – recognised, not previewed (no pure-Rust readers - yet; candidate: `e57` crate). JT 9 and 10 are read with their scene graph (`src/mesh/jt10.rs`); open there: JT 8, shattered +- [x] E57 point clouds (#373): own bounded reader `src/mesh/e57.rs` – page CRC-32C checked first, every scan + placed by its pose, cartesian/spherical, float/scaled integer, colour or intensity, invalid points dropped, thinned + evenly with a note in the viewer. Open: an openly licensed real scan as a test file (the tests build synthetic + files), per-scan grouping in the viewer, colours from embedded images +- [ ] Readers for IGES, BREP, Parasolid, FBX, DAE and USD – recognised, not previewed (no pure-Rust readers + yet). JT 9 and 10 are read with their scene graph (`src/mesh/jt10.rs`); open there: JT 8, shattered JT files (parts in other `.jt` files), a real JT 9.5 assembly as a test file (the tests build synthetic ones) – no openly licensed test files yet - [x] Creo assemblies from their parts (`src/mesh/creo/asm.rs`, section `NeuAsmSld`, components by `.prt` / diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 7b67666c..f492794c 100755 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -101,4 +101,5 @@ - [SolidCraft designs](research/solidcraft-design.md) - [3D preview of SolidCraft designs without an export](research/solidcraft-3d-preview.md) - [Talking to the desktop app from inside SolidCraft](research/solidcraft-bridge.md) + - [3D preview of E57 point clouds](research/e57-preview.md) - [CAD add-ins: Inventor and Siemens NX first](research/cad-addins.md) diff --git a/docs/src/admin/configuration.md b/docs/src/admin/configuration.md index ab837f09..df46094b 100755 --- a/docs/src/admin/configuration.md +++ b/docs/src/admin/configuration.md @@ -143,6 +143,11 @@ results are stored as they are, never parsed fully – see | `TEAMCRAFT_PREVIEW_MAX_STEP_MB` | `256` | largest STEP file (tessellation needs a multiple of the file size) | | `TEAMCRAFT_PREVIEW_MAX_MEMORY_MB` | `1024` | address space of the preview process, `0` = unlimited | +E57 laser scans (`.e57`) count as point clouds under `TEAMCRAFT_PREVIEW_MAX_MESH_MB`; real scans are often larger than +256 MB and are then not previewed. When you raise the cap for them, keep `TEAMCRAFT_PREVIEW_MAX_MEMORY_MB` at least about +the largest file size plus 100 MB: the E57 reader holds the whole file in memory to check the checksum of every page +before the cloud is thinned to 3 million points. + The same process limits protect the text extraction of PDF and HTML reports (`teamcraft text-extract`: at most 32 MB per PDF and 100 pages, the first 16 MB of an HTML file, 60 s, the memory limit below) and the spreadsheets of BOM and result imports (XLSX, XLSM, XLSB, XLS, diff --git a/docs/src/dev/fuzzing.md b/docs/src/dev/fuzzing.md index b821f8ff..714aa333 100755 --- a/docs/src/dev/fuzzing.md +++ b/docs/src/dev/fuzzing.md @@ -20,8 +20,11 @@ The targets are `stepbom`, `swpart`, `nxpart`, `invpart` (Inventor segments, par `creopart` (the Creo B-rep container, tagged format and tessellation), `cadrefs`, `bomtable`, `thumbnail`, `scdesign` (SolidCraft designs: document, linked designs, thumbnail), `textindex`, `htmltext` (HTML reports and the charset detection of text files), `mesh` (STL, OBJ, PLY, OFF, 3MF, AMF, glTF, 3DS, -points, LAS, VTK legacy and XML, CalculiX FRD) and `mesh_step` (the STEP -tessellation through `truck`, kept apart because it is slow), `cadformat` (the +points, LAS, E57, VTK legacy and XML, CalculiX FRD), `mesh_step` (the STEP +tessellation through `truck`, kept apart because it is slow), `e57` (E57 point +clouds: the bytes as they are, then cut to whole pages with every page checksum +recomputed, so the fuzzer gets past the CRC-32C to the XML, the packets and the +bit-packed streams; seed `fuzz/seeds/e57/three-points.e57`), `cadformat` (the format detection over a file's first 1024 bytes) and `resultscan` (the extraction templates and the exchange file) and `solversummary` (the solver summary of Fluent, Nastran and STAR-CCM+ output). diff --git a/docs/src/dev/threat-model.md b/docs/src/dev/threat-model.md index dcd84670..a497a964 100755 --- a/docs/src/dev/threat-model.md +++ b/docs/src/dev/threat-model.md @@ -136,9 +136,11 @@ enial of service, **E**levation of privilege. | Threat | STRIDE | Mitigation | Tests | Status | |---------------------------------------------------------------------------|--------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------| -| A crafted mesh, STEP, PDF or result file crashes or hangs the server (A3) | D | 3D conversion (`teamcraft preview-mesh`) and the text of PDF and HTML reports (`teamcraft text-extract --format pdf` or `html`) run in a child process with a wall-time limit, `kill_on_drop`, size caps per format and two at a time (`src/preview.rs` `run_worker`, `src/pdftext.rs`; HTML: the first 16 MB are read, at most 256 open elements are tracked, 200 000 characters out, `src/htmltext.rs`); a failure is cached, not retried | `src/preview.rs` `failures_of_the_conversion_process_are_explained`; `tests/parser_robustness.rs`; `tests/preview_limits.rs` `the_html_text_process_is_bounded` | mitigated on Linux and macOS | +| A crafted mesh, STEP, PDF or result file crashes or hangs the server (A3) | D | 3D conversion (`teamcraft preview-mesh`) and the text of PDF and HTML reports (`teamcraft text-extract --format pdf` or `html`) run in a child process (among them the E57 point-cloud reader `src/mesh/e57.rs`: every page CRC-32C checked before parsing, XML at most 64 MiB, 1 000 000 elements, depth 64, packets checked against the section, at most 3 million points kept) with a wall-time limit, `kill_on_drop`, size caps per format and two at a time (`src/preview.rs` `run_worker`, `src/pdftext.rs`; HTML: the first 16 MB are read, at most 256 open elements are tracked, 200 000 characters out, `src/htmltext.rs`); a failure is cached, not retried | `src/preview.rs` `failures_of_the_conversion_process_are_explained`; `tests/parser_robustness.rs`; `tests/preview_limits.rs` `the_html_text_process_is_bounded` | mitigated on Linux and macOS | | Memory exhaustion in the child | D | `RLIMIT_AS` 1 GiB on Unix, a job object with `JOB_OBJECT_LIMIT_PROCESS_MEMORY` (and `KILL_ON_JOB_CLOSE`) on Windows, which the child puts itself into (`src/preview.rs` `limit_memory`, GHSA-7q9q-g6rr-pc58); the same limit for the `text-extract` child (PDF, HTML, spreadsheets); a 3MF package entry may claim up to 2 GiB (`src/mesh.rs` `zip_entry`), bounded by the limit | `src/preview.rs` `windows_job_object_limits_memory` (Windows CI, nextest) | mitigated (F11; a smaller 3MF cap is open) | | A compromised child reads the server's secrets | I | the children start with a cleared environment (`env_clear` in `preview.rs`, `pdftext.rs`); no sandbox beyond the process boundary | – | mitigated (F12) | +| Parsers that run inside the server process | D | CAD reference scan (`src/cadrefs.rs`, with `nxpart`, `swpart`), plain text index, thumbnails, BOM import (`stepbom`, `bomtable`) run on blocking threads with their own caps: scan 32 MiB, text 4 MiB / 200 000 characters plus a 64 KiB tail of a larger plain-text file (at most a quarter of the characters, only after a text head, no NUL), result-template scan 2 MB head plus 2 MB tail of every scannable upload above 2 MB (up to 4 MB held per file during a check-in, also for files no template reads), thumbnail stream 8 MiB, tables 20 MiB, STEP 200 MiB, CATIA product structure 64 MiB (`src/catprod.rs`, assembly previews), Creo assembly structure 64 MiB (`src/mesh/creo/asm.rs`, section sizes bounded by the container reader), Deflate sections bounded and CRC-checked (`src/swpart.rs`). A panic ends only the blocking task. Spreadsheets of BOM and result imports (XLSX, XLSM, XLSB, XLS, ODS) are **not** parsed in the server process: the `text-extract` child reads them (`--format sheet`, memory and time limits of the previews, `src/bomtable.rs` `read_grid_isolated`, `run_sheet_job`) after a ZIP check of the declared and the really unpacked size (256 MiB, 10 000 entries, `check_unpacked`); the grid it returns is bounded (rows, 512 columns, 10 000 characters per cell). A dense cell range asked for by two cells far apart only hits the child's memory limit (GHSA-54vc-vgp2-8whr) | `tests/parser_robustness.rs` `damaged_bom_tables_never_panic`, `damaged_containers_never_panic`, `thumbnail_extraction_survives_damaged_files`, `claimed_sizes_beyond_the_file_are_refused`; `src/bomtable.rs` `zip_bombs_are_refused_before_parsing`, `sheet_job_writes_bounded_json_rows`, `isolated_reading_matches_in_process_reading` | mitigated (F13 fixed) | +| Panics on hostile bytes | D | `catch_unwind` around third-party readers (truck STEP, glTF, pdf_oxide); sixteen `cargo fuzz` targets (`creopart` and `e57` included) run weekly (`fuzz/`, `.github/workflows/fuzz.yml`, [Fuzzing](fuzzing.md)) – the workflow built no target until `fix/fuzz-build-target` (it defaulted to the musl triple); the seed and fixture corpus runs in every CI run. `#![deny(clippy::unwrap_used, expect_used, indexing_slicing, panic, unreachable)]` on the readers of untrusted files (`mesh`, `simmesh`, `swpart`, `nxpart`, `invpart`, `invplace`, `stepbom`, `bomtable`, `cadrefs`, `textindex`, `htmltext`, `thumbnail`, `resultscan`, `cadformat`; #106, #108), which fixed a 3DS and a reference-scan panic. Not fuzzed: `simmesh`, `pdftext`; `pdftext` is not under the lint | `tests/parser_corpus.rs` `the_corpus_never_panics_a_reader`; `tests/parser_robustness.rs`; `src/mesh.rs` `three_ds_list_chunks_without_their_count`; `src/cadrefs.rs` `a_non_ascii_letter_in_the_extension_does_not_panic` | partial (F14) | | Parsers that run inside the server process | D | CAD reference scan (`src/cadrefs.rs`, with `nxpart`, `swpart`), plain text index, thumbnails, BOM import (`stepbom`, `bomtable`) run on blocking threads with their own caps: scan 32 MiB, text 4 MiB / 200 000 characters plus a 64 KiB tail of a larger plain-text file (at most a quarter of the characters, only after a text head, no NUL), result-template scan 2 MB head plus 2 MB tail of every scannable upload above 2 MB (up to 4 MB held per file during a check-in, also for files no template reads), thumbnail stream 8 MiB, tables 20 MiB, STEP 200 MiB, CATIA product structure 64 MiB (`src/catprod.rs`, assembly previews), Creo assembly structure 64 MiB (`src/mesh/creo/asm.rs`, section sizes bounded by the container reader), Deflate sections bounded and CRC-checked (`src/swpart.rs`). SolidCraft design properties (`src/scdesign.rs` `properties`, #367): the design's `document.json` (16 MiB, stored or Deflate entries with size and CRC checked) is parsed on a blocking thread, only seven text keys kept, 500 characters each; an unreadable design is stored without properties, never refused. The values are shown escaped and handed to MCP clients marked as untrusted data. A panic ends only the blocking task. Spreadsheets of BOM and result imports (XLSX, XLSM, XLSB, XLS, ODS) are **not** parsed in the server process: the `text-extract` child reads them (`--format sheet`, memory and time limits of the previews, `src/bomtable.rs` `read_grid_isolated`, `run_sheet_job`) after a ZIP check of the declared and the really unpacked size (256 MiB, 10 000 entries, `check_unpacked`); the grid it returns is bounded (rows, 512 columns, 10 000 characters per cell). A dense cell range asked for by two cells far apart only hits the child's memory limit (GHSA-54vc-vgp2-8whr) | `tests/parser_robustness.rs` `damaged_bom_tables_never_panic`, `damaged_containers_never_panic`, `thumbnail_extraction_survives_damaged_files`, `claimed_sizes_beyond_the_file_are_refused`; `src/bomtable.rs` `zip_bombs_are_refused_before_parsing`, `sheet_job_writes_bounded_json_rows`, `isolated_reading_matches_in_process_reading` | mitigated (F13 fixed) | | Panics on hostile bytes | D | `catch_unwind` around third-party readers (truck STEP, glTF, pdf_oxide); fifteen `cargo fuzz` targets (`creopart` included) run weekly (`fuzz/`, `.github/workflows/fuzz.yml`, [Fuzzing](fuzzing.md)) – the workflow built no target until `fix/fuzz-build-target` (it defaulted to the musl triple); the seed and fixture corpus runs in every CI run. `#![deny(clippy::unwrap_used, expect_used, indexing_slicing, panic, unreachable)]` on the readers of untrusted files (`mesh`, `simmesh`, `swpart`, `nxpart`, `invpart`, `invplace`, `stepbom`, `bomtable`, `cadrefs`, `textindex`, `htmltext`, `thumbnail`, `resultscan`, `cadformat`; #106, #108), which fixed a 3DS and a reference-scan panic. Not fuzzed: `simmesh`, `pdftext`; `pdftext` is not under the lint | `tests/parser_corpus.rs` `the_corpus_never_panics_a_reader`; `tests/parser_robustness.rs`; `src/mesh.rs` `three_ds_list_chunks_without_their_count`; `src/cadrefs.rs` `a_non_ascii_letter_in_the_extension_does_not_panic` | partial (F14) | | XML entity expansion / external entities | D, I | quick-xml (3MF, AMF, VTU/VTP, SOLIDWORKS component tree) neither loads DTDs nor expands custom entities | `tests/parser_robustness.rs` `component_trees_in_broken_xml_never_panic` (no DOCTYPE payload) | mitigated; no explicit test | diff --git a/docs/src/guide/desktop.md b/docs/src/guide/desktop.md index b5195fb0..43f788a9 100755 --- a/docs/src/guide/desktop.md +++ b/docs/src/guide/desktop.md @@ -330,7 +330,8 @@ account under a random computer name and can look at everything but change nothing. The app uses the same skins and 3D viewer as the web interface; the models are converted by the server, and *Loading* or the reason a model cannot be shown appears on the canvas of -the *3D viewer* tab (see [Files](files.md)). *Settings → Appearance*: *TeamCraft* (the +the *3D viewer* tab (see [Files](files.md)); point clouds (PTS, XYZ, LAS, E57) have no +*Export STL*, and a thinned cloud says so below the view. *Settings → Appearance*: *TeamCraft* (the default) follows the light or dark appearance of the operating system and switches with it, *TeamCraft Light* and *TeamCraft Dark* stay fixed, the distribution skins are dark. *Settings → Language*: *As the system* (the diff --git a/docs/src/guide/files.md b/docs/src/guide/files.md index 20c1e073..d21aa9a9 100755 --- a/docs/src/guide/files.md +++ b/docs/src/guide/files.md @@ -92,7 +92,7 @@ has the same notes under `/api/v1/file-versions/{id}/annotations`. | | Fusion designs (`.f3d`) – the display mesh Fusion stores | | Visualisation | JT (`.jt`): JT 10 parts and whole assemblies, placed; JT 9 as NX writes it | | Meshes | STL, OBJ, PLY, OFF, 3MF (incl. components), AMF, glTF / GLB, 3DS | -| Point clouds | PTS, XYZ, LAS (uncompressed), PLY and OBJ without faces | +| Point clouds | PTS, XYZ, LAS (uncompressed), E57 (every scan placed by its pose, colour or intensity), PLY and OBJ without faces | | Simulation results | VTK (`.vtk`), VTU, VTP, CalculiX FRD – coloured by result fields | The server converts a file **once**, in a separate process with a time limit, @@ -116,6 +116,12 @@ When a STEP preview shows only part of the model, the line below the viewer says **partial preview: N of M faces** – the missing faces use geometry the kernel cannot tessellate. Details: [STEP in the 3D preview](../reference/formats.md#step-in-the-3d-preview). +Point clouds with more than 3 million points are thinned out evenly (over all +scans of an E57 file); the line below the viewer then says **thinned for the +preview from N points**. An E57 file whose page checksums do not match is +refused with a message instead of being shown wrong. Details: +[E57 in the 3D preview](../reference/formats.md#e57-in-the-3d-preview). + Simulation results show the outer surface of the mesh with a colour scale (viridis), the range of the field above the canvas and, when the file has several fields, a selector – see [Simulations](simulation.md#results-in-3d). diff --git a/docs/src/reference/architecture.md b/docs/src/reference/architecture.md index 721769ed..b7680a48 100755 --- a/docs/src/reference/architecture.md +++ b/docs/src/reference/architecture.md @@ -28,7 +28,7 @@ their content address; identical content is stored once. * **3D preview**: `mesh.rs` dispatches to one reader per format in `src/mesh/` (`stl.rs`, `obj.rs`, `ply.rs`, `off.rs`, `three_mf.rs` for 3MF and AMF, - `gltf.rs`, `three_ds.rs`, `points.rs` for PTS/XYZ/LAS); the mesh and its + `gltf.rs`, `three_ds.rs`, `points.rs` for PTS/XYZ/LAS, `e57.rs` for E57 scans with their page checksums); the mesh and its `TCMESH01` encoding are in `mesh/model.rs`, the shared bounded byte access in `mesh/helpers.rs`. It reads STL/OBJ/PLY/OFF/3MF/AMF/glTF/3DS/point clouds and tessellates STEP with the truck kernel (`mesh/step.rs`; an own diff --git a/docs/src/reference/formats.md b/docs/src/reference/formats.md index 60c07a7e..ce3887ae 100755 --- a/docs/src/reference/formats.md +++ b/docs/src/reference/formats.md @@ -291,7 +291,7 @@ searchable and compared with the item – see | Format | Extensions | |--------------------|---------------------------------------| -| ASTM E57 | `.e57` | +| ASTM E57 | `.e57` (3D) | | LAS / LAZ | `.las` (3D), `.laz` | | PTS, PTX, XYZ, PCD | `.pts` (3D) `.ptx` `.xyz` (3D) `.pcd` | @@ -391,6 +391,39 @@ assembly placements (`MAPPED_ITEM`, `CONTEXT_DEPENDENT_SHAPE_REPRESENTATION` not previewed; the conversion has a time limit of 180 s and the usual triangle limit. +## E57 in the 3D preview + +E57 files (ASTM E2807) are read by an own reader in the isolated preview +process (`src/mesh/e57.rs`; format notes in the research page +[3D preview of E57 point clouds](../research/e57-preview.md)): + +* the **CRC-32C of every 1 KiB page** is checked before anything is read; a + file with a damaged page is refused (*the checksum of page N … does not + match*), never shown as a wrong cloud; +* every scan (`data3D` entry) is moved by its **pose** (rotation quaternion and + translation), so the stations of a multi-scan file line up; +* positions from `cartesianX/Y/Z` or from `sphericalRange/Azimuth/Elevation`, + stored as floats or as scaled integers; points marked invalid + (`cartesianInvalidState`, `sphericalInvalidState`) are left out; +* colours from `colorRed/Green/Blue`, scaled by the scan's `colorLimits`; + without colours the intensity (scaled by `intensityLimits`) colours the cloud + as a field; +* metres are converted to millimetres; +* more than 3 million points are thinned evenly over all scans, and the + viewer says so; +* embedded images (`images2D`), other point fields and extensions are + ignored; `String` or `Blob` fields inside the points are refused. + +The XML section may have at most 64 MiB and 1 000 000 elements, a file at most +4096 scans; the usual size and time limits of the preview apply. E57 shares +the size cap of meshes and point clouds (`TEAMCRAFT_PREVIEW_MAX_MESH_MB`, +default 256 MB), and real laser scans are often larger: such a file is refused +as too large before any thinning starts. To preview larger scans, raise +`TEAMCRAFT_PREVIEW_MAX_MESH_MB` and keep `TEAMCRAFT_PREVIEW_MAX_MEMORY_MB` at +least about the file size plus 100 MB – the reader holds the whole file in +memory to check the checksum of every page (see +[Configuration](../admin/configuration.md)). + ## Why not every format is previewed Most native formats are proprietary and undocumented; reading their geometry diff --git a/docs/src/research/e57-preview.md b/docs/src/research/e57-preview.md new file mode 100644 index 00000000..81a349f8 --- /dev/null +++ b/docs/src/research/e57-preview.md @@ -0,0 +1,153 @@ +# 3D preview of E57 point clouds + +*Date: 2026-11-22 · Issue #373 · Decision: an own bounded reader (`src/mesh/e57.rs`), no new crate.* + +## Question + +E57 (`.e57`, ASTM E2807) is the exchange format most laser scanners and their +software export. TeamCraft recognised it (`src/cadformat.rs`) but showed no 3D +preview, although PTS, XYZ and LAS point clouds are previewed. What does a +reader need, and should it be the `e57` crate or an own reader? + +## Sources + +* **ASTM E2807-11** *Standard Specification for 3D Imaging Data Exchange, + Version 1.0* – the public description of the file layout (header, pages, + XML, binary sections), as summarised on the libE57 project pages. The + standard text itself was not available (see the table below). +* **libE57 format notes** (libe57.org, *E57 file format* and the reference + implementation's documentation, Boost Software Licence): the checksum byte + order, the packet layout of compressed vectors, the bit-pack codec and the + element names of `data3D` (`pose`, `colorLimits`, `intensityLimits`, + `cartesianInvalidState` …). +* **The `e57` crate** (github.com/cry-inc/e57, MIT/Apache-2.0, pure Rust) – + read as documentation of the same public format to confirm three details: + the checksum is stored big-endian (`crc.to_be_bytes()`), packet lengths are + stored minus one and are multiples of four, and the bit-pack stream is read + least significant bit first across packet boundaries. No code was copied. +* Synthetic files built by the tests' own minimal writer (below). No openly + licensed real scan small enough for the repository was found yet; the libE57 + sample data has no clear licence for redistribution. + +No proprietary scanner software was used or examined. + +### Source of each finding + +The text of ASTM E2807-11 itself (a paid standard) was **not available**, so +no clause numbers are given; every finding below comes from the public +documents named here instead. Where a finding says *libE57*, it is the +libE57 project site (, reference implementation under +the Boost Software Licence) – its *E57 file format* description and the +*E57 Foundation API* reference documentation +(); *e57 crate* is the source and +documentation of (MIT/Apache-2.0, +), read only as documentation, no code copied; *seed* is +`fuzz/seeds/e57/three-points.e57` and the tests' own writer, which only +confirm that the reader and the writer agree. + +| Finding | Source | +|---|---| +| File header: signature, versions, physical length, XML offset and logical length, page size | libE57 *E57 file format* (file header); field order and types confirmed in the e57 crate (file header reader) | +| Pages of 1024 bytes = 1020 data + CRC-32C; physical vs logical offsets | libE57 *E57 file format* (paged file); e57 crate (paged reader) | +| CRC-32C parameters (Castagnoli, reflected `0x82F63B78`, init/xor `0xFFFFFFFF`) | the public CRC-32C definition (RFC 3720, appendix B.4, check value `0xE3069283` for `123456789` – tested in `crc32c_matches_the_standard_check_value`) | +| Checksum stored big endian | e57 crate (`crc.to_be_bytes()` in its page writer and check in its reader); libE57 writes it the same way | +| XML element types and attributes (`Structure`, `Vector`, `CompressedVector`, `Integer`, `ScaledInteger`, `Float`, `String`, `Blob`) | libE57 *E57 Foundation API* (the node classes `StructureNode`, `VectorNode`, `CompressedVectorNode`, `IntegerNode`, `ScaledIntegerNode`, `FloatNode`, `StringNode`, `BlobNode` and their attributes) | +| `e57Root`, `data3D`, `images2D`; per scan `pose` (quaternion + translation), `colorLimits`, `intensityLimits`, `points`, the prototype field names and the invalid states | libE57 *E57 file format* (the E57 elements of `data3D`) and the *E57 Simple API* header documentation on libe57.org; element names confirmed in the e57 crate (point cloud reader) | +| Compressed vector section header (id 1, reserved bytes, logical length, data and index offsets) | libE57 *E57 file format* (binary sections); e57 crate (section header reader) | +| Data, index and empty packets; length stored minus one, multiple of 4, 64 KiB at most; one byte stream per prototype field | e57 crate (packet reader); libE57 *E57 file format* (compressed vector packets) | +| Bit-pack codec: floats as 4/8 LE bytes, integers as `value − minimum` in `⌈log₂(range + 1)⌉` bits, LSB first, continuous across packets | e57 crate (bit-pack decoder) and libE57 *E57 file format* (bit-pack codec) | + +## The format, as far as the preview needs it + +**File header** (48 bytes at offset 0, little endian): signature +`ASTM-E57`, major version `u32` (1), minor version `u32`, physical file +length `u64`, physical offset of the XML section `u64`, logical length of the +XML section `u64`, page size `u64` (1024). + +**Pages.** The whole file – header included – is cut into physical pages of +1024 bytes: 1020 bytes of data and a CRC-32C (Castagnoli, reflected +polynomial `0x82F63B78`, initial value and final XOR `0xFFFFFFFF`) of those +1020 bytes. The standard says numbers are little endian, but libE57 writes the +checksum **big endian** and every reader follows it. Offsets in the XML are +*physical* (`page · 1024 + byte`), lengths are *logical* (counted without the +checksums): logical = `page · 1020 + byte`. + +**XML section.** A tree of typed elements: `Structure`, `Vector`, +`CompressedVector`, `Integer` (attributes `minimum`, `maximum`; value as +text), `ScaledInteger` (also `scale`, `offset`; value = raw · scale + +offset), `Float` (`precision="single"|"double"`), `String`, `Blob`. The root +`e57Root` has `data3D` (one child per scan) and `images2D` (ignored). Per +scan: + +* `pose` – `rotation` (unit quaternion `w x y z`) and `translation` + (`x y z`); a point moves as `p' = R·p + t`, which lines up multi-station + scans; +* `colorLimits` (`colorRedMinimum` … `colorBlueMaximum`) and + `intensityLimits` (`intensityMinimum`, `intensityMaximum`) – the range the + stored values are scaled from; missing limits fall back to the prototype's + `minimum`/`maximum`; +* `points` – a `CompressedVector` with `fileOffset` (physical) and + `recordCount`, whose `prototype` lists the fields of a record in order: + `cartesianX/Y/Z` or `sphericalRange/Azimuth/Elevation` (radians, elevation + from the XY plane), `cartesianInvalidState` / `sphericalInvalidState` + (0 valid, 1 direction only, 2 invalid), `colorRed/Green/Blue`, + `isColorInvalid`, `intensity`, `isIntensityInvalid`, and many others + (`rowIndex`, `timeStamp`, `returnIndex`, extensions) that the preview skips. + +**Binary section of a compressed vector.** A 32-byte section header (section +id `1`, 7 reserved bytes, logical length `u64`, physical offset of the first +data packet `u64`, physical offset of the index packet `u64`), then packets +(logical addresses, at most 64 KiB, length stored minus one, multiple of 4): + +* data packet – type `1`, flags `u8`, length − 1 `u16`, byte stream count + `u16`, one `u16` buffer length per stream, then the buffers; +* index packet – type `0`, 16-byte header (skipped); +* empty packet – type `2`, 4-byte header (skipped). + +There is one byte stream per prototype field. Each stream continues from one +packet to the next. The only codec of E57 1.0 is **bit pack**: `Float` +values as 4 or 8 little-endian bytes; `Integer` and `ScaledInteger` as +`value − minimum` in `bits = ⌈log₂(maximum − minimum + 1)⌉` bits (0 bits +when minimum = maximum), least significant bit first in one continuous +bit stream. + +## Crate or own reader? + +The `e57` crate (MIT/Apache-2.0, pure Rust) reads the format well, but: + +* it checks a page's checksum only when that page is read; the issue wants + every page checked before anything is shown, so a damaged file never gives + a wrong cloud; +* it brings `roxmltree` and its own allocation decisions (one `Vec` per + record queue, sizes from the file), which we would have to audit and fuzz as + a black box in the preview child; +* its API returns records point by point through an iterator; thinning evenly + over all scans and dropping the unused fields is just as much code on top. + +An own reader is about 700 lines on top of what TeamCraft already has: +`quick-xml` (already used for 3MF, AMF and VTK XML), the bounded byte helpers +of `src/mesh/helpers.rs`, `stride_for` and `MAX_POINTS`. A table-driven +CRC-32C is 20 lines. **Decision: own reader in `src/mesh/e57.rs`, no new +dependency.** + +## Limits of the reader + +* every page's CRC-32C is checked first (either byte order accepted – a + random match is 2 in 2³²); a mismatch refuses the file and names the page; +* XML section at most 64 MiB, at most 1 000 000 elements, depth at most 64, + text kept per element at most 256 characters; +* at most 4096 scans and 256 fields per prototype; packets checked against + the section length and the stream count of the prototype; a scan that ends + before its `recordCount` is refused; +* points thinned evenly with `stride_for` over the summed `recordCount` of + all scans, so the preview never holds more than `MAX_POINTS`; the preview + notes how many points the file has (flag 8 of `TCMESH01`, also set by the + PTS/XYZ and LAS readers); +* metres converted to millimetres (the viewer's unit). + +## Not now + +* embedded images (`images2D`), colours from them, and E57 extension fields; +* `Blob`/`String` fields inside a compressed vector (not used by scanners; + refused); +* per-scan grouping in the viewer (the scans become one cloud). diff --git a/docs/src/research/index.md b/docs/src/research/index.md index f69a5589..a81cfa35 100755 --- a/docs/src/research/index.md +++ b/docs/src/research/index.md @@ -16,6 +16,7 @@ accepted in TeamCraft, from people or from AI agents | Topic | Decision | Date | |---------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------| +| [3D preview of E57 point clouds](e57-preview.md) | own bounded reader (no new crate): every page's CRC-32C checked first, XML with size and depth limits, every `data3D` scan with its pose, cartesian or spherical, float or scaled-integer positions, colours by `colorLimits`, intensity otherwise, invalid points dropped, metres to mm, thinned evenly over all scans with a note in the preview; images and extension fields ignored | 2026-11-22 | | [CAD add-ins: Inventor and Siemens NX first](cad-addins.md) | build an Inventor add-in MVP (.NET 8, registry-free `.addin`, Inventor 2025–2027) and an NX MVP after checking for an NX Open author licence (signed .NET startup application on Windows, else a journal first; Linux later); both talk to the desktop app over per-user local IPC (named pipe / Unix socket, protocol `teamcraft.cad` v1) – no token in the add-in, requests are untrusted intents the desktop app confirms; vendor assemblies referenced, never redistributed; a CAD-independent core with a fake host in CI, FreeCAD as the reference add-in CI can run on Linux | 2026-11-22 | | [SolidCraft designs (`.sc`)](solidcraft-design.md) | read thumbnail, linked designs, BOM and design properties from the ZIP or JSON design with own bounded readers – unknown versions or malformed parts are "nothing found", never an error; `solidcraft-cli` only from the desktop app (STEP export, property write-back); the native B-rep model cache not now | 2026-11-21 | | [Translated UI: message catalogs](translated-ui.md) | JSON catalogs in `shared/i18n/` (ID → sentence with `{named}` placeholders, CLDR plural categories), read by Rust (`include_str!`) and JS (`Intl.PluralRules`); English fallback, guard tests for IDs and placeholders; no new dependency, Fluent as the upgrade path | 2026-11-22 | diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 4cd5def9..da87e883 100755 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -131,3 +131,10 @@ path = "fuzz_targets/solversummary.rs" test = false doc = false bench = false + +[[bin]] +name = "e57" +path = "fuzz_targets/e57.rs" +test = false +doc = false +bench = false diff --git a/fuzz/fuzz_targets/e57.rs b/fuzz/fuzz_targets/e57.rs new file mode 100644 index 00000000..96ca7cbf --- /dev/null +++ b/fuzz/fuzz_targets/e57.rs @@ -0,0 +1,7 @@ +//! `cargo fuzz run e57` – see fuzz/README.md and `teamcraft::fuzz_harness::e57`. +#![no_main] + +use libfuzzer_sys::fuzz_target; +use teamcraft::fuzz_harness::{e57, guarded, quiet_panics}; + +fuzz_target!(init: quiet_panics(), |data: &[u8]| guarded(e57, data)); diff --git a/fuzz/seeds/e57/three-points.e57 b/fuzz/seeds/e57/three-points.e57 new file mode 100644 index 00000000..817bd335 Binary files /dev/null and b/fuzz/seeds/e57/three-points.e57 differ diff --git a/shared/js/viewer.js b/shared/js/viewer.js index 3ca71de0..a804e2f6 100755 --- a/shared/js/viewer.js +++ b/shared/js/viewer.js @@ -137,11 +137,17 @@ at += vertices * 4; } } + // flag 8: a thinned point cloud, the points in the file (u64) after the fields + var thinned = null; + if (flags & 8) { + at = Math.ceil(at / 4) * 4; + if (at + 8 <= buffer.byteLength) thinned = dv.getUint32(at, true) + dv.getUint32(at + 4, true) * 4294967296; + } // flag 4: partial preview, face counts in the last 8 bytes (after the fields) var faces = flags & 4 && buffer.byteLength >= 56 ? { shown: dv.getUint32(buffer.byteLength - 8, true), total: dv.getUint32(buffer.byteLength - 4, true) } : null; - return { positions: positions, indices: index, colors: colors, parts: parts, bounds: bounds, fields: fields, faces: faces }; + return { positions: positions, indices: index, colors: colors, parts: parts, bounds: bounds, fields: fields, faces: faces, thinned: thinned }; } // ---------------------------------------------------------------- colour map @@ -666,7 +672,10 @@ var partial = mesh.faces ? " · partial preview: " + mesh.faces.shown.toLocaleString() + " of " + mesh.faces.total.toLocaleString() + " faces" : ""; - setStatus(what + " · " + fmt(size[0]) + " × " + fmt(size[1]) + " × " + fmt(size[2]) + " (X × Y × Z, model units)" + partial); + var thin = mesh.thinned + ? " · thinned for the preview from " + mesh.thinned.toLocaleString() + " points" + : ""; + setStatus(what + " · " + fmt(size[0]) + " × " + fmt(size[1]) + " × " + fmt(size[2]) + " (X × Y × Z, model units)" + partial + thin); } function render() { diff --git a/src/cadformat.rs b/src/cadformat.rs index 7aaa10f0..f5f41201 100755 --- a/src/cadformat.rs +++ b/src/cadformat.rs @@ -1922,6 +1922,7 @@ mod tests { assert_eq!(info("step").unwrap().preview, Some("step")); assert_eq!(info("3mf").unwrap().preview, Some("3mf")); assert_eq!(info("las").unwrap().preview, Some("las")); + assert_eq!(info("e57").unwrap().preview, Some("e57")); assert_eq!( info("brep").unwrap().preview, None, diff --git a/src/fuzz_harness.rs b/src/fuzz_harness.rs index 7f0c1729..200d8982 100755 --- a/src/fuzz_harness.rs +++ b/src/fuzz_harness.rs @@ -32,6 +32,7 @@ pub const MESH_FORMATS: &[&str] = &[ "rhino", "pts", "las", + "e57", "jt", "vtk-legacy", "vtk-unstructured", @@ -156,6 +157,24 @@ pub fn mesh(data: &[u8]) { let _ = crate::catprod::document(data); } +/// E57 point clouds: the bytes as they are (almost always refused by the +/// page checksums), then cut to whole pages with the file length in the +/// header set and every page checksum recomputed, so the fuzzer reaches the +/// XML, the packets and the bit-packed streams behind the checksums. +pub fn e57(data: &[u8]) { + let _ = crate::mesh::read("e57", data); + let pages = data.len() / 1024 * 1024; + if pages == 0 { + return; + } + let mut sealed = data.get(..pages).unwrap_or_default().to_vec(); + if let Some(length) = sealed.get_mut(16..24) { + length.copy_from_slice(&(pages as u64).to_le_bytes()); + } + crate::mesh::seal_e57_pages(&mut sealed); + let _ = crate::mesh::read("e57", &sealed); +} + /// File names whose format `cadformat::detect` decides by content (the /// solver files of Fluent, STAR-CCM+ and Simcenter 3D among them). const DETECT_NAMES: &[&str] = &[ @@ -278,6 +297,7 @@ pub const TARGETS: &[Target] = &[ ("htmltext", htmltext), ("mesh", mesh), ("mesh_step", mesh_step), + ("e57", e57), ("cadformat", cadformat), ("resultscan", resultscan), ("solversummary", solversummary), diff --git a/src/main.rs b/src/main.rs index 8fba93ff..ad3752c5 100755 --- a/src/main.rs +++ b/src/main.rs @@ -761,8 +761,12 @@ fn preview_mesh( .faces .map(|(shown, total)| format!(", partial preview: {shown} of {total} faces")) .unwrap_or_default(); + let thinned = mesh + .thinned + .map(|total| format!(", thinned from {total} points")) + .unwrap_or_default(); println!( - "{} triangles, {} vertices, {} bodies{partial}", + "{} triangles, {} vertices, {} bodies{partial}{thinned}", mesh.triangle_count(), mesh.vertex_count(), mesh.parts.max(1) diff --git a/src/mesh.rs b/src/mesh.rs index 56cc9b58..02452d49 100755 --- a/src/mesh.rs +++ b/src/mesh.rs @@ -1,7 +1,7 @@ //! Triangle meshes and point clouds for the 3D preview. //! //! Pure-Rust readers for the common mesh, 3D-printing, visualisation and -//! point-cloud formats, plus STEP B-rep tessellation with the `truck` CAD +//! point-cloud formats (PTS, XYZ, LAS, E57), plus STEP B-rep tessellation with the `truck` CAD //! kernel (Apache-2.0). Every reader produces one [`Mesh`] in model //! coordinates; [`Mesh::encode`] writes the compact binary form that //! `shared/js/viewer.js` draws (`TCMESH01`, little endian). @@ -26,6 +26,7 @@ use anyhow::{bail, Result}; mod catia; pub mod creo; +mod e57; mod earcut; mod f3d; mod gltf; @@ -52,6 +53,7 @@ mod test_support; mod three_ds; mod three_mf; +pub(crate) use e57::seal_pages as seal_e57_pages; pub(crate) use helpers::*; pub use model::{color_map, Field, Mesh, MAX_FIELDS, MAX_POINTS, MAX_TRIANGLES}; pub use step::MAX_STEP_BYTES; @@ -69,6 +71,7 @@ pub fn read(format: &str, data: &[u8]) -> Result { "3ds" => three_ds::read(data)?, "pts" | "xyz" => points::read_text(data)?, "las" => points::read_las(data)?, + "e57" => e57::read_e57(data)?, "step" => step::read(data)?, "nx-part" => jt::read_nx(data)?, "jt" => jt10::read(data)?, diff --git a/src/mesh/e57.rs b/src/mesh/e57.rs new file mode 100644 index 00000000..c9e662d6 --- /dev/null +++ b/src/mesh/e57.rs @@ -0,0 +1,1543 @@ +//! E57 point clouds (ASTM E2807), the exchange format of laser scanners. +//! +//! The whole file is cut into 1024-byte pages, each ending in a CRC-32C of +//! its 1020 data bytes; every checksum is verified before anything else is +//! read, so a damaged file is refused instead of shown as a wrong cloud. The +//! XML section describes the scans (`data3D`); each scan's points sit in a +//! binary section of packets with one bit-packed byte stream per field. +//! Every scan is moved by its pose, metres become millimetres, and large +//! clouds are thinned evenly over all scans. Format notes and sources: +//! `docs/src/research/e57-preview.md`. + +use anyhow::{bail, Context, Result}; + +use super::*; + +/// Physical page size (the only one the standard defines). +const PAGE: usize = 1024; +/// Data bytes of a page (before its checksum). +const PAGE_DATA: usize = PAGE - 4; +/// The XML section is read whole: at most this many bytes. +const MAX_XML: u64 = 64 * 1024 * 1024; +/// Elements of the XML tree at most. +const MAX_NODES: usize = 1_000_000; +/// Nesting depth of the XML tree at most. +const MAX_DEPTH: usize = 64; +/// Characters of text kept per element (numbers are short). +const MAX_TEXT: usize = 256; +/// Scans (`data3D` entries) at most. +const MAX_SCANS: usize = 4096; +/// Fields of a scan's prototype at most. +const MAX_PROTOTYPE_FIELDS: usize = 256; +/// E57 stores metres; the viewer shows millimetres. +const MM_PER_M: f64 = 1000.0; +/// Colour of points without one in a cloud where others have one. +const NEUTRAL: [u8; 3] = [176, 188, 200]; + +pub(super) fn read_e57(data: &[u8]) -> Result { + read_within(data, MAX_POINTS) +} + +/// [`read_e57`] with a point budget (tests use a small one). +fn read_within(data: &[u8], budget: usize) -> Result { + if data.get(..8) != Some(b"ASTM-E57".as_slice()) { + bail!("Not an E57 file."); + } + let major = u32_le(data, 8)?; + if major != 1 { + bail!("E57 version {major} is not previewed (only version 1)."); + } + let length = u64_le(data, 16)?; + let xml_offset = u64_le(data, 24)?; + let xml_length = u64_le(data, 32)?; + let page_size = u64_le(data, 40)?; + if page_size != PAGE as u64 { + bail!("The E57 file has pages of {page_size} bytes – the standard defines 1024."); + } + let length = usize::try_from(length).unwrap_or(usize::MAX); + if length > data.len() { + return Err(ends_early(data.len())); + } + if length == 0 || length % PAGE != 0 { + bail!("The E57 file length ({length} bytes) is not a whole number of pages."); + } + let data = range(data, 0, length)?; + check_pages(data)?; + let paged = Paged { data }; + + if xml_length > MAX_XML { + bail!("The E57 XML section is too large to preview ({xml_length} bytes)."); + } + let xml = paged.read(Paged::logical(xml_offset)?, xml_length as usize)?; + let tree = parse_xml(&xml)?; + let root = 0; + if tree.node(root).map(|n| n.name.as_str()) != Some("e57Root") { + bail!("The E57 XML section has no e57Root."); + } + let scan_nodes: Vec = tree + .child(root, "data3D") + .and_then(|d| tree.node(d)) + .map(|d| d.children.clone()) + .unwrap_or_default(); + if scan_nodes.is_empty() { + bail!("The E57 file contains no 3D scan (only images or nothing)."); + } + if scan_nodes.len() > MAX_SCANS { + bail!( + "The E57 file has {} scans – the preview reads at most {MAX_SCANS}.", + scan_nodes.len() + ); + } + let mut scans = scan_nodes + .iter() + .map(|&n| Scan::from_xml(&tree, n)) + .collect::>>()?; + + // evenly over all scans, by the point counts the XML gives + let total = scans + .iter() + .fold(0u64, |sum, s| sum.saturating_add(s.records)); + let stride = stride_within(usize::try_from(total).unwrap_or(usize::MAX), budget) as u64; + let mut cloud = Cloud::default(); + let mut seen = 0u64; + for scan in &mut scans { + scan.read_points(&paged, stride, &mut seen, &mut cloud)?; + } + Ok(cloud.into_mesh(scans.len(), (stride > 1).then_some(total))) +} + +// ------------------------------------------------------------------ pages + +fn crc_table() -> [u32; 256] { + let mut table = [0u32; 256]; + for (i, slot) in table.iter_mut().enumerate() { + let mut c = i as u32; + for _ in 0..8 { + c = if c & 1 != 0 { + (c >> 1) ^ 0x82F6_3B78 + } else { + c >> 1 + }; + } + *slot = c; + } + table +} + +/// CRC-32C (Castagnoli) of `data`. +fn crc32c(table: &[u32; 256], data: &[u8]) -> u32 { + let mut crc = !0u32; + for &b in data { + let i = usize::from((crc as u8) ^ b); + crc = (crc >> 8) ^ table.get(i).copied().unwrap_or(0); + } + !crc +} + +/// Verifies the checksum of every page. libE57 writes it big endian (the +/// standard says little endian for numbers); both orders are accepted. +fn check_pages(data: &[u8]) -> Result<()> { + let table = crc_table(); + for (n, page) in data.chunks_exact(PAGE).enumerate() { + let (body, sum) = page.split_at(PAGE_DATA); + let crc = crc32c(&table, body); + if sum != crc.to_be_bytes() && sum != crc.to_le_bytes() { + bail!( + "The E57 file is damaged: the checksum of page {} (bytes {}–{}) does not match, \ + so no preview is shown.", + n + 1, + n * PAGE, + n * PAGE + PAGE - 1 + ); + } + } + Ok(()) +} + +/// Writes the checksum of every whole page (the tests' writer and the fuzz +/// harness, which would otherwise never get past the checksums). +pub(crate) fn seal_pages(data: &mut [u8]) { + let table = crc_table(); + for page in data.chunks_exact_mut(PAGE) { + let (body, sum) = page.split_at_mut(PAGE_DATA); + sum.copy_from_slice(&crc32c(&table, body).to_be_bytes()); + } +} + +/// The file's logical bytes: the pages without their checksums. +struct Paged<'a> { + /// Whole pages, checksums verified. + data: &'a [u8], +} + +impl Paged<'_> { + fn logical_len(&self) -> u64 { + (self.data.len() / PAGE * PAGE_DATA) as u64 + } + + /// The logical offset of a physical one (offsets in the file are + /// physical, lengths logical). + fn logical(physical: u64) -> Result { + let (page, at) = (physical / PAGE as u64, physical % PAGE as u64); + if at >= PAGE_DATA as u64 { + bail!("The E57 file points into a page checksum (offset {physical})."); + } + Ok(page * PAGE_DATA as u64 + at) + } + + /// Appends `len` logical bytes from `from` to `out`. + fn read_into(&self, from: u64, len: usize, out: &mut Vec) -> Result<()> { + let end = from + .checked_add(len as u64) + .filter(|end| *end <= self.logical_len()) + .ok_or_else(|| ends_early(usize::try_from(from).unwrap_or(usize::MAX)))?; + let mut at = from; + while at < end { + let page = (at / PAGE_DATA as u64) as usize; + let offset = (at % PAGE_DATA as u64) as usize; + let take = ((end - at) as usize).min(PAGE_DATA - offset); + let start = page * PAGE + offset; + out.extend_from_slice(range(self.data, start, start + take)?); + at += take as u64; + } + Ok(()) + } + + fn read(&self, from: u64, len: usize) -> Result> { + if from.saturating_add(len as u64) > self.logical_len() { + return Err(ends_early(usize::try_from(from).unwrap_or(usize::MAX))); + } + let mut out = Vec::with_capacity(len); + self.read_into(from, len, &mut out)?; + Ok(out) + } +} + +// ------------------------------------------------------------------ XML + +#[derive(Default)] +struct Node { + /// Local element name. + name: String, + /// The `type` attribute (`Structure`, `Float`, `Integer` …). + kind: String, + /// The attributes the reader uses. + attrs: Vec<(String, String)>, + text: String, + children: Vec, +} + +impl Node { + fn attr(&self, name: &str) -> Option<&str> { + self.attrs + .iter() + .find(|(k, _)| k == name) + .map(|(_, v)| v.trim()) + } + + fn attr_f64(&self, name: &str) -> Option { + self.attr(name)? + .parse() + .ok() + .filter(|v: &f64| v.is_finite()) + } + + fn attr_i64(&self, name: &str) -> Option { + self.attr(name)?.parse().ok() + } + + fn attr_u64(&self, name: &str) -> Option { + self.attr(name)?.parse().ok() + } +} + +/// The XML tree; node 0 is the root. +struct Tree { + nodes: Vec, +} + +impl Tree { + fn node(&self, i: usize) -> Option<&Node> { + self.nodes.get(i) + } + + fn child(&self, i: usize, name: &str) -> Option { + self.node(i)? + .children + .iter() + .copied() + .find(|&c| self.node(c).is_some_and(|n| n.name == name)) + } + + fn path(&self, i: usize, path: &[&str]) -> Option { + path.iter().try_fold(i, |at, name| self.child(at, name)) + } + + /// The value of an `Integer`, `ScaledInteger` or `Float` element (an + /// empty one is 0, as the standard says). + fn number(&self, i: usize) -> Option { + let n = self.node(i)?; + let text = n.text.trim(); + let value = match n.kind.as_str() { + "Integer" if text.is_empty() => 0.0, + "Integer" => text.parse::().ok()? as f64, + "ScaledInteger" => { + let raw = if text.is_empty() { + 0 + } else { + text.parse::().ok()? + }; + raw as f64 * n.attr_f64("scale").unwrap_or(1.0) + + n.attr_f64("offset").unwrap_or(0.0) + } + "Float" if text.is_empty() => 0.0, + "Float" => text.parse::().ok()?, + _ => return None, + }; + value.is_finite().then_some(value) + } + + fn number_at(&self, i: usize, path: &[&str]) -> Option { + self.number(self.path(i, path)?) + } +} + +/// Attributes kept from the XML (the rest is not needed). +const ATTRIBUTES: &[&str] = &[ + "precision", + "minimum", + "maximum", + "scale", + "offset", + "fileOffset", + "recordCount", +]; + +fn parse_xml(xml: &[u8]) -> Result { + use quick_xml::events::Event; + let mut reader = quick_xml::Reader::from_reader(xml); + let mut nodes: Vec = Vec::new(); + let mut stack: Vec = Vec::new(); + loop { + let event = reader + .read_event() + .context("The E57 XML section is invalid")?; + match event { + Event::Start(ref e) | Event::Empty(ref e) => { + let empty = matches!(event, Event::Empty(_)); + if nodes.len() >= MAX_NODES { + bail!("The E57 XML section has more than {MAX_NODES} elements."); + } + if stack.len() >= MAX_DEPTH { + bail!("The E57 XML section is nested more than {MAX_DEPTH} levels deep."); + } + let mut node = Node { + name: e.local_name().as_ref().to_owned(), + ..Node::default() + }; + for a in e.attributes().flatten() { + let key = a.key.local_name().as_ref().to_owned(); + let wanted = key == "type" || ATTRIBUTES.contains(&key.as_str()); + if !wanted { + continue; + } + let value = a + .normalized_value(quick_xml::XmlVersion::Implicit1_0) + .map(|v| v.chars().take(MAX_TEXT).collect::()) + .unwrap_or_default(); + if key == "type" { + node.kind = value; + } else { + node.attrs.push((key, value)); + } + } + let index = nodes.len(); + match stack.last() { + Some(&parent) => { + if let Some(p) = nodes.get_mut(parent) { + p.children.push(index); + } + } + None if index == 0 => {} + None => bail!("The E57 XML section has more than one root element."), + } + nodes.push(node); + if !empty { + stack.push(index); + } + } + Event::Text(t) => { + if let Some(node) = stack.last().and_then(|&i| nodes.get_mut(i)) { + let room = MAX_TEXT.saturating_sub(node.text.chars().count()); + let text = t.into_inner(); + node.text.extend(text.chars().take(room)); + } + } + Event::End(_) => { + stack.pop(); + } + Event::Eof => break, + _ => {} + } + } + if nodes.is_empty() { + bail!("The E57 XML section is empty."); + } + Ok(Tree { nodes }) +} + +// ------------------------------------------------------------------ fields + +/// What a prototype field means for the preview. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Role { + X, + Y, + Z, + Range, + Azimuth, + Elevation, + CartesianInvalid, + SphericalInvalid, + Red, + Green, + Blue, + ColorInvalid, + Intensity, + IntensityInvalid, + /// Read (the stream must be walked) and dropped. + Other, +} + +/// Number of roles that carry a value (all but `Other`). +const ROLES: usize = Role::Other as usize; + +impl Role { + fn of(name: &str) -> Role { + match name { + "cartesianX" => Role::X, + "cartesianY" => Role::Y, + "cartesianZ" => Role::Z, + "sphericalRange" => Role::Range, + "sphericalAzimuth" => Role::Azimuth, + "sphericalElevation" => Role::Elevation, + "cartesianInvalidState" => Role::CartesianInvalid, + "sphericalInvalidState" => Role::SphericalInvalid, + "colorRed" => Role::Red, + "colorGreen" => Role::Green, + "colorBlue" => Role::Blue, + "isColorInvalid" => Role::ColorInvalid, + "intensity" => Role::Intensity, + "isIntensityInvalid" => Role::IntensityInvalid, + _ => Role::Other, + } + } +} + +/// How a byte stream stores its values (the bit-pack codec of E57 1.0). +#[derive(Clone, Copy, Debug)] +enum Codec { + F32, + F64, + /// `minimum + raw` in `bits` bits, then `· scale + offset`. + Int { + min: i64, + bits: u32, + scale: f64, + offset: f64, + }, +} + +/// One field's byte stream: it continues from packet to packet and is read +/// least significant bit first. +struct Stream { + role: Role, + codec: Codec, + /// The range of the values from the prototype (limits fall back to it). + bounds: Option<(f64, f64)>, + bytes: Vec, + /// Bits of `bytes` already read. + bit: usize, +} + +impl Stream { + fn from_xml(node: &Node, role: Role) -> Result { + let int = |scale: f64, offset: f64| -> Result<(Codec, Option<(f64, f64)>)> { + let min = node.attr_i64("minimum").unwrap_or(i64::MIN); + let max = node.attr_i64("maximum").unwrap_or(i64::MAX); + if max < min { + bail!( + "The E57 field '{}' has its maximum below its minimum.", + truncate(&node.name) + ); + } + let span = (i128::from(max) - i128::from(min)) as u128; + let bits = 128 - span.leading_zeros(); + let bounds = (min as f64 * scale + offset, max as f64 * scale + offset); + let (lo, hi) = if scale < 0.0 { + (bounds.1, bounds.0) + } else { + bounds + }; + Ok(( + Codec::Int { + min, + bits, + scale, + offset, + }, + Some((lo, hi)), + )) + }; + let (codec, bounds) = match node.kind.as_str() { + "Float" => { + let codec = if node.attr("precision") == Some("single") { + Codec::F32 + } else { + Codec::F64 + }; + let bounds = node.attr_f64("minimum").zip(node.attr_f64("maximum")); + (codec, bounds) + } + "Integer" => int(1.0, 0.0)?, + "ScaledInteger" => int( + node.attr_f64("scale").unwrap_or(1.0), + node.attr_f64("offset").unwrap_or(0.0), + )?, + other => bail!( + "The E57 point field '{}' has the type '{}', which the preview does not read.", + truncate(&node.name), + truncate(other) + ), + }; + Ok(Stream { + role, + codec, + bounds, + bytes: Vec::new(), + bit: 0, + }) + } + + /// Bits one value takes. + fn width(&self) -> usize { + match self.codec { + Codec::F32 => 32, + Codec::F64 => 64, + Codec::Int { bits, .. } => bits as usize, + } + } + + fn available(&self) -> usize { + (self.bytes.len() * 8).saturating_sub(self.bit) + } + + /// The next `bits` (at most 64) bits; the caller checked `available`. + fn take(&mut self, bits: u32) -> u64 { + let mut value = 0u64; + let mut got = 0u32; + while got < bits { + let byte = self.bytes.get(self.bit / 8).copied().unwrap_or(0); + let shift = (self.bit % 8) as u32; + let n = (8 - shift).min(bits - got); + let part = (u64::from(byte) >> shift) & ((1u64 << n) - 1); + value |= part << got; + got += n; + self.bit += n as usize; + } + value + } + + fn next(&mut self) -> f64 { + match self.codec { + Codec::F32 => f64::from(f32::from_bits(self.take(32) as u32)), + Codec::F64 => f64::from_bits(self.take(64)), + Codec::Int { + min, + bits, + scale, + offset, + } => { + let raw = i128::from(min) + i128::from(self.take(bits)); + raw as f64 * scale + offset + } + } + } + + /// Drops the bytes already read. + fn compact(&mut self) { + let used = (self.bit / 8).min(self.bytes.len()); + self.bytes.drain(..used); + self.bit -= used * 8; + } +} + +/// The terminal fields under `node` in document order (one byte stream +/// each); only direct children of the prototype get a role. +fn terminals(tree: &Tree, node: usize, depth: usize, out: &mut Vec) -> Result<()> { + let Some(n) = tree.node(node) else { + return Ok(()); + }; + for &c in &n.children { + let Some(child) = tree.node(c) else { + continue; + }; + if child.kind == "Structure" { + if depth >= MAX_DEPTH { + bail!("The E57 prototype is nested too deeply."); + } + terminals(tree, c, depth + 1, out)?; + continue; + } + if out.len() >= MAX_PROTOTYPE_FIELDS { + bail!("The E57 scan has more than {MAX_PROTOTYPE_FIELDS} point fields."); + } + let role = if depth == 0 { + Role::of(&child.name) + } else { + Role::Other + }; + out.push(Stream::from_xml(child, role)?); + } + Ok(()) +} + +// ------------------------------------------------------------------ scans + +/// A unit quaternion (`w x y z`) as a rotation matrix (identity when it is +/// zero or not finite). +fn rotation(q: [f64; 4]) -> [[f64; 3]; 3] { + let [w, x, y, z] = q; + let n = (w * w + x * x + y * y + z * z).sqrt(); + if !n.is_finite() || n < 1e-12 { + return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]; + } + let (w, x, y, z) = (w / n, x / n, y / n, z / n); + [ + [ + 1.0 - 2.0 * (y * y + z * z), + 2.0 * (x * y - w * z), + 2.0 * (x * z + w * y), + ], + [ + 2.0 * (x * y + w * z), + 1.0 - 2.0 * (x * x + z * z), + 2.0 * (y * z - w * x), + ], + [ + 2.0 * (x * z - w * y), + 2.0 * (y * z + w * x), + 1.0 - 2.0 * (x * x + y * y), + ], + ] +} + +struct Scan { + /// Physical offset of the binary section. + section: u64, + records: u64, + streams: Vec, + spherical: bool, + color: bool, + intensity: bool, + rotation: [[f64; 3]; 3], + translation: [f64; 3], + /// Value ranges of red, green, blue. + color_limits: [(f64, f64); 3], + intensity_limits: (f64, f64), +} + +impl Scan { + fn from_xml(tree: &Tree, scan: usize) -> Result { + let points = tree + .child(scan, "points") + .context("An E57 scan has no points.")?; + let p = tree.node(points).context("An E57 scan has no points.")?; + if p.kind != "CompressedVector" { + bail!("The points of an E57 scan are not a compressed vector."); + } + let section = p + .attr_u64("fileOffset") + .context("The points of an E57 scan have no file offset.")?; + let records = p.attr_u64("recordCount").unwrap_or(0); + let prototype = tree + .child(points, "prototype") + .context("The points of an E57 scan have no prototype.")?; + let mut streams = Vec::new(); + terminals(tree, prototype, 0, &mut streams)?; + let has = |r: Role| streams.iter().any(|s| s.role == r); + let spherical = if has(Role::X) && has(Role::Y) && has(Role::Z) { + false + } else if has(Role::Range) && has(Role::Azimuth) && has(Role::Elevation) { + true + } else { + bail!("An E57 scan has neither cartesian nor spherical coordinates."); + }; + let color = has(Role::Red) && has(Role::Green) && has(Role::Blue); + let intensity = has(Role::Intensity); + let bounds = |r: Role| streams.iter().find(|s| s.role == r).and_then(|s| s.bounds); + let limit = + |group: &str, lo: &str, hi: &str, fallback: Option<(f64, f64)>, default: (f64, f64)| { + let (flo, fhi) = fallback.unwrap_or(default); + ( + tree.number_at(scan, &[group, lo]).unwrap_or(flo), + tree.number_at(scan, &[group, hi]).unwrap_or(fhi), + ) + }; + let color_limits = [ + limit( + "colorLimits", + "colorRedMinimum", + "colorRedMaximum", + bounds(Role::Red), + (0.0, 255.0), + ), + limit( + "colorLimits", + "colorGreenMinimum", + "colorGreenMaximum", + bounds(Role::Green), + (0.0, 255.0), + ), + limit( + "colorLimits", + "colorBlueMinimum", + "colorBlueMaximum", + bounds(Role::Blue), + (0.0, 255.0), + ), + ]; + let intensity_limits = limit( + "intensityLimits", + "intensityMinimum", + "intensityMaximum", + bounds(Role::Intensity), + (0.0, 1.0), + ); + let q = |c: &str, default: f64| { + tree.number_at(scan, &["pose", "rotation", c]) + .unwrap_or(default) + }; + let t = |c: &str| { + tree.number_at(scan, &["pose", "translation", c]) + .unwrap_or(0.0) + }; + Ok(Scan { + section, + records, + spherical, + color, + intensity, + rotation: rotation([q("w", 1.0), q("x", 0.0), q("y", 0.0), q("z", 0.0)]), + translation: [t("x"), t("y"), t("z")], + color_limits, + intensity_limits, + streams, + }) + } + + /// Reads the points of the scan; every `stride`-th record over all scans + /// (`seen` counts them) goes into `cloud`. + fn read_points( + &mut self, + paged: &Paged, + stride: u64, + seen: &mut u64, + cloud: &mut Cloud, + ) -> Result<()> { + if self.records == 0 { + return Ok(()); + } + if self.streams.iter().all(|s| s.width() == 0) { + bail!("An E57 scan stores no point data (every field is constant)."); + } + let start = Paged::logical(self.section)?; + let header = paged.read(start, 32)?; + if header.first() != Some(&1) { + bail!("The binary section of an E57 scan is not a compressed vector section."); + } + let section_end = start + .checked_add(u64_le(&header, 8)?) + .filter(|end| *end <= paged.logical_len()) + .context("The binary section of an E57 scan is longer than the file.")?; + let mut at = Paged::logical(u64_le(&header, 16)?)?; + if at < start + 32 { + bail!("The binary section of an E57 scan starts inside its header."); + } + let mut left = self.records; + let mut packet = Vec::new(); + let mut values = [f64::NAN; ROLES]; + while left > 0 { + if at.saturating_add(4) > section_end { + bail!( + "An E57 scan ends before its {} points (the file is damaged).", + self.records + ); + } + packet.clear(); + paged.read_into(at, 4, &mut packet)?; + let kind = packet.first().copied().unwrap_or(u8::MAX); + let length = u64::from(u16_le(&packet, 2)?) + 1; + if length % 4 != 0 || at + length > section_end { + bail!("A packet of an E57 scan is damaged (offset {at})."); + } + match kind { + // data packet: one buffer per byte stream + 1 => { + packet.clear(); + paged.read_into(at, length as usize, &mut packet)?; + let count = usize::from(u16_le(&packet, 4)?); + if count != self.streams.len() { + bail!( + "An E57 data packet has {count} byte streams, its scan {} fields.", + self.streams.len() + ); + } + let mut from = 6 + 2 * count; + for (k, stream) in self.streams.iter_mut().enumerate() { + let n = usize::from(u16_le(&packet, 6 + 2 * k)?); + stream + .bytes + .extend_from_slice(range(&packet, from, from + n)?); + from += n; + } + // the records every stream holds completely + let ready = self + .streams + .iter() + .filter(|s| s.width() > 0) + .map(|s| s.available() / s.width()) + .min() + .unwrap_or(0) as u64; + let n = ready.min(left); + for _ in 0..n { + values.fill(f64::NAN); + for s in &mut self.streams { + let v = s.next(); + if let Some(slot) = values.get_mut(s.role as usize) { + *slot = v; + } + } + if *seen % stride == 0 { + self.keep(&values, cloud); + } + *seen += 1; + } + left -= n; + for s in &mut self.streams { + s.compact(); + } + } + // index and empty packets carry no points + 0 | 2 => {} + other => bail!("An E57 scan has a packet of unknown type {other}."), + } + at += length; + } + Ok(()) + } + + /// Adds one record to the cloud unless it is marked invalid. + fn keep(&self, values: &[f64; ROLES], cloud: &mut Cloud) { + let get = |r: Role| values.get(r as usize).copied().unwrap_or(f64::NAN); + // a missing state field is NaN: valid + let invalid = |r: Role| { + let state = get(r); + state.is_finite() && state != 0.0 + }; + if invalid(Role::CartesianInvalid) || invalid(Role::SphericalInvalid) { + return; + } + let local = if self.spherical { + let (r, az, el) = (get(Role::Range), get(Role::Azimuth), get(Role::Elevation)); + [ + r * el.cos() * az.cos(), + r * el.cos() * az.sin(), + r * el.sin(), + ] + } else { + [get(Role::X), get(Role::Y), get(Role::Z)] + }; + let [r0, r1, r2] = self.rotation; + let dot = |row: [f64; 3]| row[0] * local[0] + row[1] * local[1] + row[2] * local[2]; + let [tx, ty, tz] = self.translation; + let p = [ + (dot(r0) + tx) * MM_PER_M, + (dot(r1) + ty) * MM_PER_M, + (dot(r2) + tz) * MM_PER_M, + ]; + if p.iter() + .any(|c| !c.is_finite() || c.abs() > f64::from(f32::MAX)) + { + return; + } + let scaled = |v: f64, (lo, hi): (f64, f64)| { + let span = if hi > lo { hi - lo } else { 1.0 }; + ((v - lo) / span).clamp(0.0, 1.0) + }; + let intensity = if self.intensity && !invalid(Role::IntensityInvalid) { + let v = scaled(get(Role::Intensity), self.intensity_limits); + if v.is_finite() { + v as f32 + } else { + f32::NAN + } + } else { + f32::NAN + }; + let color = (self.color && !invalid(Role::ColorInvalid)).then(|| { + let [lr, lg, lb] = self.color_limits; + [ + (scaled(get(Role::Red), lr) * 255.0).round() as u8, + (scaled(get(Role::Green), lg) * 255.0).round() as u8, + (scaled(get(Role::Blue), lb) * 255.0).round() as u8, + ] + }); + cloud.push(p, color, intensity); + } +} + +/// The points read so far, over all scans. +#[derive(Default)] +struct Cloud { + positions: Vec, + colors: Vec, + /// 0..=1 by the scan's intensity limits; NaN = none. + intensity: Vec, + any_color: bool, + any_intensity: bool, +} + +impl Cloud { + fn push(&mut self, p: [f64; 3], color: Option<[u8; 3]>, intensity: f32) { + self.positions + .extend([p[0] as f32, p[1] as f32, p[2] as f32]); + self.any_color |= color.is_some(); + self.any_intensity |= intensity.is_finite(); + // a point without colour in a coloured cloud: grey by its intensity + let rgb = color.unwrap_or_else(|| { + if intensity.is_finite() { + let g = (intensity * 255.0).round() as u8; + [g, g, g] + } else { + NEUTRAL + } + }); + self.colors.extend(rgb); + self.intensity.push(intensity); + } + + /// Colours when a scan has them, otherwise the intensity as a field + /// (coloured with the colour map). + fn into_mesh(self, scans: usize, thinned: Option) -> Mesh { + let mut mesh = Mesh { + positions: self.positions, + parts: u32::try_from(scans).unwrap_or(u32::MAX), + thinned, + ..Mesh::default() + }; + if self.any_color { + mesh.colors = self.colors; + } else if self.any_intensity { + mesh.fields = vec![Field { + name: "Intensity".into(), + unit: String::new(), + values: self.intensity, + }]; + mesh.bake_colors(); + } + mesh + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// How a test field is stored. + #[derive(Clone, Copy)] + enum Kind { + F32, + F64, + /// minimum, maximum (values are the integers) + Int(i64, i64), + /// raw minimum, raw maximum, scale, offset (values are raw) + Scaled(i64, i64, f64, f64), + /// a field of another type (no values written) + Other(&'static str), + } + + struct TestField { + name: &'static str, + kind: Kind, + values: Vec, + } + + fn field(name: &'static str, kind: Kind, values: &[f64]) -> TestField { + TestField { + name, + kind, + values: values.to_vec(), + } + } + + #[derive(Default)] + struct TestScan { + fields: Vec, + /// rotation (w, x, y, z) and translation + pose: Option<([f64; 4], [f64; 3])>, + /// more XML inside the scan (limits, names …) + extra: String, + /// recordCount when it should differ from the values + records: Option, + } + + fn width(kind: Kind) -> u32 { + match kind { + Kind::F32 => 32, + Kind::F64 => 64, + Kind::Other(_) => 0, + Kind::Int(lo, hi) | Kind::Scaled(lo, hi, ..) => { + 128 - ((i128::from(hi) - i128::from(lo)) as u128).leading_zeros() + } + } + } + + /// The byte stream of a field: bit-packed, least significant bit first. + fn pack(f: &TestField) -> Vec { + let mut out = Vec::new(); + match f.kind { + Kind::F32 => f + .values + .iter() + .for_each(|v| out.extend((*v as f32).to_le_bytes())), + Kind::F64 => f.values.iter().for_each(|v| out.extend(v.to_le_bytes())), + Kind::Other(_) => {} + Kind::Int(lo, _) | Kind::Scaled(lo, ..) => { + let bits = width(f.kind); + let mut bit = 0usize; + for v in &f.values { + let raw = (*v as i64 - lo) as u64; + for b in 0..bits { + if bit % 8 == 0 { + out.push(0); + } + if (raw >> b) & 1 == 1 { + *out.last_mut().unwrap() |= 1u8 << (bit % 8); + } + bit += 1; + } + } + } + } + out + } + + fn physical(logical: usize) -> usize { + logical / PAGE_DATA * PAGE + logical % PAGE_DATA + } + + fn field_xml(f: &TestField) -> String { + match f.kind { + Kind::F32 => format!(r#"<{} type="Float" precision="single"/>"#, f.name), + Kind::F64 => format!(r#"<{} type="Float"/>"#, f.name), + Kind::Other(kind) => format!(r#"<{} type="{kind}"/>"#, f.name), + Kind::Int(lo, hi) => { + format!( + r#"<{} type="Integer" minimum="{lo}" maximum="{hi}"/>"#, + f.name + ) + } + Kind::Scaled(lo, hi, s, o) => format!( + r#"<{} type="ScaledInteger" minimum="{lo}" maximum="{hi}" scale="{s}" offset="{o}"/>"#, + f.name + ), + } + } + + /// A minimal E57 writer: header, one binary section per scan (an empty + /// packet first, then data packets of at most `chunk` bytes per stream, + /// so values straddle packets), the XML, pages with their checksums. + fn e57_with(scans: &[TestScan], chunk: usize, images: &str) -> Vec { + let mut buf = vec![0u8; 48]; + let mut xml_scans = String::new(); + for scan in scans { + while buf.len() % 4 != 0 { + buf.push(0); + } + let start = buf.len(); + buf.extend([0u8; 32]); + buf.extend([2, 0, 3, 0]); // an empty packet + let streams: Vec> = scan.fields.iter().map(pack).collect(); + let packets = streams + .iter() + .map(|s| s.len().div_ceil(chunk)) + .max() + .unwrap_or(0) + .max(1); + for p in 0..packets { + let parts: Vec<&[u8]> = streams + .iter() + .map(|s| { + let from = (p * chunk).min(s.len()); + &s[from..((p + 1) * chunk).min(s.len())] + }) + .collect(); + let mut packet = vec![1u8, 0, 0, 0]; + packet.extend((parts.len() as u16).to_le_bytes()); + for part in &parts { + packet.extend((part.len() as u16).to_le_bytes()); + } + for part in &parts { + packet.extend_from_slice(part); + } + while packet.len() % 4 != 0 { + packet.push(0); + } + let len = (packet.len() - 1) as u16; + packet[2..4].copy_from_slice(&len.to_le_bytes()); + buf.extend(packet); + } + let section_len = (buf.len() - start) as u64; + buf[start] = 1; + buf[start + 8..start + 16].copy_from_slice(§ion_len.to_le_bytes()); + buf[start + 16..start + 24] + .copy_from_slice(&(physical(start + 32) as u64).to_le_bytes()); + let pose = scan + .pose + .map(|([w, x, y, z], [tx, ty, tz])| { + format!( + r#"{w}{x}{y}{z}{tx}{ty}{tz}"# + ) + }) + .unwrap_or_default(); + let records = scan + .records + .unwrap_or_else(|| scan.fields.first().map_or(0, |f| f.values.len())); + let prototype: String = scan.fields.iter().map(field_xml).collect(); + xml_scans.push_str(&format!( + r#"{pose}{}{prototype}"#, + scan.extra, + physical(start) + )); + } + let xml = format!( + r#" + + +1 +{xml_scans} +{images} +"# + ); + let xml_start = buf.len(); + buf.extend(xml.as_bytes()); + let pages = buf.len().div_ceil(PAGE_DATA); + buf[..8].copy_from_slice(b"ASTM-E57"); + buf[8..12].copy_from_slice(&1u32.to_le_bytes()); + buf[16..24].copy_from_slice(&((pages * PAGE) as u64).to_le_bytes()); + buf[24..32].copy_from_slice(&(physical(xml_start) as u64).to_le_bytes()); + buf[32..40].copy_from_slice(&(xml.len() as u64).to_le_bytes()); + buf[40..48].copy_from_slice(&(PAGE as u64).to_le_bytes()); + buf.resize(pages * PAGE_DATA, 0); + let mut file = Vec::with_capacity(pages * PAGE); + for page in buf.chunks(PAGE_DATA) { + file.extend_from_slice(page); + file.extend([0u8; 4]); + } + seal_pages(&mut file); + file + } + + fn e57(scans: &[TestScan]) -> Vec { + e57_with(scans, 7, "") + } + + fn xyz(kind: Kind, points: &[[f64; 3]]) -> Vec { + ["cartesianX", "cartesianY", "cartesianZ"] + .iter() + .enumerate() + .map(|(i, &name)| field(name, kind, &points.iter().map(|p| p[i]).collect::>())) + .collect() + } + + fn point(mesh: &Mesh, i: usize) -> [f32; 3] { + [ + mesh.positions[3 * i], + mesh.positions[3 * i + 1], + mesh.positions[3 * i + 2], + ] + } + + fn near(a: [f32; 3], b: [f32; 3]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-2) + } + + #[test] + fn the_fuzz_seed_is_a_valid_file() { + // the seed the fuzzer starts from must pass every check of the reader + // (page checksums included): 3 single-precision points with an 8-bit + // intensity, moved 0.1 m along x by the scan's pose + let seed = include_bytes!("../../fuzz/seeds/e57/three-points.e57"); + let mesh = crate::mesh::read("e57", seed).unwrap(); + assert!(mesh.is_point_cloud()); + assert_eq!(mesh.vertex_count(), 3); + assert_eq!(mesh.parts, 1); + assert!( + near(point(&mesh, 0), [100.0, 0.0, 0.0]), + "{:?}", + point(&mesh, 0) + ); + assert!( + near(point(&mesh, 1), [1100.0, 0.0, 250.0]), + "{:?}", + point(&mesh, 1) + ); + assert!( + near(point(&mesh, 2), [600.0, 1000.0, 500.0]), + "{:?}", + point(&mesh, 2) + ); + assert_eq!(mesh.fields.len(), 1); + assert_eq!(mesh.fields[0].name, "Intensity"); + assert_eq!(mesh.thinned, None); + } + + #[test] + fn crc32c_matches_the_standard_check_value() { + assert_eq!(crc32c(&crc_table(), b"123456789"), 0xE306_9283); + assert_eq!(crc32c(&crc_table(), b""), 0); + } + + #[test] + fn scans_are_moved_by_their_pose_and_converted_to_mm() { + let half = std::f64::consts::FRAC_1_SQRT_2; + let file = e57(&[ + TestScan { + fields: xyz(Kind::F32, &[[1.0, 0.0, 0.0], [0.0, 2.0, 0.0]]), + pose: Some(([1.0, 0.0, 0.0, 0.0], [10.0, 0.0, 0.0])), + ..TestScan::default() + }, + TestScan { + // 90° about z, then 5 m up + fields: xyz(Kind::F64, &[[1.0, 0.0, 0.0]]), + pose: Some(([half, 0.0, 0.0, half], [0.0, 0.0, 5.0])), + ..TestScan::default() + }, + ]); + let mesh = crate::mesh::read("e57", &file).unwrap(); + assert!(mesh.is_point_cloud()); + assert_eq!(mesh.vertex_count(), 3); + assert_eq!(mesh.parts, 2); + assert!( + near(point(&mesh, 0), [11000.0, 0.0, 0.0]), + "{:?}", + point(&mesh, 0) + ); + assert!(near(point(&mesh, 1), [10000.0, 2000.0, 0.0])); + assert!( + near(point(&mesh, 2), [0.0, 1000.0, 5000.0]), + "{:?}", + point(&mesh, 2) + ); + assert!(mesh.colors.is_empty() && mesh.fields.is_empty()); + assert_eq!(mesh.thinned, None); + } + + #[test] + fn spherical_and_scaled_integer_coordinates() { + let file = e57(&[TestScan { + fields: vec![ + // 2 m and 1 m in millimetre steps + field( + "sphericalRange", + Kind::Scaled(0, 10_000, 0.001, 0.0), + &[2000.0, 1000.0], + ), + field( + "sphericalAzimuth", + Kind::F64, + &[std::f64::consts::FRAC_PI_2, 0.0], + ), + field( + "sphericalElevation", + Kind::F32, + &[0.0, std::f64::consts::FRAC_PI_2 as f32 as f64], + ), + ], + ..TestScan::default() + }]); + let mesh = read_e57(&file).unwrap(); + assert_eq!(mesh.vertex_count(), 2); + assert!( + near(point(&mesh, 0), [0.0, 2000.0, 0.0]), + "{:?}", + point(&mesh, 0) + ); + assert!( + near(point(&mesh, 1), [0.0, 0.0, 1000.0]), + "{:?}", + point(&mesh, 1) + ); + + // cartesian scaled integers with an offset: raw · 0.01 + 5 + let file = e57(&[TestScan { + fields: xyz( + Kind::Scaled(-1000, 1000, 0.01, 5.0), + &[[100.0, -500.0, 0.0]], + ), + ..TestScan::default() + }]); + let mesh = read_e57(&file).unwrap(); + assert!( + near(point(&mesh, 0), [6000.0, 0.0, 5000.0]), + "{:?}", + point(&mesh, 0) + ); + } + + #[test] + fn colours_are_scaled_by_their_limits() { + let mut fields = xyz(Kind::F32, &[[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]); + fields.push(field("colorRed", Kind::Int(0, 65535), &[65535.0, 0.0])); + fields.push(field("colorGreen", Kind::Int(0, 65535), &[0.0, 32768.0])); + fields.push(field("colorBlue", Kind::Int(0, 65535), &[0.0, 65535.0])); + // without colorLimits: the prototype's minimum and maximum + let file = e57(&[TestScan { + fields, + ..TestScan::default() + }]); + let mesh = read_e57(&file).unwrap(); + assert_eq!(mesh.colors, [255, 0, 0, 0, 128, 255]); + assert!(mesh.fields.is_empty()); + + // colorLimits narrower than the stored range: values above clamp + let mut fields = xyz(Kind::F32, &[[0.0, 0.0, 0.0]]); + fields.push(field("colorRed", Kind::Int(0, 255), &[100.0])); + fields.push(field("colorGreen", Kind::Int(0, 255), &[50.0])); + fields.push(field("colorBlue", Kind::Int(0, 255), &[0.0])); + let limits = r#"010001000100"#; + let file = e57(&[TestScan { + fields, + extra: limits.into(), + ..TestScan::default() + }]); + assert_eq!(read_e57(&file).unwrap().colors, [255, 128, 0]); + } + + #[test] + fn intensity_colours_a_cloud_without_colours() { + let mut fields = xyz( + Kind::F32, + &[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0]], + ); + fields.push(field( + "intensity", + Kind::Int(0, 2047), + &[0.0, 1000.0, 2000.0], + )); + let limits = r#"02000"#; + let file = e57(&[TestScan { + fields, + extra: limits.into(), + ..TestScan::default() + }]); + let mesh = read_e57(&file).unwrap(); + assert_eq!(mesh.fields.len(), 1); + assert_eq!(mesh.fields[0].name, "Intensity"); + assert_eq!(mesh.fields[0].values, [0.0, 0.5, 1.0]); + assert_eq!( + mesh.colors.len(), + mesh.positions.len(), + "baked for old viewers" + ); + assert!(mesh.check().is_ok()); + } + + #[test] + fn invalid_points_unknown_fields_and_images_are_left_out() { + let mut fields = xyz( + Kind::F64, + &[ + [1.0, 0.0, 0.0], + [2.0, 0.0, 0.0], + [3.0, 0.0, 0.0], + [4.0, 0.0, 0.0], + ], + ); + fields.insert( + 0, + field("rowIndex", Kind::Int(0, 10), &[0.0, 1.0, 2.0, 3.0]), + ); + fields.push(field( + "cartesianInvalidState", + Kind::Int(0, 2), + &[0.0, 2.0, 1.0, 0.0], + )); + fields.push(field("timeStamp", Kind::F64, &[0.5, 0.6, 0.7, 0.8])); + fields.push(field("returnCount", Kind::Int(1, 1), &[1.0; 4])); + let images = r#""#; + let file = e57_with( + &[TestScan { + fields, + ..TestScan::default() + }], + 3, + images, + ); + let mesh = read_e57(&file).unwrap(); + assert_eq!(mesh.vertex_count(), 2); + assert!(near(point(&mesh, 0), [1000.0, 0.0, 0.0])); + assert!(near(point(&mesh, 1), [4000.0, 0.0, 0.0])); + + // every point invalid: no geometry + let mut fields = xyz(Kind::F32, &[[1.0, 0.0, 0.0]]); + fields.push(field("sphericalInvalidState", Kind::Int(0, 2), &[2.0])); + let file = e57(&[TestScan { + fields, + ..TestScan::default() + }]); + let err = crate::mesh::read("e57", &file).unwrap_err().to_string(); + assert!(err.contains("no geometry"), "{err}"); + } + + #[test] + fn large_clouds_are_thinned_evenly_over_all_scans() { + let file = e57(&[ + TestScan { + fields: xyz( + Kind::F32, + &[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0]], + ), + ..TestScan::default() + }, + TestScan { + fields: xyz(Kind::F32, &[[3.0, 0.0, 0.0], [4.0, 0.0, 0.0]]), + ..TestScan::default() + }, + ]); + // 5 points, budget 2: every third point over both scans + let mesh = read_within(&file, 2).unwrap(); + assert_eq!(mesh.vertex_count(), 2); + assert!(near(point(&mesh, 0), [0.0, 0.0, 0.0])); + assert!(near(point(&mesh, 1), [3000.0, 0.0, 0.0])); + assert_eq!(mesh.thinned, Some(5)); + assert_eq!(read_within(&file, 5).unwrap().thinned, None); + // the note survives the wire format + assert_eq!(Mesh::decode(&mesh.encode()).unwrap().thinned, Some(5)); + } + + #[test] + fn a_flipped_byte_is_refused() { + let file = e57(&[TestScan { + fields: xyz(Kind::F32, &[[1.0, 2.0, 3.0]]), + ..TestScan::default() + }]); + assert!(read_e57(&file).is_ok()); + for at in [100, 600, file.len() - 10] { + let mut damaged = file.clone(); + damaged[at] ^= 0x10; + let err = read_e57(&damaged).unwrap_err().to_string(); + assert!( + err.contains("damaged") && err.contains("checksum"), + "{at}: {err}" + ); + } + // the page is named + if file.len() > PAGE { + let mut damaged = file.clone(); + damaged[PAGE + 5] ^= 1; + let err = read_e57(&damaged).unwrap_err().to_string(); + assert!(err.contains("page 2"), "{err}"); + } + // little-endian checksums are accepted as well + let mut le = file.clone(); + for page in le.chunks_exact_mut(PAGE) { + page[PAGE_DATA..].reverse(); + } + assert!(read_e57(&le).is_ok()); + } + + #[test] + fn damaged_structure_is_an_error_not_a_panic() { + let file = e57(&[TestScan { + fields: xyz(Kind::F32, &[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), + ..TestScan::default() + }]); + assert!(read_e57(b"not an e57 file").is_err()); + assert!(read_e57(&file[..40]).is_err(), "header cut short"); + let err = read_e57(&file[..file.len() - PAGE.min(file.len() - 48)]) + .unwrap_err() + .to_string(); + assert!(err.contains("ends early"), "{err}"); + let mut version = file.clone(); + version[8] = 2; + assert!(read_e57(&version) + .unwrap_err() + .to_string() + .contains("version 2")); + let mut pages = file.clone(); + pages[41] = 0x08; // 2048-byte pages + assert!(read_e57(&pages) + .unwrap_err() + .to_string() + .contains("pages of")); + + // more points claimed than stored + let file = e57(&[TestScan { + fields: xyz(Kind::F32, &[[1.0, 2.0, 3.0]]), + records: Some(5), + ..TestScan::default() + }]); + let err = read_e57(&file).unwrap_err().to_string(); + assert!(err.contains("ends before its 5 points"), "{err}"); + + // no coordinates + let file = e57(&[TestScan { + fields: vec![field("intensity", Kind::F32, &[1.0])], + ..TestScan::default() + }]); + let err = read_e57(&file).unwrap_err().to_string(); + assert!(err.contains("neither cartesian nor spherical"), "{err}"); + + // no scans, only images + let err = read_e57(&e57(&[])).unwrap_err().to_string(); + assert!(err.contains("no 3D scan"), "{err}"); + + // a blob field in the prototype + let mut fields = xyz(Kind::F32, &[[1.0, 2.0, 3.0]]); + fields.push(field("label", Kind::Other("Blob"), &[])); + let file = e57(&[TestScan { + fields, + ..TestScan::default() + }]); + let err = read_e57(&file).unwrap_err().to_string(); + assert!(err.contains("does not read"), "{err}"); + } + + #[test] + fn the_bit_stream_continues_across_packets() { + let mut s = Stream { + role: Role::Other, + codec: Codec::Int { + min: -3, + bits: 3, + scale: 1.0, + offset: 0.0, + }, + bounds: None, + bytes: vec![0b1010_1100], + bit: 0, + }; + // 100 = 4, 101 = 5, then two bits of the next value + assert_eq!(s.next(), 1.0); + assert_eq!(s.next(), 2.0); + assert_eq!(s.available(), 2); + s.compact(); + assert_eq!((s.bytes.len(), s.bit), (1, 6)); + s.bytes.push(0b0000_0001); // the third value's high bit + assert_eq!(s.available(), 10); + assert_eq!(s.next(), (0b110 - 3) as f64); + assert_eq!(rotation([0.0; 4]), rotation([1.0, 0.0, 0.0, 0.0])); + } +} diff --git a/src/mesh/helpers.rs b/src/mesh/helpers.rs index 62f4ca85..448f163c 100755 --- a/src/mesh/helpers.rs +++ b/src/mesh/helpers.rs @@ -92,7 +92,12 @@ pub(crate) fn check_triangles(n: usize) -> Result<()> { /// Every `stride`-th point of a point cloud with `count` points. pub(crate) fn stride_for(count: usize) -> usize { - count.div_ceil(MAX_POINTS).max(1) + stride_within(count, MAX_POINTS) +} + +/// Every `stride`-th point of `count` points keeps at most `budget` of them. +pub(crate) fn stride_within(count: usize, budget: usize) -> usize { + count.div_ceil(budget.max(1)).max(1) } /// Thins out a point cloud that has more than [`MAX_POINTS`] points. @@ -101,6 +106,8 @@ pub(crate) fn thin_out(mesh: &mut Mesh) { return; } let stride = stride_for(mesh.vertex_count()); + let count = mesh.vertex_count() as u64; + mesh.thinned = Some(mesh.thinned.map_or(count, |t| t.max(count))); let keep = |v: &[f32]| v.to_vec(); mesh.positions = mesh .positions @@ -208,6 +215,9 @@ mod tests { assert_eq!(stride_for(MAX_POINTS + 1), 2); assert_eq!(stride_for(3 * MAX_POINTS), 3); assert_eq!(stride_for(3 * MAX_POINTS + 1), 4); + assert_eq!(stride_within(5, 2), 3); + assert_eq!(stride_within(5, 0), 5, "a budget of 0 counts as 1"); + assert_eq!(stride_within(0, 2), 1); } #[test] @@ -227,6 +237,7 @@ mod tests { }; thin_out(&mut cloud); assert_eq!(cloud.vertex_count(), 10); + assert_eq!(cloud.thinned, None); // one point more: every second point, with its colour and field value let n = MAX_POINTS + 1; let mut cloud = Mesh { @@ -241,6 +252,7 @@ mod tests { }; thin_out(&mut cloud); assert_eq!(cloud.vertex_count(), n.div_ceil(2)); + assert_eq!(cloud.thinned, Some(n as u64)); assert_eq!(cloud.colors.len(), cloud.positions.len()); assert_eq!(cloud.fields[0].values.len(), cloud.vertex_count()); assert_eq!(&cloud.positions[3..6], &[2.0, 0.0, 0.0]); diff --git a/src/mesh/model.rs b/src/mesh/model.rs index 0a5457a1..a24cd6c9 100755 --- a/src/mesh/model.rs +++ b/src/mesh/model.rs @@ -29,6 +29,9 @@ pub struct Mesh { /// A partial preview: (faces shown, faces in the file) – STEP files /// whose B-rep the kernel could tessellate only in part. pub faces: Option<(u32, u32)>, + /// A point cloud thinned out for the preview: the number of points in + /// the file (the preview shows `vertex_count()` of them, evenly spread). + pub thinned: Option, } /// Fields a mesh carries at most (the viewer offers them in a selector). @@ -244,20 +247,22 @@ impl Mesh { /// ```text /// 0 "TCMESH01" /// 8 u32 vertices 12 u32 indices 16 u32 parts - /// 20 u32 flags (1 = colours, 2 = fields, 4 = partial preview) + /// 20 u32 flags (1 = colours, 2 = fields, 4 = partial preview, 8 = thinned point cloud) /// 24 f32 × 6 bounding box /// 48 f32 × 3·vertices, u32 × indices, u8 × 3·vertices (colours, padded to 4 bytes) /// only with flag 2, after that: /// u32 field count, then per field /// u32 n, n bytes name (UTF-8), u32 m, m bytes unit, padding to 4 bytes, /// f32 min, f32 max, f32 × vertices (NaN = no value) + /// with flag 8, after that: u64 points in the file (the cloud was thinned) /// with flag 4, the last 8 bytes of the file: u32 faces shown, u32 faces in the file /// ``` /// /// Viewers that do not know flag 2 ignore the field section; meshes /// with fields also carry the first field as colours for them. The face /// count sits at the very end, so viewers that do not know flag 4 – and - /// the field section in between – are not affected. + /// the field section in between – are not affected. The point count of + /// flag 8 sits between the two, so neither older reader sees it. pub fn encode(&self) -> Vec { let field_bytes: usize = self .fields @@ -269,12 +274,13 @@ impl Mesh { + self.indices.len() * 4 + self.colors.len() + field_bytes - + 4, + + 20, ); out.extend_from_slice(MAGIC); let flags = u32::from(!self.colors.is_empty()) | (u32::from(!self.fields.is_empty()) << 1) - | (u32::from(self.faces.is_some()) << 2); + | (u32::from(self.faces.is_some()) << 2) + | (u32::from(self.thinned.is_some()) << 3); for v in [ self.vertex_count() as u32, self.indices.len() as u32, @@ -314,6 +320,9 @@ impl Mesh { } } } + if let Some(total) = self.thinned { + out.extend_from_slice(&total.to_le_bytes()); + } // last, so that viewers that do not know flag 4 are not affected if let Some((shown, total)) = self.faces { out.extend_from_slice(&shown.to_le_bytes()); @@ -397,6 +406,14 @@ impl Mesh { } end = at; } + // flag 8: the point count of a thinned cloud, after the fields + let thinned = if flags & 8 == 8 { + let total = u64_le(data, end).context("truncated mesh")?; + end += 8; + Some(total) + } else { + None + }; // flag 4: the face count in the last 8 bytes, after everything else let faces = if flags & 4 == 4 { if data.len() < end + 8 { @@ -414,6 +431,7 @@ impl Mesh { parts: parts as u32, fields, faces, + thinned, }) } } @@ -550,6 +568,41 @@ mod tests { assert!(Mesh::decode(&short).is_err()); } + #[test] + fn thinned_clouds_carry_their_point_count() { + let mut cloud = Mesh { + positions: vec![0.0, 0.0, 0.0, 1.0, 2.0, 3.0], + colors: vec![1, 2, 3, 4, 5, 6], + parts: 1, + ..Mesh::default() + }; + let plain = cloud.encode(); + cloud.thinned = Some(5_000_000_000); + let thinned = cloud.encode(); + assert_eq!(flags(&thinned), 1 | 8); + assert_eq!(thinned.len(), plain.len() + 8); + assert_eq!(thinned.len() % 4, 0); + assert_eq!(Mesh::decode(&thinned).unwrap(), cloud); + assert!(Mesh::decode(&thinned[..thinned.len() - 4]).is_err()); + + // with fields and a face count: fields, then the point count, then + // the face count in the last 8 bytes + cloud.fields = vec![Field { + name: "Intensity".into(), + unit: String::new(), + values: vec![0.0, 1.0], + }]; + cloud.faces = Some((1, 2)); + let all = cloud.encode(); + assert_eq!(flags(&all), 1 | 2 | 4 | 8); + assert_eq!(all[all.len() - 8..all.len() - 4], 1u32.to_le_bytes()); + assert_eq!( + all[all.len() - 16..all.len() - 8], + 5_000_000_000u64.to_le_bytes() + ); + assert_eq!(Mesh::decode(&all).unwrap(), cloud); + } + #[test] fn the_colour_map_runs_from_the_first_to_the_last_stop() { assert_eq!(color_map(0.0), COLOR_MAP[0]); diff --git a/src/mesh/points.rs b/src/mesh/points.rs old mode 100755 new mode 100644 index f586c802..53ec4d69 --- a/src/mesh/points.rs +++ b/src/mesh/points.rs @@ -7,16 +7,28 @@ use super::*; /// `x y z [intensity] [r g b]` per line (spaces, commas or semicolons); lines /// that are not numbers (headers, the point count of .pts files) are skipped. pub(super) fn read_text(data: &[u8]) -> Result { + read_text_within(data, MAX_POINTS) +} + +/// [`read_text`] with a point budget (tests use a small one). +/// +/// The stride starts from an estimate of the row count (the first lines); +/// when the kept points reach the budget, every second one is dropped and the +/// stride doubles, so the kept rows stay evenly spread over the whole file +/// even when the estimate was too low. +fn read_text_within(data: &[u8], budget: usize) -> Result { + let budget = budget.max(1); let text = text(data); - // estimate the number of points from the first lines to thin out evenly let sample: Vec = text.lines().take(1000).map(|l| l.len() + 1).collect(); let average = (sample.iter().sum::() / sample.len().max(1)).max(8); - let stride = stride_for(data.len() / average); + let mut stride = stride_within(data.len() / average, budget); let mut mesh = Mesh { parts: 1, ..Mesh::default() }; - let mut colors = Vec::new(); + let mut colors: Vec = Vec::new(); + // colours are kept only while every kept row has one + let mut colored = true; let mut row = 0usize; for line in text.lines() { let values: Vec = line @@ -31,24 +43,52 @@ pub(super) fn read_text(data: &[u8]) -> Result { if (row - 1) % stride != 0 { continue; } + if mesh.vertex_count() >= budget { + // kept rows are 0, s, 2s, …: keep 0, 2s, 4s, … and double s + halve(&mut mesh.positions); + if colored { + halve(&mut colors); + } + stride = stride.saturating_mul(2); + if (row - 1) % stride != 0 { + continue; + } + } mesh.vertex([*x, *y, *z]); // the last three values are the colour (an intensity may come first) - if let [.., r, g, b] = rest { - let rgb = [*r, *g, *b]; - if rgb.iter().all(|c| (0.0..=255.0).contains(c)) { - colors.extend(rgb.iter().map(|c| *c as u8)); + if colored { + match rest { + [.., r, g, b] if [r, g, b].iter().all(|c| (0.0..=255.0).contains(*c)) => { + colors.extend([*r as u8, *g as u8, *b as u8]); + } + _ => { + colored = false; + colors = Vec::new(); + } } } - if mesh.vertex_count() > MAX_POINTS { - break; - } } - if colors.len() == mesh.positions.len() { + if colored && colors.len() == mesh.positions.len() { mesh.colors = colors; } + // every row was counted, also those dropped for the budget + if mesh.vertex_count() < row { + mesh.thinned = Some(row as u64); + } Ok(mesh) } +/// Keeps every second triple (x y z or r g b) of `values`. +fn halve(values: &mut Vec) { + let kept: Vec = values + .chunks_exact(3) + .step_by(2) + .flatten() + .copied() + .collect(); + *values = kept; +} + pub(super) fn read_las(data: &[u8]) -> Result { if data.len() < 227 || data.get(..4) != Some(b"LASF".as_slice()) { bail!("Not a LAS file."); @@ -84,6 +124,7 @@ pub(super) fn read_las(data: &[u8]) -> Result { let stride = stride_for(count); let mut mesh = Mesh { parts: 1, + thinned: (count > MAX_POINTS).then_some(count as u64), ..Mesh::default() }; let mut raw_colors: Vec = Vec::new(); @@ -170,4 +211,36 @@ mod tests { assert!(read_las(b"LASF").is_err(), "header cut short"); assert!(read_las(b"not a las file at all").is_err()); } + + #[test] + fn text_points_are_thinned_over_the_whole_file() { + // long first lines make the row estimate far too low: 1000 padded + // lines, then 3000 short ones, x = row number, all with a colour + let mut file = String::new(); + for row in 0..4000 { + let pad = if row < 1000 { + " ".repeat(100) + } else { + String::new() + }; + file.push_str(&format!("{row} 0 0{pad} 1 2 3\n")); + } + let cloud = read_text_within(file.as_bytes(), 100).unwrap(); + assert!(cloud.vertex_count() <= 100, "{}", cloud.vertex_count()); + assert!(cloud.vertex_count() >= 50, "{}", cloud.vertex_count()); + assert_eq!(cloud.thinned, Some(4000)); + let xs: Vec = cloud.positions.chunks_exact(3).map(|p| p[0]).collect(); + assert_eq!(xs[0], 0.0); + assert!(*xs.last().unwrap() > 3500.0, "the end of the file is kept"); + // evenly spaced rows + let step = xs[1] - xs[0]; + assert!(xs.windows(2).all(|w| w[1] - w[0] == step)); + assert_eq!(cloud.colors.len(), cloud.positions.len()); + assert_eq!(&cloud.colors[..3], &[1, 2, 3]); + + // within the budget nothing is dropped and nothing is marked thinned + let small = read_text_within(file.as_bytes(), 4000).unwrap(); + assert_eq!(small.vertex_count(), 4000); + assert_eq!(small.thinned, None); + } } diff --git a/src/preview.rs b/src/preview.rs index f821f8e5..5a974e83 100755 --- a/src/preview.rs +++ b/src/preview.rs @@ -247,6 +247,8 @@ pub enum PreviewFormat { Pts, Xyz, Las, + /// E57 scans (ASTM E2807): every scan placed by its pose. + E57, /// Simulation results (see `simmesh`): legacy VTK, VTU, VTP, CalculiX FRD. VtkLegacy, Vtu, @@ -255,7 +257,7 @@ pub enum PreviewFormat { } impl PreviewFormat { - pub const ALL: [PreviewFormat; 30] = [ + pub const ALL: [PreviewFormat; 31] = [ PreviewFormat::Stl, PreviewFormat::Obj, PreviewFormat::Ply, @@ -282,6 +284,7 @@ impl PreviewFormat { PreviewFormat::Pts, PreviewFormat::Xyz, PreviewFormat::Las, + PreviewFormat::E57, PreviewFormat::VtkLegacy, PreviewFormat::Vtu, PreviewFormat::Vtp, @@ -327,6 +330,7 @@ impl PreviewFormat { PreviewFormat::Pts => "pts", PreviewFormat::Xyz => "xyz", PreviewFormat::Las => "las", + PreviewFormat::E57 => "e57", PreviewFormat::VtkLegacy => "vtk-legacy", PreviewFormat::Vtu => "vtk-unstructured", PreviewFormat::Vtp => "vtk-polydata", @@ -365,7 +369,7 @@ impl PreviewFormat { pub fn is_point_cloud(self) -> bool { matches!( self, - PreviewFormat::Pts | PreviewFormat::Xyz | PreviewFormat::Las + PreviewFormat::Pts | PreviewFormat::Xyz | PreviewFormat::Las | PreviewFormat::E57 ) } @@ -1376,6 +1380,8 @@ mod tests { assert_eq!(PreviewFormat::of(".stl"), None); assert!(PreviewFormat::Step.is_brep() && !PreviewFormat::Stl.is_brep()); assert!(PreviewFormat::Las.is_point_cloud()); + assert_eq!(PreviewFormat::of("scan.e57"), Some(PreviewFormat::E57)); + assert!(PreviewFormat::E57.is_point_cloud() && !PreviewFormat::E57.is_brep()); assert_eq!(PreviewFormat::of("chair.3dm"), Some(PreviewFormat::Rhino)); assert_eq!(PreviewFormat::of("beam.vtu"), Some(PreviewFormat::Vtu)); assert_eq!( diff --git a/src/shape.rs b/src/shape.rs index e732faa4..3e09ed75 100755 --- a/src/shape.rs +++ b/src/shape.rs @@ -695,6 +695,7 @@ mod tests { parts: 1, fields: Vec::new(), faces: None, + thinned: None, } } @@ -719,6 +720,7 @@ mod tests { parts: 1, fields: Vec::new(), faces: None, + thinned: None, } } diff --git a/tests/parser_corpus.rs b/tests/parser_corpus.rs index 42f40129..cfa72820 100755 --- a/tests/parser_corpus.rs +++ b/tests/parser_corpus.rs @@ -27,6 +27,7 @@ fn fixture_types(target: &str) -> Option<&'static [&'static str]> { // The STEP tessellation is slow in a debug build: only small files. "mesh_step" => &["stp"], "mesh" => &["3dm"], + "e57" => &["e57"], _ => return None, }) }