ifc-style 0.4.0

Presentation: styles, colours, textures, layers, annotation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
//! Authoring colours, surface styles, and presentation layers.
//!
//! Split from the module root: these writers form one concern --
//! how a surface looks -- and the root was over the monolith limit.

use ifc_model::{Edit, EntityId, Model, Transaction, Value};
use ifc_schema::Schema;

use super::{
    build_named, enumeration, invalid_authoring, optional_reference, optional_text, text,
    validate_optional_ref, validate_ratio, validate_ref,
};
use crate::colour::ColourOrFactor;
use crate::error::{StyleError, StyleResult};
use crate::surface_style::{duplicate_surface_element_category, SURFACE_STYLE_ELEMENT_MEMBERS};

/// Draft input for [`create_colour_rgb`]: the writable attributes of a new
/// `IfcColourRgb`.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct ColourRgbDraft<'a> {
    /// The `Name` attribute, when supplied.
    pub name: Option<&'a str>,
    /// The `Red` channel; must be a finite value in `[0, 1]`.
    pub red: f64,
    /// The `Green` channel; must be a finite value in `[0, 1]`.
    pub green: f64,
    /// The `Blue` channel; must be a finite value in `[0, 1]`.
    pub blue: f64,
}

impl<'a> ColourRgbDraft<'a> {
    /// Starts a draft from its required `red`, `green`, `blue`; every other
    /// field is unset.
    #[must_use]
    pub fn new(red: f64, green: f64, blue: f64) -> Self {
        Self {
            name: None,
            red,
            green,
            blue,
        }
    }

    /// Sets `name`.
    ///
    /// The `Name` attribute, when supplied.
    #[must_use]
    pub fn name(mut self, value: &'a str) -> Self {
        self.name = Some(value);
        self
    }
}

/// Draft input for [`create_surface_style_shading`]: the writable attributes
/// of a new `IfcSurfaceStyleShading`.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct SurfaceStyleShadingDraft {
    /// The `SurfaceColour` reference to an `IfcColourRgb`.
    pub surface_colour: EntityId,
    /// The `Transparency` factor, when supplied; must be a finite value in
    /// `[0, 1]`.
    pub transparency: Option<f64>,
}

impl SurfaceStyleShadingDraft {
    /// Starts a draft from its required `surface_colour`; every other field is
    /// unset.
    #[must_use]
    pub fn new(surface_colour: EntityId) -> Self {
        Self {
            surface_colour,
            transparency: None,
        }
    }

    /// Sets `transparency`.
    ///
    /// The `Transparency` factor, when supplied; must be a finite value in
    /// `[0, 1]`.
    #[must_use]
    pub fn transparency(mut self, value: f64) -> Self {
        self.transparency = Some(value);
        self
    }
}

/// Draft input for [`create_surface_style`]: the writable attributes of a
/// new `IfcSurfaceStyle`.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SurfaceStyleDraft<'a> {
    /// The `Name` attribute, when supplied.
    pub name: Option<&'a str>,
    /// The `Side` attribute.
    pub side: crate::SurfaceSide,
    /// The `Styles` elements: one to five references, no two from the same
    /// surface-style element category (shading, lighting, refraction,
    /// textures, externally defined).
    pub elements: Vec<EntityId>,
}

impl<'a> SurfaceStyleDraft<'a> {
    /// Starts a draft from its required `side`, `elements`; every other field
    /// is unset.
    #[must_use]
    pub fn new(side: crate::SurfaceSide, elements: Vec<EntityId>) -> Self {
        Self {
            name: None,
            side,
            elements,
        }
    }

    /// Sets `name`.
    ///
    /// The `Name` attribute, when supplied.
    #[must_use]
    pub fn name(mut self, value: &'a str) -> Self {
        self.name = Some(value);
        self
    }
}

/// Draft input for [`create_styled_item`]: the writable attributes of a new
/// `IfcStyledItem`.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct StyledItemDraft<'a> {
    /// The `Item` reference to an `IfcRepresentationItem`, when supplied.
    pub item: Option<EntityId>,
    /// The `Styles` references; at least one is required. On IFC2x3 these
    /// are wrapped in a staged `IfcPresentationStyleAssignment`.
    pub styles: Vec<EntityId>,
    /// The `Name` attribute, when supplied.
    pub name: Option<&'a str>,
}

impl<'a> StyledItemDraft<'a> {
    /// Starts a draft from its required `styles`; every other field is unset.
    #[must_use]
    pub fn new(styles: Vec<EntityId>) -> Self {
        Self {
            item: None,
            styles,
            name: None,
        }
    }

    /// Sets `item`.
    ///
    /// The `Item` reference to an `IfcRepresentationItem`, when supplied.
    #[must_use]
    pub fn item(mut self, value: EntityId) -> Self {
        self.item = Some(value);
        self
    }

    /// Sets `name`.
    ///
    /// The `Name` attribute, when supplied.
    #[must_use]
    pub fn name(mut self, value: &'a str) -> Self {
        self.name = Some(value);
        self
    }
}

/// Draft input for [`create_presentation_layer_with_style`]: the writable
/// attributes of a new `IfcPresentationLayerWithStyle`.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PresentationLayerDraft<'a> {
    /// The `Name` attribute; must be non-empty.
    pub name: &'a str,
    /// The `Description` attribute, when supplied.
    pub description: Option<&'a str>,
    /// The `AssignedItems` references; at least one is required, and each
    /// must resolve to an `IfcRepresentation` or `IfcRepresentationItem`.
    pub assigned_items: Vec<EntityId>,
    /// The `Identifier` attribute, when supplied.
    pub identifier: Option<&'a str>,
    /// The `LayerOn` attribute, when supplied.
    pub layer_on: Option<bool>,
    /// The `LayerFrozen` attribute, when supplied.
    pub layer_frozen: Option<bool>,
    /// The `LayerBlocked` attribute, when supplied.
    pub layer_blocked: Option<bool>,
    /// The `LayerStyles` references.
    pub layer_styles: Vec<EntityId>,
}

impl<'a> PresentationLayerDraft<'a> {
    /// Starts a draft from its required `name`, `assigned_items`; every other
    /// field is unset.
    #[must_use]
    pub fn new(name: &'a str, assigned_items: Vec<EntityId>) -> Self {
        Self {
            name,
            description: None,
            assigned_items,
            identifier: None,
            layer_on: None,
            layer_frozen: None,
            layer_blocked: None,
            layer_styles: Vec::new(),
        }
    }

    /// Sets `description`.
    ///
    /// The `Description` attribute, when supplied.
    #[must_use]
    pub fn description(mut self, value: &'a str) -> Self {
        self.description = Some(value);
        self
    }

    /// Sets `identifier`.
    ///
    /// The `Identifier` attribute, when supplied.
    #[must_use]
    pub fn identifier(mut self, value: &'a str) -> Self {
        self.identifier = Some(value);
        self
    }

    /// Sets `layer_on`.
    ///
    /// The `LayerOn` attribute, when supplied.
    #[must_use]
    pub fn layer_on(mut self, value: bool) -> Self {
        self.layer_on = Some(value);
        self
    }

    /// Sets `layer_frozen`.
    ///
    /// The `LayerFrozen` attribute, when supplied.
    #[must_use]
    pub fn layer_frozen(mut self, value: bool) -> Self {
        self.layer_frozen = Some(value);
        self
    }

    /// Sets `layer_blocked`.
    ///
    /// The `LayerBlocked` attribute, when supplied.
    #[must_use]
    pub fn layer_blocked(mut self, value: bool) -> Self {
        self.layer_blocked = Some(value);
        self
    }

    /// Sets `layer_styles`.
    ///
    /// The `LayerStyles` references.
    #[must_use]
    pub fn layer_styles(mut self, value: Vec<EntityId>) -> Self {
        self.layer_styles = value;
        self
    }
}

/// Stage a new `IfcColourRgb` in `tx`. Fails if any channel is not a finite
/// value in `[0, 1]`.
pub fn create_colour_rgb(
    tx: &mut Transaction,
    schema: &Schema,
    draft: ColourRgbDraft<'_>,
) -> StyleResult<EntityId> {
    validate_ratio("IfcColourRgb", "Red", draft.red)?;
    validate_ratio("IfcColourRgb", "Green", draft.green)?;
    validate_ratio("IfcColourRgb", "Blue", draft.blue)?;
    let mut values = Vec::new();
    optional_text(&mut values, "Name", draft.name);
    values.extend([
        ("Red", Value::Real(draft.red)),
        ("Green", Value::Real(draft.green)),
        ("Blue", Value::Real(draft.blue)),
    ]);
    Ok(tx.create(build_named(schema, "IfcColourRgb", values)?))
}

/// Stage a new `IfcSurfaceStyleShading` in `tx`. Fails if `surface_colour`
/// does not resolve to an `IfcColourRgb`, or `transparency` is not a finite
/// value in `[0, 1]`.
pub fn create_surface_style_shading(
    tx: &mut Transaction,
    model: &Model,
    schema: &Schema,
    draft: SurfaceStyleShadingDraft,
) -> StyleResult<EntityId> {
    validate_ref(tx, model, schema, draft.surface_colour, "IfcColourRgb")?;
    if let Some(value) = draft.transparency {
        validate_ratio("IfcSurfaceStyleShading", "Transparency", value)?;
    }
    let mut values = vec![("SurfaceColour", Value::Ref(draft.surface_colour))];
    if let Some(value) = draft.transparency {
        values.push(("Transparency", Value::Real(value)));
    }
    Ok(tx.create(build_named(schema, "IfcSurfaceStyleShading", values)?))
}

/// Stage a new `IfcSurfaceStyle` in `tx`. Fails if `elements` is empty,
/// exceeds five members, contains two members from the same surface-style
/// element category, or any member does not resolve to its expected type.
pub fn create_surface_style(
    tx: &mut Transaction,
    model: &Model,
    schema: &Schema,
    draft: SurfaceStyleDraft<'_>,
) -> StyleResult<EntityId> {
    if draft.elements.is_empty() || draft.elements.len() > 5 {
        return Err(invalid_authoring(
            "IfcSurfaceStyle",
            "Styles",
            format!("expected 1..=5 elements, found {}", draft.elements.len()),
        ));
    }
    let mut element_types = Vec::with_capacity(draft.elements.len());
    for element in &draft.elements {
        element_types.push(validate_surface_element(tx, model, schema, *element)?);
    }
    if let Some(category) =
        duplicate_surface_element_category(schema, element_types.iter().map(String::as_str))
    {
        return Err(invalid_authoring(
            "IfcSurfaceStyle",
            "Styles",
            format!("duplicate {category} category"),
        ));
    }
    let mut values = Vec::new();
    optional_text(&mut values, "Name", draft.name);
    values.push(("Side", enumeration(draft.side.as_ifc())));
    values.push((
        "Styles",
        Value::List(draft.elements.into_iter().map(Value::Ref).collect()),
    ));
    Ok(tx.create(build_named(schema, "IfcSurfaceStyle", values)?))
}

/// Stage a new `IfcStyledItem` in `tx`. Fails if `styles` is empty, `item`
/// does not resolve to an `IfcRepresentationItem`, or a style does not
/// resolve to its expected type for the target schema version.
pub fn create_styled_item(
    tx: &mut Transaction,
    model: &Model,
    schema: &Schema,
    draft: StyledItemDraft<'_>,
) -> StyleResult<EntityId> {
    validate_optional_ref(tx, model, schema, draft.item, "IfcRepresentationItem")?;
    if draft.styles.is_empty() {
        return Err(invalid_authoring(
            "IfcStyledItem",
            "Styles",
            "at least one style is required",
        ));
    }
    for style in &draft.styles {
        validate_ref(tx, model, schema, *style, "IfcPresentationStyle")?;
    }

    let mut staged = tx.clone();
    let style_values = if schema.version() == Some(ifc_schema::SchemaVersion::Ifc2x3) {
        let wrapper = build_named(
            schema,
            "IfcPresentationStyleAssignment",
            vec![(
                "Styles",
                Value::List(draft.styles.into_iter().map(Value::Ref).collect()),
            )],
        )?;
        vec![Value::Ref(staged.create(wrapper))]
    } else {
        draft.styles.into_iter().map(Value::Ref).collect()
    };
    let mut values = vec![("Styles", Value::List(style_values))];
    optional_reference(&mut values, "Item", draft.item);
    optional_text(&mut values, "Name", draft.name);
    let id = staged.create(build_named(schema, "IfcStyledItem", values)?);
    *tx = staged;
    Ok(id)
}

/// Stage a new `IfcPresentationLayerWithStyle` in `tx`. Fails if `name` is
/// empty, `assigned_items` is empty, or any assigned item or layer style
/// does not resolve to its expected type.
pub fn create_presentation_layer_with_style(
    tx: &mut Transaction,
    model: &Model,
    schema: &Schema,
    draft: PresentationLayerDraft<'_>,
) -> StyleResult<EntityId> {
    if draft.name.is_empty() {
        return Err(invalid_authoring(
            "IfcPresentationLayerWithStyle",
            "Name",
            "must not be empty",
        ));
    }
    if draft.assigned_items.is_empty() {
        return Err(invalid_authoring(
            "IfcPresentationLayerWithStyle",
            "AssignedItems",
            "at least one item is required",
        ));
    }
    for item in &draft.assigned_items {
        validate_layered_item(tx, model, schema, *item)?;
    }
    for style in &draft.layer_styles {
        validate_ref(tx, model, schema, *style, "IfcPresentationStyle")?;
    }
    let mut values = vec![
        ("Name", text(draft.name)),
        (
            "AssignedItems",
            Value::List(draft.assigned_items.into_iter().map(Value::Ref).collect()),
        ),
        (
            "LayerStyles",
            Value::List(draft.layer_styles.into_iter().map(Value::Ref).collect()),
        ),
    ];
    optional_text(&mut values, "Description", draft.description);
    optional_text(&mut values, "Identifier", draft.identifier);
    if let Some(value) = draft.layer_on {
        values.push(("LayerOn", Value::Bool(value)));
    }
    if let Some(value) = draft.layer_frozen {
        values.push(("LayerFrozen", Value::Bool(value)));
    }
    if let Some(value) = draft.layer_blocked {
        values.push(("LayerBlocked", Value::Bool(value)));
    }
    Ok(tx.create(build_named(
        schema,
        "IfcPresentationLayerWithStyle",
        values,
    )?))
}

fn staged_type(tx: &Transaction, model: &Model, target: EntityId) -> Option<String> {
    tx.edits()
        .iter()
        .rev()
        .find_map(|edit| match edit {
            Edit::Create { id, entity } if *id == target => Some(entity.type_name.to_string()),
            _ => None,
        })
        .or_else(|| model.get(target).map(|entity| entity.type_name.to_string()))
}

fn validate_surface_element(
    tx: &Transaction,
    model: &Model,
    schema: &Schema,
    target: EntityId,
) -> StyleResult<String> {
    let actual = staged_type(tx, model, target).ok_or(StyleError::DanglingReference {
        source_id: EntityId(0),
        target,
    })?;
    if SURFACE_STYLE_ELEMENT_MEMBERS
        .iter()
        .any(|member| schema.is_a(&actual, member))
    {
        Ok(actual)
    } else {
        Err(StyleError::ReferenceType {
            target,
            expected: "IfcSurfaceStyleElementSelect",
            actual,
        })
    }
}

fn validate_layered_item(
    tx: &Transaction,
    model: &Model,
    schema: &Schema,
    target: EntityId,
) -> StyleResult<()> {
    let actual = staged_type(tx, model, target).ok_or(StyleError::DanglingReference {
        source_id: EntityId(0),
        target,
    })?;
    if schema.is_a(&actual, "IfcRepresentationItem") || schema.is_a(&actual, "IfcRepresentation") {
        Ok(())
    } else {
        Err(StyleError::ReferenceType {
            target,
            expected: "IfcLayeredItem",
            actual,
        })
    }
}

/// Authored fields for an `IfcSurfaceStyleRendering`.
///
/// The rendering form extends the shading form with the parameters a
/// renderer needs. Every colour slot is an `IfcColourOrFactor`, so a
/// caller states either an explicit colour or a factor of the surface
/// colour -- the two are not interchangeable and the schema keeps both.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct SurfaceStyleRenderingDraft {
    /// `SurfaceColour`, an `IfcColourRgb`.
    pub surface_colour: EntityId,
    /// `Transparency`, a normalised ratio.
    pub transparency: Option<f64>,
    /// `DiffuseColour`.
    pub diffuse: Option<ColourOrFactor>,
    /// `TransmissionColour`.
    pub transmission: Option<ColourOrFactor>,
    /// `DiffuseTransmissionColour`.
    pub diffuse_transmission: Option<ColourOrFactor>,
    /// `ReflectionColour`.
    pub reflection: Option<ColourOrFactor>,
    /// `SpecularColour`.
    pub specular: Option<ColourOrFactor>,
    /// `ReflectanceMethod`, an `IfcReflectanceMethodEnum` token.
    pub reflectance_method: &'static str,
}

impl SurfaceStyleRenderingDraft {
    /// Starts a draft from its required `surface_colour`, `reflectance_method`;
    /// every other field is unset.
    #[must_use]
    pub fn new(surface_colour: EntityId, reflectance_method: &'static str) -> Self {
        Self {
            surface_colour,
            transparency: None,
            diffuse: None,
            transmission: None,
            diffuse_transmission: None,
            reflection: None,
            specular: None,
            reflectance_method,
        }
    }

    /// Sets `transparency`.
    ///
    /// `Transparency`, a normalised ratio.
    #[must_use]
    pub fn transparency(mut self, value: f64) -> Self {
        self.transparency = Some(value);
        self
    }

    /// Sets `diffuse`.
    ///
    /// `DiffuseColour`.
    #[must_use]
    pub fn diffuse(mut self, value: ColourOrFactor) -> Self {
        self.diffuse = Some(value);
        self
    }

    /// Sets `transmission`.
    ///
    /// `TransmissionColour`.
    #[must_use]
    pub fn transmission(mut self, value: ColourOrFactor) -> Self {
        self.transmission = Some(value);
        self
    }

    /// Sets `diffuse_transmission`.
    ///
    /// `DiffuseTransmissionColour`.
    #[must_use]
    pub fn diffuse_transmission(mut self, value: ColourOrFactor) -> Self {
        self.diffuse_transmission = Some(value);
        self
    }

    /// Sets `reflection`.
    ///
    /// `ReflectionColour`.
    #[must_use]
    pub fn reflection(mut self, value: ColourOrFactor) -> Self {
        self.reflection = Some(value);
        self
    }

    /// Sets `specular`.
    ///
    /// `SpecularColour`.
    #[must_use]
    pub fn specular(mut self, value: ColourOrFactor) -> Self {
        self.specular = Some(value);
        self
    }
}

/// Stage an `IfcSurfaceStyleRendering`.
///
/// # Errors
///
/// Refuses a `surface_colour` or colour member that is not an
/// `IfcColourRgb`, a factor or transparency outside `[0, 1]`, and a
/// `reflectance_method` the schema does not declare.
pub fn create_surface_style_rendering(
    tx: &mut Transaction,
    model: &Model,
    schema: &Schema,
    draft: SurfaceStyleRenderingDraft,
) -> StyleResult<EntityId> {
    const ENTITY: &str = "IfcSurfaceStyleRendering";
    validate_ref(tx, model, schema, draft.surface_colour, "IfcColourRgb")?;
    if let Some(value) = draft.transparency {
        validate_ratio(ENTITY, "Transparency", value)?;
    }
    let mut values = vec![("SurfaceColour", Value::Ref(draft.surface_colour))];
    if let Some(value) = draft.transparency {
        values.push(("Transparency", Value::Real(value)));
    }
    for (attribute, member) in [
        ("DiffuseColour", draft.diffuse),
        ("TransmissionColour", draft.transmission),
        ("DiffuseTransmissionColour", draft.diffuse_transmission),
        ("ReflectionColour", draft.reflection),
        ("SpecularColour", draft.specular),
    ] {
        let Some(member) = member else { continue };
        let value = match member {
            ColourOrFactor::Colour(id) => {
                validate_ref(tx, model, schema, id, "IfcColourRgb")?;
                Value::Ref(id)
            }
            ColourOrFactor::Factor(factor) => {
                validate_ratio(ENTITY, attribute, factor)?;
                Value::Real(factor)
            }
        };
        values.push((attribute, value));
    }
    // A reflectance method the schema does not declare names a
    // shading model the renderer cannot resolve.
    let declared = schema
        .attributes(ENTITY)
        .iter()
        .find(|a| a.name.eq_ignore_ascii_case("ReflectanceMethod"))
        .and_then(|a| schema.type_def(&a.type_name))
        .is_some_and(|def| match &def.kind {
            ifc_schema::TypeKind::Enumeration(values) => values
                .iter()
                .any(|v| v.eq_ignore_ascii_case(draft.reflectance_method)),
            _ => false,
        });
    if !declared {
        return Err(invalid_authoring(
            ENTITY,
            "ReflectanceMethod",
            draft.reflectance_method,
        ));
    }
    values.push((
        "ReflectanceMethod",
        Value::Enum(draft.reflectance_method.into()),
    ));
    Ok(tx.create(build_named(schema, ENTITY, values)?))
}