1use ifc_model::{EntityId, Model, Transaction, Value};
24use ifc_schema::Schema;
25
26use crate::authoring::{build_named, invalid_authoring, validate_ratio, validate_ref};
27use crate::StyleResult;
28
29#[derive(Debug, Clone, Copy)]
31#[non_exhaustive]
32pub struct LightSourceDraft<'a> {
33 pub name: Option<&'a str>,
35 pub light_colour: EntityId,
37 pub ambient_intensity: Option<f64>,
39 pub intensity: Option<f64>,
41}
42
43impl<'a> LightSourceDraft<'a> {
44 #[must_use]
47 pub fn new(light_colour: EntityId) -> Self {
48 Self {
49 name: None,
50 light_colour,
51 ambient_intensity: None,
52 intensity: None,
53 }
54 }
55
56 #[must_use]
60 pub fn name(mut self, value: &'a str) -> Self {
61 self.name = Some(value);
62 self
63 }
64
65 #[must_use]
69 pub fn ambient_intensity(mut self, value: f64) -> Self {
70 self.ambient_intensity = Some(value);
71 self
72 }
73
74 #[must_use]
78 pub fn intensity(mut self, value: f64) -> Self {
79 self.intensity = Some(value);
80 self
81 }
82}
83
84#[derive(Debug, Clone, Copy)]
90pub struct Attenuation {
91 pub constant: f64,
93 pub distance: f64,
95 pub quadric: f64,
97}
98
99fn check_light(entity: &'static str, draft: &LightSourceDraft<'_>) -> StyleResult<()> {
100 if let Some(value) = draft.ambient_intensity {
101 validate_ratio(entity, "AmbientIntensity", value)?;
102 }
103 if let Some(value) = draft.intensity {
104 validate_ratio(entity, "Intensity", value)?;
105 }
106 Ok(())
107}
108
109fn light_values<'a>(draft: &LightSourceDraft<'a>) -> Vec<(&'static str, Value)> {
110 let mut values = vec![("LightColour", Value::Ref(draft.light_colour))];
111 if let Some(name) = draft.name {
112 values.push(("Name", Value::Text(name.into())));
113 }
114 if let Some(value) = draft.ambient_intensity {
115 values.push(("AmbientIntensity", Value::Real(value)));
116 }
117 if let Some(value) = draft.intensity {
118 values.push(("Intensity", Value::Real(value)));
119 }
120 values
121}
122
123fn check_attenuation(entity: &'static str, attenuation: &Attenuation) -> StyleResult<()> {
124 let all = [
125 ("ConstantAttenuation", attenuation.constant),
126 ("DistanceAttenuation", attenuation.distance),
127 ("QuadricAttenuation", attenuation.quadric),
128 ];
129 for (attribute, value) in all {
130 if !value.is_finite() {
131 return Err(invalid_authoring(
132 entity,
133 attribute,
134 format!("expected a finite coefficient, got {value}"),
135 ));
136 }
137 }
138 if all.iter().all(|(_, value)| *value == 0.0) {
139 return Err(invalid_authoring(
140 entity,
141 "ConstantAttenuation",
142 "all three coefficients zero leaves no attenuation function",
143 ));
144 }
145 Ok(())
146}
147
148pub fn create_light_source_ambient(
155 tx: &mut Transaction,
156 model: &Model,
157 schema: &Schema,
158 draft: LightSourceDraft<'_>,
159) -> StyleResult<EntityId> {
160 check_light("IfcLightSourceAmbient", &draft)?;
161 validate_ref(tx, model, schema, draft.light_colour, "IfcColourRgb")?;
162 Ok(tx.create(build_named(
163 schema,
164 "IfcLightSourceAmbient",
165 light_values(&draft),
166 )?))
167}
168
169pub fn create_light_source_directional(
176 tx: &mut Transaction,
177 model: &Model,
178 schema: &Schema,
179 draft: LightSourceDraft<'_>,
180 orientation: EntityId,
181) -> StyleResult<EntityId> {
182 check_light("IfcLightSourceDirectional", &draft)?;
183 validate_ref(tx, model, schema, draft.light_colour, "IfcColourRgb")?;
184 validate_ref(tx, model, schema, orientation, "IfcDirection")?;
185
186 let mut values = light_values(&draft);
187 values.push(("Orientation", Value::Ref(orientation)));
188 Ok(tx.create(build_named(schema, "IfcLightSourceDirectional", values)?))
189}
190
191pub fn create_light_source_positional(
199 tx: &mut Transaction,
200 model: &Model,
201 schema: &Schema,
202 draft: LightSourceDraft<'_>,
203 point: PointLight,
204) -> StyleResult<EntityId> {
205 let PointLight {
206 position,
207 radius,
208 attenuation,
209 } = point;
210 check_light("IfcLightSourcePositional", &draft)?;
211 if !radius.is_finite() || radius <= 0.0 {
212 return Err(invalid_authoring(
213 "IfcLightSourcePositional",
214 "Radius",
215 format!("expected a positive length, got {radius}"),
216 ));
217 }
218 check_attenuation("IfcLightSourcePositional", &attenuation)?;
219 validate_ref(tx, model, schema, draft.light_colour, "IfcColourRgb")?;
220 validate_ref(tx, model, schema, position, "IfcCartesianPoint")?;
221
222 let mut values = light_values(&draft);
223 values.extend([
224 ("Position", Value::Ref(position)),
225 ("Radius", Value::Real(radius)),
226 ("ConstantAttenuation", Value::Real(attenuation.constant)),
227 ("DistanceAttenuation", Value::Real(attenuation.distance)),
228 ("QuadricAttenuation", Value::Real(attenuation.quadric)),
229 ]);
230 Ok(tx.create(build_named(schema, "IfcLightSourcePositional", values)?))
231}
232
233#[derive(Debug, Clone, Copy)]
241pub struct PointLight {
242 pub position: EntityId,
244 pub radius: f64,
246 pub attenuation: Attenuation,
248}
249
250impl Default for Attenuation {
251 fn default() -> Self {
257 Self {
258 constant: 1.0,
259 distance: 0.0,
260 quadric: 0.0,
261 }
262 }
263}
264
265#[derive(Debug, Clone, Copy)]
267pub struct SpotCone {
268 pub orientation: EntityId,
270 pub spread_angle: f64,
272 pub beam_width_angle: f64,
274 pub concentration_exponent: Option<f64>,
276}
277
278pub fn create_light_source_spot(
285 tx: &mut Transaction,
286 model: &Model,
287 schema: &Schema,
288 draft: LightSourceDraft<'_>,
289 point: PointLight,
290 cone: SpotCone,
291) -> StyleResult<EntityId> {
292 let PointLight {
293 position,
294 radius,
295 attenuation,
296 } = point;
297 check_light("IfcLightSourceSpot", &draft)?;
298 if !radius.is_finite() || radius <= 0.0 {
299 return Err(invalid_authoring(
300 "IfcLightSourceSpot",
301 "Radius",
302 format!("expected a positive length, got {radius}"),
303 ));
304 }
305 check_attenuation("IfcLightSourceSpot", &attenuation)?;
306
307 for (attribute, value) in [
308 ("SpreadAngle", cone.spread_angle),
309 ("BeamWidthAngle", cone.beam_width_angle),
310 ] {
311 if !value.is_finite() || value <= 0.0 {
312 return Err(invalid_authoring(
313 "IfcLightSourceSpot",
314 attribute,
315 format!("expected a positive plane angle, got {value}"),
316 ));
317 }
318 }
319
320 validate_ref(tx, model, schema, draft.light_colour, "IfcColourRgb")?;
321 validate_ref(tx, model, schema, position, "IfcCartesianPoint")?;
322 validate_ref(tx, model, schema, cone.orientation, "IfcDirection")?;
323
324 let mut values = light_values(&draft);
325 values.extend([
326 ("Position", Value::Ref(position)),
327 ("Radius", Value::Real(radius)),
328 ("ConstantAttenuation", Value::Real(attenuation.constant)),
329 ("DistanceAttenuation", Value::Real(attenuation.distance)),
330 ("QuadricAttenuation", Value::Real(attenuation.quadric)),
331 ("Orientation", Value::Ref(cone.orientation)),
332 ("SpreadAngle", Value::Real(cone.spread_angle)),
333 ("BeamWidthAngle", Value::Real(cone.beam_width_angle)),
334 ]);
335 if let Some(value) = cone.concentration_exponent {
336 values.push(("ConcentrationExponent", Value::Real(value)));
337 }
338 Ok(tx.create(build_named(schema, "IfcLightSourceSpot", values)?))
339}
340
341pub fn create_surface_style_lighting(
347 tx: &mut Transaction,
348 model: &Model,
349 schema: &Schema,
350 diffuse_transmission: EntityId,
351 diffuse_reflection: EntityId,
352 transmission: EntityId,
353 reflectance: EntityId,
354) -> StyleResult<EntityId> {
355 for colour in [
356 diffuse_transmission,
357 diffuse_reflection,
358 transmission,
359 reflectance,
360 ] {
361 validate_ref(tx, model, schema, colour, "IfcColourRgb")?;
362 }
363
364 let values = vec![
365 (
366 "DiffuseTransmissionColour",
367 Value::Ref(diffuse_transmission),
368 ),
369 ("DiffuseReflectionColour", Value::Ref(diffuse_reflection)),
370 ("TransmissionColour", Value::Ref(transmission)),
371 ("ReflectanceColour", Value::Ref(reflectance)),
372 ];
373 Ok(tx.create(build_named(schema, "IfcSurfaceStyleLighting", values)?))
374}
375
376pub fn create_surface_style_refraction(
383 tx: &mut Transaction,
384 schema: &Schema,
385 refraction_index: Option<f64>,
386 dispersion_factor: Option<f64>,
387) -> StyleResult<EntityId> {
388 if let Some(value) = refraction_index {
389 if !value.is_finite() || value < 1.0 {
390 return Err(invalid_authoring(
391 "IfcSurfaceStyleRefraction",
392 "RefractionIndex",
393 format!("expected at least 1.0, the vacuum index, got {value}"),
394 ));
395 }
396 }
397 if let Some(value) = dispersion_factor {
398 if !value.is_finite() {
399 return Err(invalid_authoring(
400 "IfcSurfaceStyleRefraction",
401 "DispersionFactor",
402 format!("expected a finite factor, got {value}"),
403 ));
404 }
405 }
406
407 let mut values = Vec::new();
408 if let Some(value) = refraction_index {
409 values.push(("RefractionIndex", Value::Real(value)));
410 }
411 if let Some(value) = dispersion_factor {
412 values.push(("DispersionFactor", Value::Real(value)));
413 }
414 Ok(tx.create(build_named(schema, "IfcSurfaceStyleRefraction", values)?))
415}
416
417#[derive(Debug, Clone, Copy)]
419pub struct GoniometricLight {
420 pub position: EntityId,
422 pub colour_appearance: Option<EntityId>,
424 pub colour_temperature: f64,
426 pub luminous_flux: f64,
428 pub emission_source: &'static str,
430 pub distribution_data_source: EntityId,
433}
434
435pub fn create_light_source_goniometric(
448 tx: &mut Transaction,
449 model: &Model,
450 schema: &Schema,
451 draft: LightSourceDraft<'_>,
452 light: GoniometricLight,
453) -> StyleResult<EntityId> {
454 const ENTITY: &str = "IfcLightSourceGoniometric";
455 check_light(ENTITY, &draft)?;
456 validate_ref(tx, model, schema, draft.light_colour, "IfcColourRgb")?;
457 if let Some(colour) = light.colour_appearance {
458 validate_ref(tx, model, schema, colour, "IfcColourRgb")?;
459 }
460 for (value, attribute) in [
461 (light.colour_temperature, "ColourTemperature"),
462 (light.luminous_flux, "LuminousFlux"),
463 ] {
464 if !value.is_finite() || value <= 0.0 {
467 return Err(invalid_authoring(
468 ENTITY,
469 attribute,
470 format!("expected a positive measure, got {value}"),
471 ));
472 }
473 }
474 let declared = schema
475 .attributes(ENTITY)
476 .iter()
477 .find(|a| a.name.eq_ignore_ascii_case("LightEmissionSource"))
478 .and_then(|a| schema.type_def(&a.type_name))
479 .is_some_and(|def| match &def.kind {
480 ifc_schema::TypeKind::Enumeration(values) => values
481 .iter()
482 .any(|v| v.eq_ignore_ascii_case(light.emission_source)),
483 _ => false,
484 });
485 if !declared {
486 return Err(invalid_authoring(
487 ENTITY,
488 "LightEmissionSource",
489 light.emission_source,
490 ));
491 }
492
493 let mut values = light_values(&draft);
494 values.push(("Position", Value::Ref(light.position)));
495 if let Some(colour) = light.colour_appearance {
496 values.push(("ColourAppearance", Value::Ref(colour)));
497 }
498 values.push(("ColourTemperature", Value::Real(light.colour_temperature)));
499 values.push(("LuminousFlux", Value::Real(light.luminous_flux)));
500 values.push((
501 "LightEmissionSource",
502 Value::Enum(light.emission_source.into()),
503 ));
504 values.push((
505 "LightDistributionDataSource",
506 Value::Ref(light.distribution_data_source),
507 ));
508 Ok(tx.create(build_named(schema, ENTITY, values)?))
509}