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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
//! Externally defined styles, texture coordinate indices, and
//! the blob texture.
//!
//! # Why these sit apart from the presentation writers
//!
//! An externally defined style names a style held in another
//! system: a hatch pattern in a CAD library, a font the file does
//! not embed. The record carries only the reference, so nothing
//! here validates the target exists -- that is the point of the
//! entity, and inventing a check would refuse legitimate files.
//!
//! # The rules that are enforced
//!
//! `IfcBlobTexture` states both of the family's WHERE rules:
//!
//! ```text
//! RasterCodeByteStream  : BLENGTH(RasterCode) MOD 8 = 0;
//! SupportedRasterFormat : SELF.RasterFormat IN ['BMP','JPG','GIF','PNG'];
//! ```
//!
//! A raster code that is not a whole number of bytes cannot be
//! decoded by any reader, and a format outside the closed list
//! names a decoder the schema does not promise.

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

use crate::error::StyleResult;

use super::{build_named, invalid_authoring, optional_reference, optional_text};

/// Which externally defined style is being named.
///
/// The three share one attribute shape, so a single writer covers
/// them; the tag keeps a caller from spelling the type name itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExternalStyleKind {
    /// `IfcExternallyDefinedHatchStyle`: a fill pattern held elsewhere.
    HatchStyle,
    /// `IfcExternallyDefinedSurfaceStyle`: a surface appearance held elsewhere.
    SurfaceStyle,
    /// `IfcExternallyDefinedTextFont`: a font the file does not embed.
    TextFont,
}

impl ExternalStyleKind {
    fn type_name(self) -> &'static str {
        match self {
            Self::HatchStyle => "IfcExternallyDefinedHatchStyle",
            Self::SurfaceStyle => "IfcExternallyDefinedSurfaceStyle",
            Self::TextFont => "IfcExternallyDefinedTextFont",
        }
    }
}

/// Stage an externally defined style reference.
///
/// All three attributes are optional in the schema, but a reference
/// naming nothing at all identifies no external resource: it would
/// round-trip as three nulls and resolve for no reader. At least one
/// of location, identification, or name must be given.
///
/// # Errors
///
/// Refuses a reference with no locating attribute set, and a blank
/// string in any attribute that is supplied.
pub fn create_externally_defined_style(
    tx: &mut Transaction,
    schema: &Schema,
    kind: ExternalStyleKind,
    location: Option<&str>,
    identification: Option<&str>,
    name: Option<&str>,
) -> StyleResult<EntityId> {
    let entity = kind.type_name();
    for (attribute, value) in [
        ("Location", location),
        ("Identification", identification),
        ("Name", name),
    ] {
        if value.is_some_and(|text| text.trim().is_empty()) {
            return Err(invalid_authoring(entity, attribute, "blank"));
        }
    }
    if location.is_none() && identification.is_none() && name.is_none() {
        return Err(invalid_authoring(entity, "Location", "no attribute set"));
    }
    let mut values = Vec::new();
    optional_text(&mut values, "Location", location);
    optional_text(&mut values, "Identification", identification);
    optional_text(&mut values, "Name", name);
    Ok(tx.create(build_named(schema, entity, values)?))
}

fn index_list(
    entity: &'static str,
    attribute: &'static str,
    indices: &[i64],
) -> StyleResult<Value> {
    if indices.len() < 3 {
        return Err(invalid_authoring(entity, attribute, indices.len()));
    }
    // IfcPositiveInteger is one-based: 0 is not a valid index and
    // accepting it would silently shift every lookup by one.
    if let Some(bad) = indices.iter().find(|index| **index < 1) {
        return Err(invalid_authoring(entity, attribute, bad));
    }
    Ok(Value::List(
        indices.iter().copied().map(Value::Integer).collect(),
    ))
}

/// Stage an `IfcTextureCoordinateIndices`.
///
/// # Errors
///
/// Refuses fewer than three indices, and any index below 1.
pub fn create_texture_coordinate_indices(
    tx: &mut Transaction,
    schema: &Schema,
    tex_coord_index: &[i64],
    tex_coords_of: EntityId,
) -> StyleResult<EntityId> {
    const ENTITY: &str = "IfcTextureCoordinateIndices";
    let values = vec![
        (
            "TexCoordIndex",
            index_list(ENTITY, "TexCoordIndex", tex_coord_index)?,
        ),
        ("TexCoordsOf", Value::Ref(tex_coords_of)),
    ];
    Ok(tx.create(build_named(schema, ENTITY, values)?))
}

/// Stage an `IfcTextureCoordinateIndicesWithVoids`.
///
/// `inner_tex_coord_indices` is `LIST [1:?] OF LIST [3:?] OF UNIQUE`:
/// each void is its own loop of at least three indices, and the
/// indices within one void must be distinct. A repeated index inside
/// a void collapses two corners of the hole onto one texture
/// coordinate, which parses and renders wrongly.
///
/// # Errors
///
/// Refuses an outer list with no voids, any void with fewer than
/// three indices, any index below 1, and a repeated index within a
/// single void.
pub fn create_texture_coordinate_indices_with_voids(
    tx: &mut Transaction,
    schema: &Schema,
    tex_coord_index: &[i64],
    tex_coords_of: EntityId,
    inner_tex_coord_indices: &[&[i64]],
) -> StyleResult<EntityId> {
    const ENTITY: &str = "IfcTextureCoordinateIndicesWithVoids";
    if inner_tex_coord_indices.is_empty() {
        return Err(invalid_authoring(ENTITY, "InnerTexCoordIndices", "empty"));
    }
    let mut inner = Vec::with_capacity(inner_tex_coord_indices.len());
    for void in inner_tex_coord_indices {
        let list = index_list(ENTITY, "InnerTexCoordIndices", void)?;
        // UNIQUE is declared on the inner list, so duplicates are
        // checked per void rather than across the whole set.
        for (position, index) in void.iter().enumerate() {
            if void[..position].contains(index) {
                return Err(invalid_authoring(ENTITY, "InnerTexCoordIndices", index));
            }
        }
        inner.push(list);
    }
    let values = vec![
        (
            "TexCoordIndex",
            index_list(ENTITY, "TexCoordIndex", tex_coord_index)?,
        ),
        ("TexCoordsOf", Value::Ref(tex_coords_of)),
        ("InnerTexCoordIndices", Value::List(inner)),
    ];
    Ok(tx.create(build_named(schema, ENTITY, values)?))
}

/// Attributes of an `IfcBlobTexture`.
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct BlobTextureDraft<'a> {
    /// `RepeatS`: whether the texture tiles along S.
    pub repeat_s: bool,
    /// `RepeatT`: whether the texture tiles along T.
    pub repeat_t: bool,
    /// `Mode`: the texture application mode.
    pub mode: Option<&'a str>,
    /// `TextureTransform`: a 2D operator applied to the coordinates.
    pub texture_transform: Option<EntityId>,
    /// `Parameter`: optional, but non-empty when present.
    pub parameter: &'a [&'a str],
    /// `RasterFormat`: one of BMP, JPG, GIF, PNG.
    pub raster_format: &'a str,
    /// `RasterCode`: the hex payload, a whole number of bytes.
    pub raster_code: &'a str,
}

/// Raster formats `SupportedRasterFormat` admits.
///
/// Closed and upper-case in the schema: 'png' is not 'PNG'.
const RASTER_FORMATS: &[&str] = &["BMP", "JPG", "GIF", "PNG"];

/// Stage an `IfcBlobTexture`, embedding the raster bytes in the file.
///
/// `raster_code` is the hex payload as it appears in STEP, without
/// the surrounding quotes. `RasterCodeByteStream` requires it to be
/// a whole number of bytes: STEP binary is bit-counted, so an odd
/// hex-digit count is a partial byte no decoder can complete.
///
/// # Errors
///
/// Refuses a raster format outside the closed list, a payload that is
/// not a whole number of bytes, a non-hex payload, an empty payload,
/// and an empty parameter list.
pub fn create_blob_texture(
    tx: &mut Transaction,
    schema: &Schema,
    draft: BlobTextureDraft<'_>,
) -> StyleResult<EntityId> {
    let BlobTextureDraft {
        repeat_s,
        repeat_t,
        mode,
        texture_transform,
        parameter,
        raster_format,
        raster_code,
    } = draft;
    const ENTITY: &str = "IfcBlobTexture";
    if !RASTER_FORMATS.contains(&raster_format) {
        return Err(invalid_authoring(ENTITY, "RasterFormat", raster_format));
    }
    if raster_code.is_empty() {
        return Err(invalid_authoring(ENTITY, "RasterCode", "empty"));
    }
    // BLENGTH counts bits; one hex digit is four bits, so a whole
    // byte is an even digit count.
    if raster_code.len() % 2 != 0 {
        return Err(invalid_authoring(ENTITY, "RasterCode", raster_code.len()));
    }
    if let Some(bad) = raster_code.chars().find(|c| !c.is_ascii_hexdigit()) {
        return Err(invalid_authoring(ENTITY, "RasterCode", bad));
    }
    Ok(tx.create(build_named(
        schema,
        ENTITY,
        blob_values(
            repeat_s,
            repeat_t,
            mode,
            texture_transform,
            parameter,
            raster_format,
            raster_code,
        )?,
    )?))
}

#[allow(clippy::too_many_arguments)]
fn blob_values(
    repeat_s: bool,
    repeat_t: bool,
    mode: Option<&str>,
    texture_transform: Option<EntityId>,
    parameter: &[&str],
    raster_format: &str,
    raster_code: &str,
) -> StyleResult<Vec<(&'static str, Value)>> {
    const ENTITY: &str = "IfcBlobTexture";
    // Parameter is OPTIONAL LIST [1:?]: absent is legal, present and
    // empty is not.
    let parameters = if parameter.is_empty() {
        Value::Null
    } else {
        for text in parameter {
            if text.trim().is_empty() {
                return Err(invalid_authoring(ENTITY, "Parameter", "blank"));
            }
        }
        Value::List(parameter.iter().map(|t| Value::Text((*t).into())).collect())
    };
    let mut values = vec![
        ("RepeatS", Value::Bool(repeat_s)),
        ("RepeatT", Value::Bool(repeat_t)),
        ("RasterFormat", Value::Text(raster_format.into())),
        ("RasterCode", Value::Binary(raster_code.into())),
    ];
    if !matches!(parameters, Value::Null) {
        values.push(("Parameter", parameters));
    }
    optional_text(&mut values, "Mode", mode);
    optional_reference(&mut values, "TextureTransform", texture_transform);
    Ok(values)
}

/// Stage an `IfcSurfaceStyleWithTextures`.
///
/// # Errors
///
/// Refuses an empty texture list: the single attribute is
/// `LIST [1:?]`, so a style with no textures is not a style.
pub fn create_surface_style_with_textures(
    tx: &mut Transaction,
    schema: &Schema,
    textures: &[EntityId],
) -> StyleResult<EntityId> {
    const ENTITY: &str = "IfcSurfaceStyleWithTextures";
    if textures.is_empty() {
        return Err(invalid_authoring(ENTITY, "Textures", "empty"));
    }
    let values = vec![(
        "Textures",
        Value::List(textures.iter().copied().map(Value::Ref).collect()),
    )];
    Ok(tx.create(build_named(schema, ENTITY, values)?))
}

/// Stage an `IfcIndexedPolygonalTextureMap`.
///
/// # Errors
///
/// Refuses an empty map list and an empty coordinate-index set,
/// both declared `[1:?]`.
pub fn create_indexed_polygonal_texture_map(
    tx: &mut Transaction,
    schema: &Schema,
    maps: &[EntityId],
    mapped_to: EntityId,
    tex_coords: EntityId,
    tex_coord_indices: &[EntityId],
) -> StyleResult<EntityId> {
    const ENTITY: &str = "IfcIndexedPolygonalTextureMap";
    if maps.is_empty() {
        return Err(invalid_authoring(ENTITY, "Maps", "empty"));
    }
    if tex_coord_indices.is_empty() {
        return Err(invalid_authoring(ENTITY, "TexCoordIndices", "empty"));
    }
    let values = vec![
        (
            "Maps",
            Value::List(maps.iter().copied().map(Value::Ref).collect()),
        ),
        ("MappedTo", Value::Ref(mapped_to)),
        ("TexCoords", Value::Ref(tex_coords)),
        (
            "TexCoordIndices",
            Value::List(tex_coord_indices.iter().copied().map(Value::Ref).collect()),
        ),
    ];
    Ok(tx.create(build_named(schema, ENTITY, values)?))
}

/// `IfcTextAlignment`: closed and lower-case.
const TEXT_ALIGNMENT: &[&str] = &["left", "right", "center", "justify"];

/// `IfcTextDecoration`: closed and lower-case.
const TEXT_DECORATION: &[&str] = &["none", "underline", "overline", "line-through", "blink"];

/// `IfcTextTransformation`: closed and lower-case.
const TEXT_TRANSFORMATION: &[&str] = &["capitalize", "uppercase", "lowercase", "none"];

fn closed(
    entity: &'static str,
    attribute: &'static str,
    value: Option<&str>,
    permitted: &[&str],
) -> StyleResult<Value> {
    let Some(text) = value else {
        return Ok(Value::Null);
    };
    // Case-sensitive: the schema lists 'none', so 'None' fails WR1.
    if !permitted.contains(&text) {
        return Err(invalid_authoring(entity, attribute, text));
    }
    Ok(Value::Text(text.into()))
}

/// A resolved `IfcSizeSelect` value.
///
/// The select admits six measure types, and a bare real is
/// ambiguous between them. The caller names which one it means so
/// the value is written typed rather than guessed.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SizeValue<'a> {
    /// `IfcDescriptiveMeasure`: a word such as 'small'.
    Descriptive(&'a str),
    /// `IfcLengthMeasure`: any finite length.
    Length(f64),
    /// `IfcPositiveLengthMeasure`: a length above zero.
    PositiveLength(f64),
    /// `IfcRatioMeasure`: any finite ratio.
    Ratio(f64),
    /// `IfcNormalisedRatioMeasure`: a ratio within 0 to 1.
    NormalisedRatio(f64),
    /// `IfcPositiveRatioMeasure`: a ratio above zero.
    PositiveRatio(f64),
}

impl SizeValue<'_> {
    fn into_value(self, entity: &'static str, attribute: &'static str) -> StyleResult<Value> {
        let (type_name, inner) = match self {
            Self::Descriptive(text) => {
                if text.trim().is_empty() {
                    return Err(invalid_authoring(entity, attribute, "blank"));
                }
                ("IFCDESCRIPTIVEMEASURE", Value::Text(text.into()))
            }
            Self::Length(v) => ("IFCLENGTHMEASURE", finite(entity, attribute, v)?),
            Self::PositiveLength(v) => {
                if v <= 0.0 {
                    return Err(invalid_authoring(entity, attribute, v));
                }
                ("IFCPOSITIVELENGTHMEASURE", finite(entity, attribute, v)?)
            }
            Self::Ratio(v) => ("IFCRATIOMEASURE", finite(entity, attribute, v)?),
            Self::NormalisedRatio(v) => {
                if !(0.0..=1.0).contains(&v) {
                    return Err(invalid_authoring(entity, attribute, v));
                }
                ("IFCNORMALISEDRATIOMEASURE", finite(entity, attribute, v)?)
            }
            Self::PositiveRatio(v) => {
                if v <= 0.0 {
                    return Err(invalid_authoring(entity, attribute, v));
                }
                ("IFCPOSITIVERATIOMEASURE", finite(entity, attribute, v)?)
            }
        };
        Ok(Value::Typed {
            type_name: type_name.into(),
            value: Box::new(inner),
        })
    }
}

fn finite(entity: &'static str, attribute: &'static str, value: f64) -> StyleResult<Value> {
    if !value.is_finite() {
        return Err(invalid_authoring(entity, attribute, value));
    }
    Ok(Value::Real(value))
}

/// Attributes of an `IfcTextStyleTextModel`.
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct TextModelDraft<'a> {
    /// `TextIndent`.
    pub text_indent: Option<SizeValue<'a>>,
    /// `TextAlign`, one of the closed lower-case alignment words.
    pub text_align: Option<&'a str>,
    /// `TextDecoration`, one of the closed lower-case decoration words.
    pub text_decoration: Option<&'a str>,
    /// `LetterSpacing`.
    pub letter_spacing: Option<SizeValue<'a>>,
    /// `WordSpacing`.
    pub word_spacing: Option<SizeValue<'a>>,
    /// `TextTransform`, one of the closed lower-case transform words.
    pub text_transform: Option<&'a str>,
    /// `LineHeight`.
    pub line_height: Option<SizeValue<'a>>,
}

/// Stage an `IfcTextStyleTextModel`.
///
/// Every attribute is optional, so this writer enforces the value
/// rules rather than presence: the three word-valued attributes are
/// closed lower-case lists, and each size is a resolved select.
///
/// # Errors
///
/// Refuses a word outside its closed list, and a size value that
/// violates the measure type the caller named.
pub fn create_text_style_text_model(
    tx: &mut Transaction,
    schema: &Schema,
    draft: TextModelDraft<'_>,
) -> StyleResult<EntityId> {
    const ENTITY: &str = "IfcTextStyleTextModel";
    let values = vec![
        ("TextIndent", size(ENTITY, "TextIndent", draft.text_indent)?),
        (
            "TextAlign",
            closed(ENTITY, "TextAlign", draft.text_align, TEXT_ALIGNMENT)?,
        ),
        (
            "TextDecoration",
            closed(
                ENTITY,
                "TextDecoration",
                draft.text_decoration,
                TEXT_DECORATION,
            )?,
        ),
        (
            "LetterSpacing",
            size(ENTITY, "LetterSpacing", draft.letter_spacing)?,
        ),
        (
            "WordSpacing",
            size(ENTITY, "WordSpacing", draft.word_spacing)?,
        ),
        (
            "TextTransform",
            closed(
                ENTITY,
                "TextTransform",
                draft.text_transform,
                TEXT_TRANSFORMATION,
            )?,
        ),
        ("LineHeight", size(ENTITY, "LineHeight", draft.line_height)?),
    ];
    Ok(tx.create(build_named(schema, ENTITY, values)?))
}

fn size(
    entity: &'static str,
    attribute: &'static str,
    value: Option<SizeValue<'_>>,
) -> StyleResult<Value> {
    value.map_or(Ok(Value::Null), |v| v.into_value(entity, attribute))
}

/// Stage an `IfcTextStyle`.
///
/// `text_font_style` is `IfcTextFontSelect` and is required: it
/// resolves to either a pre-defined text font or an externally
/// defined one, both of which this module can stage.
///
/// # Errors
///
/// Refuses a blank name.
pub fn create_text_style(
    tx: &mut Transaction,
    schema: &Schema,
    name: Option<&str>,
    text_character_appearance: Option<EntityId>,
    text_style: Option<EntityId>,
    text_font_style: EntityId,
    model_or_draughting: Option<bool>,
) -> StyleResult<EntityId> {
    const ENTITY: &str = "IfcTextStyle";
    if name.is_some_and(|text| text.trim().is_empty()) {
        return Err(invalid_authoring(ENTITY, "Name", "blank"));
    }
    let mut values = vec![("TextFontStyle", Value::Ref(text_font_style))];
    optional_text(&mut values, "Name", name);
    optional_reference(
        &mut values,
        "TextCharacterAppearance",
        text_character_appearance,
    );
    optional_reference(&mut values, "TextStyle", text_style);
    if let Some(flag) = model_or_draughting {
        values.push(("ModelOrDraughting", Value::Bool(flag)));
    }
    Ok(tx.create(build_named(schema, ENTITY, values)?))
}

/// Stage an `IfcIndexedTriangleTextureMap`.
///
/// The triangle form differs from the polygonal one in its index
/// slot: `TexCoordIndex` is a list of triples of *integers* into the
/// coordinate list, not a list of index entities. Writing entity
/// references there would produce a map whose every triangle is
/// unresolvable, which is why the two forms have separate writers.
///
/// # Errors
///
/// Refuses an empty `maps` list (`LIST [1:?]`) and an index value of
/// zero: `IfcPositiveInteger` is one-based.
pub fn create_indexed_triangle_texture_map(
    tx: &mut Transaction,
    schema: &Schema,
    maps: &[EntityId],
    mapped_to: EntityId,
    tex_coords: EntityId,
    tex_coord_index: &[[i64; 3]],
) -> StyleResult<EntityId> {
    const ENTITY: &str = "IfcIndexedTriangleTextureMap";
    if maps.is_empty() {
        return Err(invalid_authoring(ENTITY, "Maps", "empty"));
    }
    for triangle in tex_coord_index {
        if let Some(index) = triangle.iter().find(|value| **value < 1) {
            return Err(invalid_authoring(
                ENTITY,
                "TexCoordIndex",
                format!("{index} is not a positive one-based index"),
            ));
        }
    }
    let mut values = vec![
        (
            "Maps",
            Value::List(maps.iter().copied().map(Value::Ref).collect()),
        ),
        ("MappedTo", Value::Ref(mapped_to)),
        ("TexCoords", Value::Ref(tex_coords)),
    ];
    if !tex_coord_index.is_empty() {
        values.push((
            "TexCoordIndex",
            Value::List(
                tex_coord_index
                    .iter()
                    .map(|triangle| {
                        Value::List(triangle.iter().copied().map(Value::Integer).collect())
                    })
                    .collect(),
            ),
        ));
    }
    Ok(tx.create(build_named(schema, ENTITY, values)?))
}

/// Stage an `IfcLightDistributionData`: one row of a photometric
/// table.
///
/// A row fixes a main-plane angle and gives the intensity at each
/// secondary angle. The two lists are read in parallel, so a row whose
/// lengths disagree silently pairs an angle with the wrong intensity.
/// That is checked here rather than left to the reader.
///
/// # Errors
///
/// Refuses empty lists (both are `LIST [1:?]`), lists of differing
/// length, and non-finite values.
pub fn create_light_distribution_data(
    tx: &mut Transaction,
    schema: &Schema,
    main_plane_angle: f64,
    secondary_plane_angles: &[f64],
    luminous_intensities: &[f64],
) -> StyleResult<EntityId> {
    const ENTITY: &str = "IfcLightDistributionData";
    if secondary_plane_angles.is_empty() || luminous_intensities.is_empty() {
        return Err(invalid_authoring(ENTITY, "SecondaryPlaneAngle", "empty"));
    }
    if secondary_plane_angles.len() != luminous_intensities.len() {
        return Err(invalid_authoring(
            ENTITY,
            "LuminousIntensity",
            "expected one intensity per secondary angle",
        ));
    }
    if !main_plane_angle.is_finite()
        || secondary_plane_angles.iter().any(|v| !v.is_finite())
        || luminous_intensities.iter().any(|v| !v.is_finite())
    {
        return Err(invalid_authoring(ENTITY, "MainPlaneAngle", "not finite"));
    }
    let reals = |values: &[f64]| Value::List(values.iter().copied().map(Value::Real).collect());
    let values = vec![
        ("MainPlaneAngle", Value::Real(main_plane_angle)),
        ("SecondaryPlaneAngle", reals(secondary_plane_angles)),
        ("LuminousIntensity", reals(luminous_intensities)),
    ];
    Ok(tx.create(build_named(schema, ENTITY, values)?))
}

/// Stage an `IfcLightIntensityDistribution`: a photometric table.
///
/// # Errors
///
/// Refuses an empty `distribution_data` list (`LIST [1:?]`) and a
/// curve token the schema does not declare.
pub fn create_light_intensity_distribution(
    tx: &mut Transaction,
    schema: &Schema,
    light_distribution_curve: &str,
    distribution_data: &[EntityId],
) -> StyleResult<EntityId> {
    const ENTITY: &str = "IfcLightIntensityDistribution";
    if distribution_data.is_empty() {
        return Err(invalid_authoring(ENTITY, "DistributionData", "empty"));
    }
    let declared = schema
        .attributes(ENTITY)
        .iter()
        .find(|a| a.name.eq_ignore_ascii_case("LightDistributionCurve"))
        .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(light_distribution_curve)),
            _ => false,
        });
    if !declared {
        return Err(invalid_authoring(
            ENTITY,
            "LightDistributionCurve",
            light_distribution_curve,
        ));
    }
    let values = vec![
        (
            "LightDistributionCurve",
            Value::Enum(light_distribution_curve.into()),
        ),
        (
            "DistributionData",
            Value::List(distribution_data.iter().copied().map(Value::Ref).collect()),
        ),
    ];
    Ok(tx.create(build_named(schema, ENTITY, values)?))
}

mod builders;