1use crate::{Error, Result};
8use ifc_lite_core::{AttributeValue, DecodedEntity, EntityDecoder, IfcType};
9use serde::{Deserialize, Serialize};
10use std::cell::Cell;
11use std::collections::BTreeMap;
12pub(super) const MAX_SOURCE_VALUE_DEPTH: usize = 32;
13pub(super) const MAX_SOURCE_VALUES: usize = 1_000_000;
14
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18#[serde(tag = "type", content = "value", rename_all = "snake_case")]
19pub enum SourceValue {
20 EntityRef(u32),
21 String(String),
22 Integer(i64),
23 Real(f64),
24 Binary(String),
25 Enum(String),
26 List(Vec<SourceValue>),
27 Typed {
28 name: String,
29 value: Box<SourceValue>,
30 },
31 Null,
32 Derived,
33}
34
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
36pub struct SourceRecord {
37 pub id: u32,
38 pub ifc_type_name: String,
39 pub attributes: BTreeMap<String, SourceValue>,
41}
42
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
44pub struct AnalyticBoundarySource {
45 pub root_entity_id: u32,
46 pub capture_status: super::AnalyticStatus,
48 pub plane_angle_to_radians: f64,
50 #[serde(serialize_with = "serialize_source_records")]
54 pub records: BTreeMap<u32, SourceRecord>,
55}
56
57fn serialize_source_records<S: serde::Serializer>(
60 records: &BTreeMap<u32, SourceRecord>,
61 serializer: S,
62) -> std::result::Result<S::Ok, S::Error> {
63 serializer.collect_map(records.iter().map(|(id, record)| (id.to_string(), record)))
64}
65
66thread_local! {
67 static REQUESTED: Cell<bool> = const { Cell::new(false) };
68}
69
70pub fn with_source_capture<R>(f: impl FnOnce() -> R) -> R {
78 struct Restore(bool);
79 impl Drop for Restore {
80 fn drop(&mut self) {
81 REQUESTED.with(|requested| requested.set(self.0));
82 }
83 }
84 let _restore = Restore(REQUESTED.with(|requested| requested.replace(true)));
85 f()
86}
87
88pub(super) fn requested() -> bool {
89 #[cfg(all(target_arch = "wasm32", not(feature = "wasm_source_capture")))]
94 {
95 false
96 }
97 #[cfg(any(not(target_arch = "wasm32"), feature = "wasm_source_capture"))]
98 {
99 REQUESTED.with(Cell::get)
100 }
101}
102
103#[derive(Default)]
104pub(super) struct SourceCapture {
105 records: BTreeMap<u32, SourceRecord>,
106 values: usize,
107 enabled: bool,
108 failure: Option<String>,
109}
110impl SourceCapture {
111 pub fn enabled() -> Self {
112 Self {
113 enabled: true,
114 ..Self::default()
115 }
116 }
117 pub fn finish(mut self, root_entity_id: u32, scale: f64) -> AnalyticBoundarySource {
118 if !scale.is_finite() || scale <= 0.0 {
119 self.fail("invalid source plane-angle unit scale".to_owned());
120 }
121 AnalyticBoundarySource {
122 root_entity_id,
123 capture_status: self.failure.map_or(
124 super::AnalyticStatus::Complete,
125 super::AnalyticStatus::Unsupported,
126 ),
127 plane_angle_to_radians: scale,
128 records: self.records,
129 }
130 }
131
132 pub fn is_enabled(&self) -> bool {
133 self.enabled
134 }
135
136 pub fn fail(&mut self, reason: String) {
137 self.records.clear();
138 self.enabled = false;
139 if self.failure.is_none() {
140 self.failure = Some(reason);
141 }
142 }
143
144 pub fn record(&mut self, entity: &DecodedEntity, decoder: &mut EntityDecoder) -> Result<()> {
145 self.try_record(entity, decoder)
146 .or_else(|error| self.fail_error(error))
147 }
148
149 pub fn fail_error(&mut self, error: Error) -> Result<()> {
150 #[cfg(feature = "retained-runtime")]
151 if matches!(error, Error::ProgramStopped(_)) {
152 return Err(error);
153 }
154 self.fail(error.to_string());
155 Ok(())
156 }
157
158 fn try_record(&mut self, entity: &DecodedEntity, decoder: &mut EntityDecoder) -> Result<()> {
162 if !self.enabled {
163 return Ok(());
164 }
165 let mut pending = vec![entity.clone()];
166 let mut visited = std::collections::HashSet::new();
167 let mut work = 0;
168 while let Some(entity) = pending.pop() {
169 #[cfg(feature = "retained-runtime")]
170 crate::resource::source_step()?;
171 work += 1;
172 if work > 1_000_000 {
173 return Err(invalid("source coefficient work budget exceeded"));
174 }
175 if !visited.insert(entity.id) || self.records.contains_key(&entity.id) {
176 continue;
177 }
178 self.record_values(&entity)?;
179 pending.extend(Self::coefficients(&entity, decoder)?);
180 }
181 Ok(())
182 }
183
184 fn record_values(&mut self, entity: &DecodedEntity) -> Result<()> {
185 let names: &[&str] = match entity.ifc_type {
186 IfcType::IfcRectangleProfileDef => {
187 &["ProfileType", "ProfileName", "Position", "XDim", "YDim"]
188 }
189 IfcType::IfcArbitraryClosedProfileDef => &["ProfileType", "ProfileName", "OuterCurve"],
190 IfcType::IfcArbitraryProfileDefWithVoids => {
191 &["ProfileType", "ProfileName", "OuterCurve", "InnerCurves"]
192 }
193 IfcType::IfcCircleProfileDef => &["ProfileType", "ProfileName", "Position", "Radius"],
194 IfcType::IfcPolyline => &["Points"],
195 IfcType::IfcIndexedPolyCurve => &["Points", "Segments", "SelfIntersect"],
196 IfcType::IfcCompositeCurve | IfcType::IfcCompositeCurveOnSurface => {
197 &["Segments", "SelfIntersect"]
198 }
199 IfcType::IfcCompositeCurveSegment => &["Transition", "SameSense", "ParentCurve"],
200 IfcType::IfcTrimmedCurve => &[
201 "BasisCurve",
202 "Trim1",
203 "Trim2",
204 "SenseAgreement",
205 "MasterRepresentation",
206 ],
207 IfcType::IfcLine => &["Pnt", "Dir"],
208 IfcType::IfcExtrudedAreaSolid => {
209 &["SweptArea", "Position", "ExtrudedDirection", "Depth"]
210 }
211 IfcType::IfcSweptDiskSolid => &[
212 "Directrix",
213 "Radius",
214 "InnerRadius",
215 "StartParam",
216 "EndParam",
217 ],
218 IfcType::IfcBSplineCurveWithKnots => &[
219 "Degree",
220 "ControlPointsList",
221 "CurveForm",
222 "ClosedCurve",
223 "SelfIntersect",
224 "KnotMultiplicities",
225 "Knots",
226 "KnotSpec",
227 ],
228 IfcType::IfcRationalBSplineCurveWithKnots => &[
229 "Degree",
230 "ControlPointsList",
231 "CurveForm",
232 "ClosedCurve",
233 "SelfIntersect",
234 "KnotMultiplicities",
235 "Knots",
236 "KnotSpec",
237 "WeightsData",
238 ],
239 IfcType::IfcCircle => &["Position", "Radius"],
240 IfcType::IfcAxis2Placement2D => &["Location", "RefDirection"],
241 IfcType::IfcAxis2Placement3D => &["Location", "Axis", "RefDirection"],
242 IfcType::IfcCartesianPoint => &["Coordinates"],
243 IfcType::IfcDirection => &["DirectionRatios"],
244 IfcType::IfcVector => &["Orientation", "Magnitude"],
245 IfcType::IfcCartesianPointList2D | IfcType::IfcCartesianPointList3D => &["CoordList"],
246 _ => return Err(invalid("unsupported source record type")),
247 };
248 if self.records.len() >= 100_000 {
249 return Err(invalid("source records exceed work budget"));
250 }
251 let attributes = names
252 .iter()
253 .enumerate()
254 .filter_map(|(i, name)| entity.get(i).map(|v| (name, v)))
255 .map(|(name, v)| Ok(((*name).to_owned(), self.value(v, 0)?)))
256 .collect::<Result<_>>()?;
257 self.records.insert(
258 entity.id,
259 SourceRecord {
260 id: entity.id,
261 ifc_type_name: entity.ifc_type.name().to_owned(),
262 attributes,
263 },
264 );
265 Ok(())
266 }
267
268 fn coefficients(
269 entity: &DecodedEntity,
270 decoder: &mut EntityDecoder,
271 ) -> Result<Vec<DecodedEntity>> {
272 let mut dependencies = Vec::new();
273 use IfcType::*;
274 let slots: &[(usize, &[IfcType])] = match entity.ifc_type {
277 IfcRectangleProfileDef | IfcCircleProfileDef => &[(2, &[IfcAxis2Placement2D])],
278 IfcLine => &[(0, &[IfcCartesianPoint]), (1, &[IfcVector])],
279 IfcExtrudedAreaSolid => &[(1, &[IfcAxis2Placement3D]), (2, &[IfcDirection])],
280 IfcCircle => &[(0, &[IfcAxis2Placement2D, IfcAxis2Placement3D])],
281 IfcIndexedPolyCurve => &[(0, &[IfcCartesianPointList2D, IfcCartesianPointList3D])],
282 IfcAxis2Placement2D => &[(0, &[IfcCartesianPoint]), (1, &[IfcDirection])],
283 IfcAxis2Placement3D => &[
284 (0, &[IfcCartesianPoint]),
285 (1, &[IfcDirection]),
286 (2, &[IfcDirection]),
287 ],
288 IfcVector => &[(0, &[IfcDirection])],
289 _ => &[],
290 };
291 for &(slot, expected) in slots {
292 if let Some(id) = entity.get_ref(slot) {
293 dependencies.push(Self::coefficient(id, expected, decoder)?);
294 }
295 }
296 let points = match entity.ifc_type {
297 IfcPolyline => Some(ifc_lite_core::slot::IfcPolyline::POINTS.index()),
298 IfcBSplineCurveWithKnots => {
299 Some(ifc_lite_core::slot::IfcBSplineCurveWithKnots::CONTROL_POINTS_LIST.index())
300 }
301 IfcRationalBSplineCurveWithKnots => Some(
302 ifc_lite_core::slot::IfcRationalBSplineCurveWithKnots::CONTROL_POINTS_LIST.index(),
303 ),
304 _ => None,
305 };
306 if let Some(slot) = points {
307 if let Some(points) = entity.get_list(slot) {
308 for point in points {
309 #[cfg(feature = "retained-runtime")]
310 crate::resource::source_step()?;
311 if let Some(id) = point.as_entity_ref() {
312 dependencies.push(Self::coefficient(id, &[IfcCartesianPoint], decoder)?);
313 }
314 }
315 }
316 }
317 if entity.ifc_type == IfcTrimmedCurve {
318 for slot in [1, 2] {
319 if let Some(selectors) = entity.get_list(slot) {
320 for selector in selectors {
321 #[cfg(feature = "retained-runtime")]
322 crate::resource::source_step()?;
323 if let Some(id) = selector.as_entity_ref() {
324 dependencies.push(Self::coefficient(
325 id,
326 &[IfcCartesianPoint],
327 decoder,
328 )?);
329 }
330 }
331 }
332 }
333 }
334 Ok(dependencies)
335 }
336
337 fn coefficient(
338 id: u32,
339 expected: &[IfcType],
340 decoder: &mut EntityDecoder,
341 ) -> Result<DecodedEntity> {
342 let entity = decoder.decode_by_id(id)?;
343 if !expected.contains(&entity.ifc_type) {
346 return Err(invalid("invalid source coefficient dependency"));
347 }
348 Ok(entity)
349 }
350
351 fn value(&mut self, value: &AttributeValue, depth: usize) -> Result<SourceValue> {
352 #[cfg(feature = "retained-runtime")]
353 crate::resource::source_step()?;
354 self.values += 1;
355 if depth >= MAX_SOURCE_VALUE_DEPTH || self.values > MAX_SOURCE_VALUES {
356 return Err(invalid("source values exceed work budget"));
357 }
358 Ok(match value {
359 AttributeValue::EntityRef(v) => SourceValue::EntityRef(*v),
360 AttributeValue::String(v) => SourceValue::String(v.clone()),
361 AttributeValue::Binary(v) => SourceValue::Binary(v.clone()),
362 AttributeValue::Integer(v) => SourceValue::Integer(*v),
363 AttributeValue::Float(v) if v.is_finite() => SourceValue::Real(*v),
364 AttributeValue::Float(_) => return Err(invalid("nonfinite source coefficient")),
365 AttributeValue::Enum(v) => SourceValue::Enum(v.clone()),
366 AttributeValue::List(v) => SourceValue::List(
367 v.iter()
368 .map(|x| self.value(x, depth + 1))
369 .collect::<Result<_>>()?,
370 ),
371 AttributeValue::Typed { name, value } => SourceValue::Typed {
372 name: name.to_string(),
373 value: Box::new(self.value(value, depth + 1)?),
374 },
375 AttributeValue::Null => SourceValue::Null,
376 AttributeValue::Derived => SourceValue::Derived,
377 })
378 }
379}
380fn invalid(message: &str) -> Error {
381 Error::geometry(message.to_owned())
382}