ifc_lite_cache/lib.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Native writer for the browser-readable `.ifclite` cache, format v28
6//! (`@ifc-lite/cache`, `packages/cache/src/types.ts` `FORMAT_VERSION`), so a
7//! server or function can build the cache a browser then only reads (#9584).
8//!
9//! Two entry points with one output: [`build_cache`] builds the cache in
10//! memory, [`build_cache_to_path`] streams it to a file without holding the
11//! mesh set, and the two are byte-identical for the same input and options
12//! (`tests/streamed_matches_in_memory.rs`). The `ifc-build-cache` binary is a
13//! thin CLI over the second. Both run the canonical pipeline and add no
14//! ingest or geometry of their own: the scalar sections come from
15//! `ifc_lite_processing::data_model::extract_data_model_with` (rooted
16//! entities; property and quantity tables off), the geometry from
17//! `ifc_lite_processing::process`. Each section module mirrors its TS
18//! serializer field for field and names it.
19//!
20//! # Determinism
21//!
22//! The output is a pure function of the source bytes and [`CacheOptions`]:
23//! meshes are chunked in the pipeline's emit order (pinned by the
24//! mesh-determinism contract, independent of thread count), the data model's
25//! tables are ordered, and deflate is `miniz_oxide` at a fixed level. The
26//! stored chunk bytes therefore differ from the TS writer's (node zlib), which
27//! moves directory `byteOffset`/`byteLength` and can flip a chunk's
28//! `DeflateRaw` flag; the inflated payloads are what the two writers share.
29//! `scripts/cache-native-conformance.mjs` checks both properties.
30//!
31//! # What the native pipeline does not produce
32//!
33//! Each is a value the format and the TS reader accept; none is faked:
34//!
35//! - **Properties / Quantities** are written empty, as the TS writer does for
36//! a STEP-parsed store (`packages/cache/README.md`).
37//! - **Selection coverage** (the v28 EntityIndex trailer, #9947) is written
38//! absent: it is computed by the TS parser alone
39//! (`selection-relationship-index.ts`), and porting it would be a second
40//! ingest implementation.
41//! - **InstancedShards** (IFNS) are never written: native `process` has no
42//! GPU-instancing partition, so every occurrence is a flat mesh.
43//! - **Appearance provenance** (v19) is mode 0 on every mesh and the source
44//! pool is empty: canonical-item source indices are a browser-batch output.
45//! - **`shadingColor`** (v25) is never present: the native pass reports one
46//! colour per mesh and no distinct authored DiffuseColour.
47//! - **Mesh frame.** Native `process` meshes with its own per-mesh origins
48//! (zero for most meshes; the browser path stores local-frame origins) and
49//! in its own frame tier. Its translation is recorded as `wasmRtcOffset`;
50//! when the `IfcSite`-local tier also removed the site rotation, which
51//! `CoordinateInfo` cannot express, the writer puts that rotation back into
52//! the stored origins, positions and normals (`pipeline.rs`), so every
53//! vertex reads back at `MeshFrame::to_world` of its pass-frame point.
54//! `wasmRtcFrame`, `buildingRotation` and `boundsRecoveryFallbackCount` are
55//! left absent (each is producer provenance of the browser path;
56//! `buildingRotation` orients camera presets and is never applied to
57//! geometry).
58//! - **Entity rows** are the data model's rooted table and naming rules (an
59//! explicit `''` Name and the own-Representation flag are re-read from the
60//! source, which the data model does not carry: `row_facts.rs`), not the
61//! TS parser's row selection, so the scalar sections encode the same model
62//! the TS writer would be handed for this data, not the bytes a TS parse of
63//! the same file produces. `scripts/cache-native-conformance.mjs` states
64//! and checks the row-set difference against a TS parse.
65
66mod buf;
67mod build;
68mod entities;
69mod entity_index;
70mod format;
71mod geometry;
72mod pipeline;
73mod relationships;
74mod row_facts;
75mod stream;
76mod strings;
77mod type_enum;
78
79use std::path::Path;
80
81pub use format::FORMAT_VERSION;
82
83/// What to write. [`Default`] matches the TS writer's defaults.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub struct CacheOptions {
86 /// Run the geometry pass and write the Geometry section (`includeGeometry`).
87 pub include_geometry: bool,
88 /// Store `sourceHash = 0` and set `HeaderFlags.SourceHashUnset` instead of
89 /// hashing the whole source (`omitSourceHash`).
90 pub omit_source_hash: bool,
91 /// Deflate-raw chunks of 64 KiB and up when that is smaller
92 /// (`compressGeometryChunks`).
93 pub compress_geometry_chunks: bool,
94}
95
96impl Default for CacheOptions {
97 fn default() -> Self {
98 Self { include_geometry: true, omit_source_hash: false, compress_geometry_chunks: true }
99 }
100}
101
102/// What a build produced. Both entry points report the same values for the
103/// same input and options.
104#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
105pub struct CacheStats {
106 /// STEP instances in the source: the header's `entityCount`.
107 pub entity_count: u64,
108 /// Rows in the Entities section.
109 pub entity_rows: u64,
110 pub mesh_count: u64,
111 /// Meshes the TS `validateMeshes` rules drop (absurd counts, unpaired normals).
112 pub skipped_meshes: u64,
113 pub chunk_count: u64,
114 pub total_vertices: u64,
115 pub total_triangles: u64,
116 pub cache_bytes: u64,
117 /// Distinct chunk grid cells. A cell's chunk stays open until the 8 MiB
118 /// soft cap or the end of the pass closes it, and each holds under the
119 /// cap plus at most one more mesh of any size, so the geometry a build
120 /// holds at once is bounded per cell: this times the cap, plus one mesh
121 /// per cell.
122 pub chunk_cells: u64,
123 /// The most serialized record bytes the open chunks held at once: the
124 /// measured side of that bound.
125 pub peak_open_chunk_bytes: u64,
126}
127
128#[derive(Debug, thiserror::Error)]
129#[non_exhaustive]
130pub enum CacheError {
131 /// Section and chunk offsets and lengths are u32, so a cache this large
132 /// cannot be addressed. Refused, never wrapped; the streaming writer
133 /// refuses as soon as the geometry it has spooled crosses the bound.
134 #[error("cache would be at least {0} bytes; the format addresses at most 4 GiB")]
135 TooLarge(u64),
136 /// EntityIndex spans are u32 offsets into the source: a larger source
137 /// cannot be indexed without wrapping.
138 #[error("source is {0} bytes; the entity index addresses at most 4 GiB")]
139 SourceTooLarge(u64),
140 /// EntityIndex type indices are u16 (the TS writer refuses the same).
141 #[error("source has {0} distinct entity type names; the entity index holds at most 65536")]
142 TooManyTypeNames(usize),
143 /// Writing the output or its staging files.
144 #[error("{context}: {source}")]
145 Io {
146 context: String,
147 #[source]
148 source: std::io::Error,
149 },
150}
151
152/// The length of `payload` under the writer's own chunk compressor. For
153/// `scripts/cache-native-conformance.mjs` only: a chunk stored raw above the
154/// compression floor must not have been strictly smaller compressed, and only
155/// the writer's compressor can say so.
156#[doc(hidden)]
157pub fn deflate_raw_len(payload: &[u8]) -> usize {
158 geometry::chunks::deflate_raw(payload).len()
159}
160
161/// Build a complete `.ifclite` cache for `source` (the IFC STEP bytes), in
162/// memory: the pipeline retains every mesh.
163pub fn build_cache(source: &[u8], options: CacheOptions) -> Result<(Vec<u8>, CacheStats), CacheError> {
164 build::build(source, &options, format::Limits::FORMAT)
165}
166
167/// Build the same cache straight to `output`: byte-identical to
168/// [`build_cache`] for the same input and options, without holding the mesh
169/// set. The pipeline runs with `retain_meshes` off; each chunk is serialized
170/// when it closes and appended to a spool file beside `output`, so only the
171/// open chunks and the 44-byte directory entries stay in memory.
172///
173/// `output` appears complete or not at all: the cache is written to a
174/// temporary file in the same directory, synced, then renamed over it. On
175/// any error before the rename, the temporary file and the spool are removed
176/// and an existing `output` is left untouched. An error from syncing the
177/// parent directory after the rename (Unix) means `output` already holds the
178/// complete new cache, but the rename may not survive a crash.
179pub fn build_cache_to_path(source: &[u8], output: &Path, options: CacheOptions) -> Result<CacheStats, CacheError> {
180 stream::build_to_path(source, output, &options, format::Limits::FORMAT, stream::BATCH_JOBS)
181}