ifc_style/assignment/fill.rs
1//! The cut fill of a material (#597), per context and per view (#624); see
2//! [`StyleIndex::material_fill`].
3
4use std::cmp::Ordering;
5
6use ifc_model::EntityId;
7
8use crate::error::{StyleError, StyleResult};
9use crate::fill_style::{resolve_fill, ContextFill, ContextFillResult, HatchLine, MaterialFill};
10use crate::units::StyleUnits;
11
12use super::StyleIndex;
13
14impl StyleIndex<'_, '_> {
15 /// The cut fill `material`'s `IfcMaterialDefinitionRepresentation` states,
16 /// over every one of its `IfcStyledRepresentation`s (one per
17 /// representation context), as hatch line families in metres and
18 /// radians (see [`MaterialFill`]). `None` when the material has no
19 /// representation or none states an `IfcFillAreaStyle`.
20 ///
21 /// The traversal is that of [`StyleIndex::material_colour`]. Fills in
22 /// different contexts must draw the same: equal flag, background and
23 /// hatch lines (as a set, compared exactly); the first one, in
24 /// ascending order of representation and item, is returned.
25 /// A material that states different fills per context (cut and
26 /// projection) is ambiguous here: see [`StyleIndex::material_fills`] and
27 /// [`StyleIndex::material_fill_for_view`].
28 ///
29 /// # Errors
30 ///
31 /// [`StyleError::AmbiguousFill`] when one styled item, or the material
32 /// across its styled items, states fills that differ;
33 /// [`StyleError::UnsupportedFill`] for tiles, an externally defined
34 /// hatch style, a predefined curve font other than 'continuous' and a
35 /// 'by layer' colour or width; [`StyleError::UnitUndeclared`] when a
36 /// measure needs a unit `units` does not state (a colour-only fill needs
37 /// none); [`StyleError::InvalidValue`] and [`StyleError::OutOfRange`]
38 /// for a fill that breaks a rule of the standard (`MaxOneColour`, a
39 /// non-positive distance, a vector along the hatch lines, ...);
40 /// [`StyleError::UnknownEntity`] for a dangling style;
41 /// [`StyleError::ReferenceType`] for a representation that is no
42 /// `IfcStyledRepresentation` or an item that is no `IfcStyledItem`; and
43 /// the projection errors of a malformed style.
44 pub fn material_fill(
45 &self,
46 material: EntityId,
47 units: StyleUnits,
48 ) -> StyleResult<Option<MaterialFill>> {
49 let mut found = Vec::new();
50 for representation in self.representations_of(material)? {
51 found.extend(self.representation_fills(representation, units)?);
52 }
53 agree_fill(material, found)
54 }
55
56 /// The fills `material` states per representation context, one
57 /// [`ContextFill`] for each context that carries a fill area style, in
58 /// ascending order of the lowest `IfcStyledRepresentation` in it.
59 ///
60 /// This is how one material gives several fills, e.g. a cut fill in a
61 /// `SECTION_VIEW` sub-context and a projection fill in an
62 /// `ELEVATION_VIEW` one. [`StyleIndex::material_fill`] over the same
63 /// material refuses that as [`StyleError::AmbiguousFill`]: use this
64 /// method for per-view fills, or [`StyleIndex::material_fill_for_view`]
65 /// for one view.
66 ///
67 /// One refused context fails the whole call;
68 /// [`StyleIndex::material_fills_by_context`] keeps refusals apart.
69 ///
70 /// Fills agree as in `material_fill`, but only within a context: the
71 /// styled items of one representation must agree, then the
72 /// representations of one context. Of agreeing representations the
73 /// lowest is reported.
74 ///
75 /// # Errors
76 ///
77 /// [`StyleError::AmbiguousFill`] with the representation as owner when
78 /// its styled items differ, and with the context as owner when two
79 /// representations in it differ; every other error of
80 /// [`StyleIndex::material_fill`]; and the projection errors of a missing
81 /// or malformed representation context.
82 pub fn material_fills(
83 &self,
84 material: EntityId,
85 units: StyleUnits,
86 ) -> StyleResult<Vec<ContextFill>> {
87 // (context, its representations' fills), in order of first sight.
88 let mut contexts: Vec<(EntityId, Vec<(EntityId, MaterialFill)>)> = Vec::new();
89 for representation in self.representations_of(material)? {
90 let Some(fill) = agree_fill(
91 representation,
92 self.representation_fills(representation, units)?,
93 )?
94 else {
95 continue;
96 };
97 let context = self.context_of(representation)?;
98 match contexts.iter_mut().find(|(id, _)| *id == context) {
99 Some((_, found)) => found.push((representation, fill)),
100 None => contexts.push((context, vec![(representation, fill)])),
101 }
102 }
103 let mut out = Vec::new();
104 for (context, found) in contexts {
105 let representation = found[0].0;
106 let fills = found.into_iter().map(|(_, fill)| fill).collect();
107 let Some(fill) = agree_fill(context, fills)? else {
108 continue;
109 };
110 let described = self.describe_context(context)?;
111 out.push(ContextFill {
112 representation,
113 context,
114 identifier: described.identifier,
115 context_type: described.context_type,
116 target_view: described.target_view,
117 user_defined_target_view: described.user_defined_target_view,
118 parent_context: described.parent_context,
119 fill,
120 });
121 }
122 Ok(out)
123 }
124
125 /// What `material` states per representation context, like
126 /// [`StyleIndex::material_fills`], but a refusal that belongs to one
127 /// context stays in that context's entry: one [`ContextFillResult`] for
128 /// each context that carries a fill area style or was refused, in order
129 /// of the lowest `IfcStyledRepresentation` in it that states a fill or
130 /// was refused.
131 ///
132 /// Within a context the first refusal, in ascending order of
133 /// representation, is the entry's; a later representation cannot
134 /// replace it. Fills agree as in `material_fills`.
135 ///
136 /// When `material_fills` returns `Ok`, this returns the same contexts
137 /// in the same order, each `Ok` with equal fields. When it returns an
138 /// error, this returns an error, or at least one refused entry.
139 ///
140 /// # Errors
141 ///
142 /// Only refusals no context owns fail the call: the definitions and
143 /// their `Representations` (a member that is no `IfcStyledRepresentation`
144 /// included), the `ContextOfItems` of a representation that states a fill
145 /// or was refused, and the record of a context that has an entry
146 /// (`ContextIdentifier`, `ContextType`, a missing or invalid `TargetView`,
147 /// `UserDefinedTargetView`, `ParentContext`). Everything else lands in
148 /// [`ContextFillResult::fill`]: the errors of a representation's items
149 /// and styles, [`StyleError::AmbiguousFill`] owned by a styled item, a
150 /// representation, or a context whose representations differ.
151 pub fn material_fills_by_context(
152 &self,
153 material: EntityId,
154 units: StyleUnits,
155 ) -> StyleResult<Vec<ContextFillResult>> {
156 struct Pending {
157 context: EntityId,
158 representation: EntityId,
159 state: StyleResult<Vec<MaterialFill>>,
160 }
161 let mut contexts: Vec<Pending> = Vec::new();
162 for representation in self.representations_of(material)? {
163 let resolved = self
164 .representation_fills(representation, units)
165 .and_then(|fills| agree_fill(representation, fills));
166 if matches!(resolved, Ok(None)) {
167 continue;
168 }
169 let context = self.context_of(representation)?;
170 let index = match contexts.iter().position(|p| p.context == context) {
171 Some(index) => index,
172 None => {
173 contexts.push(Pending {
174 context,
175 representation,
176 state: Ok(Vec::new()),
177 });
178 contexts.len() - 1
179 }
180 };
181 let pending = &mut contexts[index];
182 match resolved {
183 Ok(Some(fill)) => {
184 if let Ok(fills) = &mut pending.state {
185 fills.push(fill);
186 }
187 }
188 Ok(None) => {}
189 Err(error) => {
190 if pending.state.is_ok() {
191 pending.state = Err(error);
192 }
193 }
194 }
195 }
196 let mut out = Vec::new();
197 for Pending {
198 context,
199 representation,
200 state,
201 } in contexts
202 {
203 let Some(fill) = state
204 .and_then(|fills| agree_fill(context, fills))
205 .transpose()
206 else {
207 continue;
208 };
209 let described = self.describe_context(context)?;
210 out.push(ContextFillResult {
211 representation,
212 context,
213 identifier: described.identifier,
214 context_type: described.context_type,
215 target_view: described.target_view,
216 user_defined_target_view: described.user_defined_target_view,
217 parent_context: described.parent_context,
218 fill,
219 });
220 }
221 Ok(out)
222 }
223
224 /// The fill `material` states in the representation contexts whose
225 /// `TargetView` is `target_view` (`"SECTION_VIEW"`, without dots): the
226 /// fill they agree on, `None` when no such context carries one.
227 ///
228 /// A plain `IfcGeometricRepresentationContext` matches no view, not even
229 /// `MODEL_VIEW`; `USERDEFINED` matches every user-defined sub-context
230 /// without comparing `UserDefinedTargetView`. Fills agree as in
231 /// [`StyleIndex::material_fill`], so contexts that differ give
232 /// [`StyleError::AmbiguousFill`] owned by the material.
233 ///
234 /// # Errors
235 ///
236 /// [`StyleError::UnknownTargetView`] (before anything is read) when
237 /// `target_view` is no `IfcGeometricProjectionEnum` literal: the match is
238 /// exact and case-sensitive. The refusal of the first matching context
239 /// that was refused, and the whole-call errors of
240 /// [`StyleIndex::material_fills_by_context`]. A refusal in a context of
241 /// another view does not matter here.
242 pub fn material_fill_for_view(
243 &self,
244 material: EntityId,
245 target_view: &str,
246 units: StyleUnits,
247 ) -> StyleResult<Option<MaterialFill>> {
248 if !PROJECTIONS.contains(&target_view) {
249 return Err(StyleError::UnknownTargetView {
250 value: target_view.to_owned(),
251 });
252 }
253 let mut fills = Vec::new();
254 for entry in self.material_fills_by_context(material, units)? {
255 if entry.target_view.as_deref() == Some(target_view) {
256 fills.push(entry.fill?);
257 }
258 }
259 agree_fill(material, fills)
260 }
261
262 /// The fill a bare `IfcFillAreaStyle` states, as [`StyleIndex::material_fill`]
263 /// resolves it, for a style nothing may reference (a pattern library).
264 /// [`MaterialFill::styled_item`] is `None`.
265 ///
266 /// # Errors
267 ///
268 /// [`StyleError::UnknownEntity`] for a missing entity;
269 /// [`StyleError::WrongEntityType`] when `style` is no `IfcFillAreaStyle`;
270 /// and the errors of [`StyleIndex::material_fill`] for the style itself.
271 pub fn fill_area_style(&self, style: EntityId, units: StyleUnits) -> StyleResult<MaterialFill> {
272 let view = self.view();
273 resolve_fill(view, style, None, units)
274 }
275
276 /// The `IfcStyledRepresentation`s of `material`, ascending.
277 fn representations_of(&self, material: EntityId) -> StyleResult<Vec<EntityId>> {
278 let view = self.view();
279 let mut found = Vec::new();
280 for definition in self.definitions_of(material)? {
281 found.extend(
282 view.record(definition, "IfcMaterialDefinitionRepresentation")?
283 .required_refs("Representations", "IfcStyledRepresentation", 1, None)?,
284 );
285 }
286 found.sort_unstable();
287 found.dedup();
288 Ok(found)
289 }
290
291 /// The `ContextOfItems` of `representation`.
292 fn context_of(&self, representation: EntityId) -> StyleResult<EntityId> {
293 self.view()
294 .record(representation, "IfcStyledRepresentation")?
295 .required_ref("ContextOfItems", "IfcRepresentationContext")
296 }
297
298 /// The identifying attributes of `context`, and for a sub-context its
299 /// projection and parent.
300 fn describe_context(&self, context: EntityId) -> StyleResult<Described> {
301 let view = self.view();
302 let record = view.record(context, "IfcRepresentationContext")?;
303 let sub = view
304 .schema
305 .is_a(record.type_name(), "IfcGeometricRepresentationSubContext");
306 let (target_view, user_defined_target_view, parent_context) = if sub {
307 let target = record.required_enum("TargetView")?.trim_matches('.');
308 if !PROJECTIONS.contains(&target) {
309 return Err(StyleError::InvalidValue {
310 entity: record.type_name().to_owned(),
311 id: context,
312 attribute: "TargetView",
313 value: target.to_owned(),
314 });
315 }
316 (
317 Some(target.to_owned()),
318 record
319 .optional_text("UserDefinedTargetView")?
320 .map(str::to_owned),
321 Some(record.required_ref("ParentContext", "IfcGeometricRepresentationContext")?),
322 )
323 } else {
324 (None, None, None)
325 };
326 Ok(Described {
327 identifier: record
328 .optional_text("ContextIdentifier")?
329 .map(str::to_owned),
330 context_type: record.optional_text("ContextType")?.map(str::to_owned),
331 target_view,
332 user_defined_target_view,
333 parent_context,
334 })
335 }
336
337 /// The fill of each styled item of `representation` that states one,
338 /// in ascending item order.
339 fn representation_fills(
340 &self,
341 representation: EntityId,
342 units: StyleUnits,
343 ) -> StyleResult<Vec<MaterialFill>> {
344 let view = self.view();
345 let mut items = view
346 .record(representation, "IfcStyledRepresentation")?
347 .required_refs("Items", "IfcStyledItem", 1, None)?;
348 items.sort_unstable();
349 items.dedup();
350 let mut found = Vec::new();
351 for styled in items {
352 let styles = view.flatten_assignments(view.styled_item(styled)?.styles()?)?;
353 let mut fills = Vec::new();
354 for style in styles {
355 let entity = view
356 .model
357 .get(style)
358 .ok_or(StyleError::UnknownEntity { id: style })?;
359 if view.schema.is_a(&entity.type_name, "IfcFillAreaStyle") {
360 fills.push(resolve_fill(view, style, Some(styled), units)?);
361 }
362 }
363 if let Some(fill) = agree_fill(styled, fills)? {
364 found.push(fill);
365 }
366 }
367 Ok(found)
368 }
369}
370
371/// `IfcGeometricProjectionEnum`, the same in every release.
372const PROJECTIONS: [&str; 9] = [
373 "GRAPH_VIEW",
374 "SKETCH_VIEW",
375 "MODEL_VIEW",
376 "PLAN_VIEW",
377 "REFLECTED_PLAN_VIEW",
378 "SECTION_VIEW",
379 "ELEVATION_VIEW",
380 "USERDEFINED",
381 "NOTDEFINED",
382];
383
384/// The attributes of a representation context a [`ContextFill`] reports.
385struct Described {
386 identifier: Option<String>,
387 context_type: Option<String>,
388 target_view: Option<String>,
389 user_defined_target_view: Option<String>,
390 parent_context: Option<EntityId>,
391}
392
393/// The first of `found` when every fill agrees, `None` when empty, else
394/// ambiguous.
395fn agree_fill(owner: EntityId, found: Vec<MaterialFill>) -> StyleResult<Option<MaterialFill>> {
396 let Some(first) = found.first() else {
397 return Ok(None);
398 };
399 if found.iter().all(|fill| same_fill(first, fill)) {
400 return Ok(found.into_iter().next());
401 }
402 let mut styles: Vec<EntityId> = found.iter().map(|fill| fill.style).collect();
403 styles.sort_unstable();
404 styles.dedup();
405 Err(StyleError::AmbiguousFill { owner, styles })
406}
407
408/// Whether two fills draw the same: flag, background and the hatch lines as
409/// a multiset. Names and ids do not draw.
410fn same_fill(a: &MaterialFill, b: &MaterialFill) -> bool {
411 a.model_or_draughting == b.model_or_draughting
412 && a.background == b.background
413 && sorted(&a.lines) == sorted(&b.lines)
414}
415
416/// The lines in a total order, with `-0.0` read as `0.0` so that equal
417/// values never sort apart.
418fn sorted(lines: &[HatchLine]) -> Vec<HatchLine> {
419 let mut lines: Vec<HatchLine> = lines.iter().map(normalised).collect();
420 lines.sort_by(compare);
421 lines
422}
423
424fn normalised(line: &HatchLine) -> HatchLine {
425 let mut line = line.clone();
426 line.angle_rad += 0.0;
427 line.spacing += 0.0;
428 line.shift += 0.0;
429 line.origin = line.origin.map(|x| x + 0.0);
430 line.pattern_start = line.pattern_start.map(|p| p.map(|x| x + 0.0));
431 line.dashes = line
432 .dashes
433 .map(|pairs| pairs.into_iter().map(|p| p.map(|x| x + 0.0)).collect());
434 line.colour = line.colour.map(|c| c.map(|x| x + 0.0));
435 line.width = line.width.map(|x| x + 0.0);
436 line
437}
438
439fn compare(a: &HatchLine, b: &HatchLine) -> Ordering {
440 let dashes = |line: &HatchLine| -> Option<Vec<f64>> {
441 line.dashes
442 .as_ref()
443 .map(|pairs| pairs.iter().flatten().copied().collect())
444 };
445 a.angle_rad
446 .total_cmp(&b.angle_rad)
447 .then(a.spacing.total_cmp(&b.spacing))
448 .then(a.shift.total_cmp(&b.shift))
449 .then_with(|| slices(&a.origin, &b.origin))
450 .then_with(|| options(a.pattern_start, b.pattern_start, |x, y| slices(&x, &y)))
451 .then_with(|| options(dashes(a), dashes(b), |x, y| slices(&x, &y)))
452 .then_with(|| options(a.colour, b.colour, |x, y| slices(&x, &y)))
453 .then_with(|| options(a.width, b.width, |x, y| x.total_cmp(&y)))
454}
455
456fn slices(a: &[f64], b: &[f64]) -> Ordering {
457 a.iter()
458 .zip(b)
459 .map(|(x, y)| x.total_cmp(y))
460 .find(|order| order.is_ne())
461 .unwrap_or_else(|| a.len().cmp(&b.len()))
462}
463
464/// `None` before `Some`.
465fn options<T>(a: Option<T>, b: Option<T>, compare: impl Fn(T, T) -> Ordering) -> Ordering {
466 match (a, b) {
467 (None, None) => Ordering::Equal,
468 (None, Some(_)) => Ordering::Less,
469 (Some(_), None) => Ordering::Greater,
470 (Some(a), Some(b)) => compare(a, b),
471 }
472}