Skip to main content

ifc_style/authoring/
fill.rs

1//! Authoring fill-area patterns.
2//!
3//! Split from `external`: hatching and tiling are one concern -- how an
4//! area is filled -- and the module was over the monolith limit.
5
6use ifc_model::{EntityId, Model, Transaction, Value};
7use ifc_schema::Schema;
8
9use crate::error::StyleResult;
10
11use super::{build_named, invalid_authoring, staged_type, validate_ref};
12
13/// `IfcHatchLineDistanceSelect`: the spacing between hatch lines.
14#[derive(Debug, Clone, Copy)]
15pub enum HatchLineDistance {
16    /// An `IfcPositiveLengthMeasure`: constant perpendicular spacing.
17    Length(f64),
18    /// A skewed pattern: in IFC4 and later an `IfcVector`; in IFC2X3 an
19    /// `IfcOneDirectionRepeatFactor`.
20    Vector(EntityId),
21}
22
23/// Stage an `IfcFillAreaStyleHatching`.
24///
25/// One family of parallel hatch lines. `HatchLineAngle` is in the
26/// project's plane angle unit (`IfcPlaneAngleMeasure`);
27/// `StyleIndex::material_fill` converts it with `StyleUnits`.
28///
29/// # Errors
30///
31/// Refuses a non-positive or non-finite line distance, a non-finite
32/// angle, and a reference of the wrong type -- including a point that
33/// is not 2D, which `PatternStart2D` and `RefHatchLine2D` require.
34pub fn create_fill_area_style_hatching(
35    tx: &mut Transaction,
36    model: &Model,
37    schema: &Schema,
38    appearance: EntityId,
39    distance: HatchLineDistance,
40    reference: (Option<EntityId>, Option<EntityId>),
41    angle: f64,
42) -> StyleResult<EntityId> {
43    const ENTITY: &str = "IfcFillAreaStyleHatching";
44    let (point_of_reference, pattern_start) = reference;
45    validate_ref(tx, model, schema, appearance, "IfcCurveStyle")?;
46    if !angle.is_finite() {
47        return Err(invalid_authoring(ENTITY, "HatchLineAngle", "not finite"));
48    }
49    let start = match distance {
50        HatchLineDistance::Length(value) => {
51            if !value.is_finite() || value <= 0.0 {
52                return Err(invalid_authoring(
53                    ENTITY,
54                    "StartOfNextHatchLine",
55                    format!("expected a positive length, got {value}"),
56                ));
57            }
58            Value::Typed {
59                type_name: "IFCPOSITIVELENGTHMEASURE".into(),
60                value: Box::new(Value::Real(value)),
61            }
62        }
63        HatchLineDistance::Vector(id) => {
64            if schema.entity("IfcOneDirectionRepeatFactor").is_some() {
65                validate_ref(tx, model, schema, id, "IfcOneDirectionRepeatFactor")?;
66                if schema.is_a(staged_type(tx, model, id)?, "IfcTwoDirectionRepeatFactor") {
67                    return Err(invalid_authoring(
68                        ENTITY,
69                        "StartOfNextHatchLine",
70                        "WR21: a two-direction repeat factor",
71                    ));
72                }
73            } else {
74                validate_ref(tx, model, schema, id, "IfcVector")?;
75            }
76            Value::Ref(id)
77        }
78    };
79    for point in [point_of_reference, pattern_start].into_iter().flatten() {
80        validate_ref(tx, model, schema, point, "IfcCartesianPoint")?;
81    }
82    let mut values = vec![
83        ("HatchLineAppearance", Value::Ref(appearance)),
84        ("StartOfNextHatchLine", start),
85    ];
86    if let Some(point) = point_of_reference {
87        values.push(("PointOfReferenceHatchLine", Value::Ref(point)));
88    }
89    if let Some(point) = pattern_start {
90        values.push(("PatternStart", Value::Ref(point)));
91    }
92    values.push(("HatchLineAngle", Value::Real(angle)));
93    Ok(tx.create(build_named(schema, ENTITY, values)?))
94}
95
96/// Stage an `IfcFillAreaStyleTiles`.
97///
98/// A repeating tiled fill. `TilingPattern` is `LIST [2:2] OF IfcVector`
99/// -- exactly two, because two vectors define the lattice the tile
100/// repeats on; one would leave the repetition direction undetermined.
101///
102/// # Errors
103///
104/// Refuses a tiling pattern that is not exactly two vectors, an empty
105/// tile set (`SET [1:?]`), a non-positive tiling scale, and a
106/// reference of the wrong type.
107pub fn create_fill_area_style_tiles(
108    tx: &mut Transaction,
109    model: &Model,
110    schema: &Schema,
111    tiling_pattern: &[EntityId],
112    tiles: &[EntityId],
113    tiling_scale: f64,
114) -> StyleResult<EntityId> {
115    const ENTITY: &str = "IfcFillAreaStyleTiles";
116    if tiling_pattern.len() != 2 {
117        return Err(invalid_authoring(
118            ENTITY,
119            "TilingPattern",
120            format!("expected exactly two vectors, got {}", tiling_pattern.len()),
121        ));
122    }
123    if tiles.is_empty() {
124        return Err(invalid_authoring(ENTITY, "Tiles", "empty"));
125    }
126    if !tiling_scale.is_finite() || tiling_scale <= 0.0 {
127        return Err(invalid_authoring(
128            ENTITY,
129            "TilingScale",
130            format!("expected a positive ratio, got {tiling_scale}"),
131        ));
132    }
133    for vector in tiling_pattern {
134        validate_ref(tx, model, schema, *vector, "IfcVector")?;
135    }
136    for tile in tiles {
137        validate_ref(tx, model, schema, *tile, "IfcStyledItem")?;
138    }
139    let values = vec![
140        (
141            "TilingPattern",
142            Value::List(tiling_pattern.iter().copied().map(Value::Ref).collect()),
143        ),
144        (
145            "Tiles",
146            Value::List(tiles.iter().copied().map(Value::Ref).collect()),
147        ),
148        ("TilingScale", Value::Real(tiling_scale)),
149    ];
150    Ok(tx.create(build_named(schema, ENTITY, values)?))
151}