Skip to main content

ifc_lite_processing/style/
mod.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//! Canonical IFC styling — the single source of truth for mesh colors,
6//! shared between the HTTP server, the native pipeline, and the browser-side
7//! WASM bindings (issue #913).
8//!
9//! This mirrors the [`crate::symbolic`] split: presentation logic that used
10//! to be copied into every consumer (`wasm-bindings`, `processing`,
11//! `apps/server`, the now-discontinued desktop app) lives here exactly once.
12//! See issue #913 for the design and rationale.
13//!
14//! Phase 0 (this commit) introduces only the two pieces with no decoder or
15//! geometry dependency — the canonical [`Rgba`] color type and the single
16//! [`default_color_for_type`] table — and wires nothing into the pipeline
17//! yet. The decoder-driven resolver (`StyleIndex`, `IfcStyledItem` /
18//! `IfcIndexedColourMap` / material-chain resolution) arrives in Phase 2.
19//!
20//! ## Canonical contracts
21//!
22//! - **`f32` is canonical; `u8` is transport-only.** Colors are [`Rgba`]
23//!   ([`f32; 4`], straight-alpha, `0.0..=1.0`) end-to-end. The browser's
24//!   8-bit SharedArrayBuffer transport is expressed *only* through
25//!   [`Rgba::to_rgba8`] / [`Rgba::from_rgba8`]; the backend stays exact.
26//!   (Decision §8.3 of the plan.)
27//! - **One default table.** [`default_color_for_type`] is the only
28//!   IFC-type → color map in Rust. A CI guard (Phase 1) fails the build if a
29//!   second one appears.
30
31use ifc_lite_core::IfcType;
32
33pub(crate) mod fill;
34mod indexed_colour;
35mod material;
36mod surface;
37// Public styling resolvers — the single shared implementation that both the
38// native pipeline and the browser `wasm-bindings` call (issue #913, Phase 2e).
39// `split_mesh_by_indexed_colour` is also public so the browser `processGeometryBatch`
40// path can restore the per-triangle palette split it lost in the #874 mesh-pipeline
41// unification (issue #858) — keeping one shared splitter rather than a wasm copy.
42pub use indexed_colour::{
43    resolve_indexed_colour_map_full, split_mesh_by_indexed_colour, FullIndexedColourMap,
44};
45pub use material::{
46    build_element_material_colors, build_material_style_index, flatten_material_color_index,
47    pick_material_style_for_submesh, pick_opaque_first, resolve_material_ids,
48    resolve_submesh_color,
49};
50pub use surface::extract_surface_style_colors;
51
52/// Alpha at or above which a color is treated as opaque.
53///
54/// Used by submesh material selection (Phase 2) to prefer glass (transparent)
55/// vs frame (opaque) styles. Matches the browser's `TRANSPARENCY_ALPHA_THRESHOLD`.
56pub const TRANSPARENCY_ALPHA_THRESHOLD: f32 = 0.95;
57
58/// Resolved appearance of one geometry item (the value side of the
59/// styled-item index keyed by geometry express id).
60///
61/// Lives here — not in `processor.rs` — because it is shared by the native
62/// pipeline, the canonical per-element producer ([`crate::element`]), and the
63/// browser `wasm-bindings` batch path, which lifts its flat `(id, rgba8)`
64/// wire arrays into this richer form via [`GeometryStyleInfo::from_color`].
65#[derive(Debug, Clone)]
66pub struct GeometryStyleInfo {
67    /// Apparent colour for rendering: IfcSurfaceStyleRendering.DiffuseColour
68    /// when authored, otherwise the SurfaceColour. Matches what most IFC
69    /// viewers display.
70    pub color: [f32; 4],
71    /// SurfaceColour, populated only when the file authored a distinct
72    /// DiffuseColour. Read by the WASM bridge's parallel extractor so the
73    /// GLB exporter can offer "Shading" as a colour source; the
74    /// processing-crate `MeshData` doesn't propagate it (server pipeline
75    /// has no GLB consumer yet).
76    pub shading_color: Option<[f32; 4]>,
77    pub material_name: Option<String>,
78}
79
80impl GeometryStyleInfo {
81    /// Lift a bare RGBA colour (e.g. from the browser prepass's flat
82    /// `styleIds`/`styleColors` wire arrays) into the rich form. No shading
83    /// colour, no material name — exactly the fidelity the wire carries.
84    pub fn from_color(color: [f32; 4]) -> Self {
85        Self {
86            color,
87            shading_color: None,
88            material_name: None,
89        }
90    }
91}
92
93/// Canonical straight-alpha RGBA color, components in `0.0..=1.0`.
94///
95/// Serializes transparently as a bare `[f32; 4]` JSON array, so it is a
96/// drop-in replacement for the `[f32; 4]` colors used across the pipeline
97/// today (e.g. `MeshData.color`).
98#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
99#[serde(transparent)]
100pub struct Rgba(pub [f32; 4]);
101
102impl Rgba {
103    /// Construct from components.
104    pub const fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
105        Rgba([r, g, b, a])
106    }
107
108    /// Construct from a raw `[f32; 4]`.
109    pub const fn from_array(c: [f32; 4]) -> Self {
110        Rgba(c)
111    }
112
113    /// The underlying `[f32; 4]`.
114    pub const fn to_array(self) -> [f32; 4] {
115        self.0
116    }
117
118    /// The alpha component.
119    pub const fn alpha(self) -> f32 {
120        self.0[3]
121    }
122
123    /// `true` when alpha is below [`TRANSPARENCY_ALPHA_THRESHOLD`].
124    pub fn is_transparent(self) -> bool {
125        self.0[3] < TRANSPARENCY_ALPHA_THRESHOLD
126    }
127
128    /// Quantize to 8-bit RGBA for the browser SAB transport.
129    ///
130    /// Components are clamped to `0.0..=1.0` then rounded to nearest 1/255.
131    /// This is the *only* sanctioned quantization point (plan §8.3); the
132    /// backend never calls it.
133    pub fn to_rgba8(self) -> [u8; 4] {
134        let q = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8;
135        [q(self.0[0]), q(self.0[1]), q(self.0[2]), q(self.0[3])]
136    }
137
138    /// Reconstruct from 8-bit RGBA (the inverse of [`Rgba::to_rgba8`],
139    /// modulo the 1/255 quantization step).
140    pub fn from_rgba8(c: [u8; 4]) -> Self {
141        Rgba([
142            c[0] as f32 / 255.0,
143            c[1] as f32 / 255.0,
144            c[2] as f32 / 255.0,
145            c[3] as f32 / 255.0,
146        ])
147    }
148}
149
150impl From<[f32; 4]> for Rgba {
151    fn from(c: [f32; 4]) -> Self {
152        Rgba(c)
153    }
154}
155
156impl From<Rgba> for [f32; 4] {
157    fn from(c: Rgba) -> Self {
158        c.0
159    }
160}
161
162/// The canonical default color for an IFC type.
163///
164/// This is the **union** of the historical `wasm-bindings` and `processing`
165/// tables (plan §8.1): every type keeps the value from whichever table
166/// defined it, and `IfcFurnishingElement` resolves to the browser's lighter
167/// wood (the value users see today). Types not listed fall through to neutral
168/// gray.
169pub fn default_color_for_type(ifc_type: IfcType) -> Rgba {
170    match ifc_type {
171        // Walls — light gray
172        IfcType::IfcWall | IfcType::IfcWallStandardCase => Rgba::new(0.85, 0.85, 0.85, 1.0),
173
174        // Slabs — darker gray
175        IfcType::IfcSlab => Rgba::new(0.7, 0.7, 0.7, 1.0),
176
177        // Roofs — brown-ish
178        IfcType::IfcRoof => Rgba::new(0.6, 0.5, 0.4, 1.0),
179
180        // Columns / beams / members — steel gray
181        IfcType::IfcColumn | IfcType::IfcBeam | IfcType::IfcMember => Rgba::new(0.6, 0.65, 0.7, 1.0),
182
183        // Windows — light blue, transparent
184        IfcType::IfcWindow => Rgba::new(0.6, 0.8, 1.0, 0.4),
185
186        // Doors — wood brown
187        IfcType::IfcDoor => Rgba::new(0.6, 0.45, 0.3, 1.0),
188
189        // Stairs (incl. stair flights — from the processing table)
190        IfcType::IfcStair | IfcType::IfcStairFlight => Rgba::new(0.75, 0.75, 0.75, 1.0),
191
192        // Railings
193        IfcType::IfcRailing => Rgba::new(0.4, 0.4, 0.45, 1.0),
194
195        // Plates / coverings
196        IfcType::IfcPlate | IfcType::IfcCovering => Rgba::new(0.8, 0.8, 0.8, 1.0),
197
198        // Curtain walls — glass blue (from the wasm table)
199        IfcType::IfcCurtainWall => Rgba::new(0.5, 0.7, 0.9, 0.5),
200
201        // Furniture — light wood (from the wasm table; §8.1)
202        IfcType::IfcFurnishingElement => Rgba::new(0.7, 0.55, 0.4, 1.0),
203
204        // Spaces — cyan, transparent
205        IfcType::IfcSpace => Rgba::new(0.2, 0.85, 1.0, 0.3),
206
207        // Spatial zones (modelled GFA volumes) — violet, transparent. A
208        // distinct hue from IfcSpace's cyan so net (room) vs gross (zone)
209        // areas read apart when both are shown (#1075).
210        IfcType::IfcSpatialZone => Rgba::new(0.72, 0.35, 0.95, 0.28),
211
212        // Opening elements — red-orange, transparent
213        IfcType::IfcOpeningElement => Rgba::new(1.0, 0.42, 0.29, 0.4),
214
215        // Site — green
216        IfcType::IfcSite => Rgba::new(0.4, 0.8, 0.3, 1.0),
217
218        // Building element proxy — generic gray (from the processing table)
219        IfcType::IfcBuildingElementProxy => Rgba::new(0.6, 0.6, 0.6, 1.0),
220
221        // Default — neutral gray
222        _ => Rgba::new(0.8, 0.8, 0.8, 1.0),
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn rgba_array_round_trip() {
232        let c = Rgba::new(0.1, 0.2, 0.3, 0.4);
233        assert_eq!(c.to_array(), [0.1, 0.2, 0.3, 0.4]);
234        assert_eq!(Rgba::from_array([0.1, 0.2, 0.3, 0.4]), c);
235        let back: [f32; 4] = c.into();
236        assert_eq!(back, [0.1, 0.2, 0.3, 0.4]);
237        assert_eq!(Rgba::from([0.5, 0.6, 0.7, 0.8]).alpha(), 0.8);
238    }
239
240    #[test]
241    fn quantization_clamps_and_rounds() {
242        assert_eq!(Rgba::new(0.0, 1.0, 0.5, 1.0).to_rgba8(), [0, 255, 128, 255]);
243        // out-of-range components clamp, not wrap
244        assert_eq!(Rgba::new(-0.5, 1.5, 0.0, 2.0).to_rgba8(), [0, 255, 0, 255]);
245    }
246
247    #[test]
248    fn quantization_within_one_step() {
249        // Every 8-bit round trip stays within the documented 1/255 tolerance.
250        for raw in [0.0_f32, 0.123, 0.4, 0.42, 0.5, 0.555, 0.95, 1.0] {
251            let back = Rgba::from_rgba8(Rgba::new(raw, raw, raw, raw).to_rgba8()).to_array();
252            assert!((back[0] - raw).abs() <= 1.0 / 255.0, "drift too large for {raw}");
253        }
254    }
255
256    #[test]
257    fn transparency_threshold() {
258        assert!(Rgba::new(0.6, 0.8, 1.0, 0.4).is_transparent());
259        assert!(!Rgba::new(0.85, 0.85, 0.85, 1.0).is_transparent());
260        // exactly the threshold counts as opaque
261        assert!(!Rgba::new(0.0, 0.0, 0.0, TRANSPARENCY_ALPHA_THRESHOLD).is_transparent());
262    }
263
264    #[test]
265    fn defaults_cover_known_types() {
266        assert_eq!(
267            default_color_for_type(IfcType::IfcWall).to_array(),
268            [0.85, 0.85, 0.85, 1.0]
269        );
270        // IfcWindow is transparent by default
271        assert!(default_color_for_type(IfcType::IfcWindow).is_transparent());
272        // unmapped type → neutral gray fallback
273        assert_eq!(
274            default_color_for_type(IfcType::IfcProject).to_array(),
275            [0.8, 0.8, 0.8, 1.0]
276        );
277    }
278
279    #[test]
280    fn union_resolves_the_four_contested_types() {
281        // The four types that diverged between the historical tables (§2.2).
282        assert_eq!(
283            default_color_for_type(IfcType::IfcCurtainWall).to_array(),
284            [0.5, 0.7, 0.9, 0.5],
285            "curtain wall = wasm glass blue"
286        );
287        assert_eq!(
288            default_color_for_type(IfcType::IfcStairFlight).to_array(),
289            [0.75, 0.75, 0.75, 1.0],
290            "stair flight = processing gray (grouped with IfcStair)"
291        );
292        assert_eq!(
293            default_color_for_type(IfcType::IfcBuildingElementProxy).to_array(),
294            [0.6, 0.6, 0.6, 1.0],
295            "proxy = processing gray"
296        );
297        assert_eq!(
298            default_color_for_type(IfcType::IfcFurnishingElement).to_array(),
299            [0.7, 0.55, 0.4, 1.0],
300            "furnishing = wasm light wood, not processing's darker brown"
301        );
302        // IfcStair and IfcStairFlight must agree.
303        assert_eq!(
304            default_color_for_type(IfcType::IfcStair),
305            default_color_for_type(IfcType::IfcStairFlight)
306        );
307    }
308}