1use ifc_model::value::Value;
24use ifc_model::{EntityId, Model};
25
26use crate::crs::Damage;
27use crate::error::{GeorefError, GeorefResult};
28use crate::slot::map_conversion as slot;
29use crate::view::GeorefView;
30
31pub(crate) const HAS_COORDINATE_OPERATION: &str =
33 "HasCoordinateOperation : SET [0:1] OF IfcCoordinateOperation";
34
35const UNPINNED_OPERATIONS: &[&str] = &[
38 "IFCMAPCONVERSION",
39 "IFCMAPCONVERSIONSCALED",
40 "IFCRIGIDOPERATION",
41];
42
43const UNPINNED_CRS: &[&str] = &["IFCPROJECTEDCRS", "IFCGEOGRAPHICCRS"];
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48#[non_exhaustive]
49pub enum OperationSource {
50 Context(EntityId),
54 CoordinateReferenceSystem(EntityId),
57 PropertySet(EntityId),
63}
64
65impl OperationSource {
66 #[must_use]
68 pub const fn entity(&self) -> EntityId {
69 match self {
70 Self::Context(id) | Self::CoordinateReferenceSystem(id) | Self::PropertySet(id) => *id,
71 }
72 }
73}
74
75pub fn resolve_operation_source(
92 view: &GeorefView,
93 operation: EntityId,
94) -> GeorefResult<OperationSource> {
95 let actual = view.require_known_type(operation)?;
96 if !view.schema.is_a(actual, "IfcCoordinateOperation") {
97 return Err(GeorefError::WrongType {
98 entity: operation,
99 expected: "IFCCOORDINATEOPERATION",
100 actual: actual.to_owned(),
101 });
102 }
103 operation_source(view.model, Some(view), operation, None)
104}
105
106pub fn coordinate_operation_for(
119 view: &GeorefView,
120 source: EntityId,
121) -> GeorefResult<Option<EntityId>> {
122 let model = view.model;
123 if model.get(source).is_none() {
124 return Err(GeorefError::MissingEntity {
125 referrer: source,
126 missing: source,
127 });
128 }
129 classify(model, Some(view), source)?;
130 let operations = operations_from(model, Some(view), source, None)?;
131 match operations.as_slice() {
132 [] => Ok(None),
133 [one] => {
134 forbid_sub_context(model, source)?;
135 Ok(Some(*one))
136 }
137 _ => Err(GeorefError::RuleViolation {
138 entity: source,
139 rule: HAS_COORDINATE_OPERATION,
140 }),
141 }
142}
143
144pub(crate) fn operation_source(
147 model: &Model,
148 view: Option<&GeorefView>,
149 operation: EntityId,
150 damage: Option<&Damage>,
151) -> GeorefResult<OperationSource> {
152 let entity = model.get(operation).ok_or(GeorefError::MissingEntity {
153 referrer: operation,
154 missing: operation,
155 })?;
156 let source = match entity.attribute(slot::SOURCE_CRS) {
157 None | Some(Value::Null) => {
158 return Err(GeorefError::MissingAttribute {
159 entity: operation,
160 index: slot::SOURCE_CRS,
161 name: "SourceCRS",
162 })
163 }
164 Some(value) => value.as_ref_id().ok_or(GeorefError::InvalidAttribute {
165 entity: operation,
166 index: slot::SOURCE_CRS,
167 name: "SourceCRS",
168 })?,
169 };
170 if model.get(source).is_none() {
171 return Err(GeorefError::MissingEntity {
172 referrer: operation,
173 missing: source,
174 });
175 }
176 let classified = classify(model, view, source)?;
177 forbid_sub_context(model, source)?;
178 if operations_from(model, view, source, damage)?.len() > 1 {
179 return Err(GeorefError::RuleViolation {
180 entity: source,
181 rule: HAS_COORDINATE_OPERATION,
182 });
183 }
184 Ok(classified)
185}
186
187fn classify(
189 model: &Model,
190 view: Option<&GeorefView>,
191 id: EntityId,
192) -> GeorefResult<OperationSource> {
193 let entity = model.get(id).ok_or(GeorefError::MissingEntity {
194 referrer: id,
195 missing: id,
196 })?;
197 let type_name = entity.type_name.as_ref();
198 let (is_context, is_crs) = match view {
199 Some(view) => {
200 let declared = view.require_known_type(id)?;
201 (
202 view.schema
203 .is_a(declared, "IfcGeometricRepresentationContext"),
204 view.schema.is_a(declared, "IfcCoordinateReferenceSystem"),
205 )
206 }
207 None => (
208 entity.is_type("IFCGEOMETRICREPRESENTATIONCONTEXT")
209 || entity.is_type("IFCGEOMETRICREPRESENTATIONSUBCONTEXT"),
210 UNPINNED_CRS.iter().any(|crs| entity.is_type(crs)),
211 ),
212 };
213 if is_context {
214 Ok(OperationSource::Context(id))
215 } else if is_crs {
216 Ok(OperationSource::CoordinateReferenceSystem(id))
217 } else {
218 Err(GeorefError::WrongType {
219 entity: id,
220 expected: "IFCCOORDINATEREFERENCESYSTEM or IFCGEOMETRICREPRESENTATIONCONTEXT",
221 actual: type_name.to_owned(),
222 })
223 }
224}
225
226fn forbid_sub_context(model: &Model, source: EntityId) -> GeorefResult<()> {
228 match model.get(source) {
229 Some(entity) if entity.is_type("IFCGEOMETRICREPRESENTATIONSUBCONTEXT") => {
230 Err(GeorefError::RuleViolation {
231 entity: source,
232 rule: "NoCoordOperation",
233 })
234 }
235 _ => Ok(()),
236 }
237}
238
239fn operations_from(
245 model: &Model,
246 view: Option<&GeorefView>,
247 source: EntityId,
248 damage: Option<&Damage>,
249) -> GeorefResult<Vec<EntityId>> {
250 let types: Vec<&str> = match view {
251 Some(view) => view.schema.subtypes("IfcCoordinateOperation"),
252 None => UNPINNED_OPERATIONS.to_vec(),
253 };
254 let mut found = Vec::new();
255 for (id, operation) in types
256 .into_iter()
257 .flat_map(|type_name| model.of_type(type_name))
258 {
259 if let Some(damage) = damage {
260 damage.check(id)?;
261 }
262 if operation.reference(slot::SOURCE_CRS) == Some(source) {
263 found.push(id);
264 }
265 }
266 found.sort_unstable();
267 found.dedup();
268 Ok(found)
269}