1use ifc_model::value::Value;
20use ifc_model::EntityId;
21use ifc_schema::SchemaVersion;
22
23use crate::error::{GeorefError, GeorefResult};
24
25#[non_exhaustive]
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct CompoundPlaneAngle {
30 pub degrees: i64,
32 pub minutes: i64,
34 pub seconds: i64,
36 pub millionths: Option<i64>,
38}
39
40impl CompoundPlaneAngle {
41 #[must_use]
47 pub fn decimal_degrees(&self) -> f64 {
48 self.degrees as f64
49 + self.minutes as f64 / 60.0
50 + self.seconds as f64 / 3600.0
51 + self.millionths.unwrap_or(0) as f64 / 3_600_000_000.0
52 }
53}
54
55#[derive(Debug, Clone, Copy)]
57pub(crate) enum Axis {
58 Latitude,
59 Longitude,
60}
61
62impl Axis {
63 const fn name(self) -> &'static str {
64 match self {
65 Self::Latitude => "RefLatitude",
66 Self::Longitude => "RefLongitude",
67 }
68 }
69}
70
71pub(crate) fn read_angle(
73 value: Option<&Value>,
74 entity: EntityId,
75 index: usize,
76 axis: Axis,
77 version: SchemaVersion,
78) -> GeorefResult<Option<CompoundPlaneAngle>> {
79 let name = axis.name();
80 let invalid = GeorefError::InvalidAttribute {
81 entity,
82 index,
83 name,
84 };
85 let items = match value.map(Value::unwrap_typed) {
86 None | Some(Value::Null) => return Ok(None),
87 Some(Value::List(items)) => items,
88 Some(_) => return Err(invalid),
89 };
90 if !(3..=4).contains(&items.len()) {
92 return Err(invalid);
93 }
94 let mut parts = [0_i64; 4];
95 for (slot, item) in parts.iter_mut().zip(items) {
96 *slot = item.unwrap_typed().as_i64().ok_or(invalid.clone())?;
97 }
98 let angle = CompoundPlaneAngle {
99 degrees: parts[0],
100 minutes: parts[1],
101 seconds: parts[2],
102 millionths: (items.len() == 4).then_some(parts[3]),
103 };
104 let violation = |rule| GeorefError::InvalidCompoundAngle {
105 entity,
106 index,
107 name,
108 rule,
109 };
110 if let Some(rule) = broken_rule(&angle, version) {
111 return Err(violation(rule));
112 }
113 let degrees = angle.decimal_degrees();
114 let (limit, rule) = match axis {
115 Axis::Latitude => (90.0, "WGS84 latitude range [-90, 90]"),
116 Axis::Longitude => (180.0, "WGS84 longitude range [-180, 180]"),
117 };
118 if degrees.abs() > limit {
119 return Err(violation(rule));
120 }
121 Ok(Some(angle))
122}
123
124fn broken_rule(angle: &CompoundPlaneAngle, version: SchemaVersion) -> Option<&'static str> {
126 let CompoundPlaneAngle {
127 degrees: d,
128 minutes: m,
129 seconds: s,
130 millionths: u,
131 } = *angle;
132 if version == SchemaVersion::Ifc2x3 {
133 let same_sign = (d >= 0 && m >= 0 && s >= 0) || (d <= 0 && m <= 0 && s <= 0);
134 return if !(-360..360).contains(&d) {
135 Some("WR1")
136 } else if !(-60..60).contains(&m) {
137 Some("WR2")
138 } else if !(-60..60).contains(&s) {
139 Some("WR3")
140 } else if !same_sign {
141 Some("WR4")
142 } else {
143 None
144 };
145 }
146 let u_all = u.unwrap_or(0);
147 let same_sign =
148 (d >= 0 && m >= 0 && s >= 0 && u_all >= 0) || (d <= 0 && m <= 0 && s <= 0 && u_all <= 0);
149 if m.unsigned_abs() >= 60 {
150 Some("MinutesInRange")
151 } else if s.unsigned_abs() >= 60 {
152 Some("SecondsInRange")
153 } else if u.is_some_and(|u| u.unsigned_abs() >= 1_000_000) {
154 Some("MicrosecondsInRange")
155 } else if !same_sign {
156 Some("ConsistentSign")
157 } else {
158 None
159 }
160}
161
162#[cfg(test)]
163mod tests {
164 use super::*;
165
166 fn list(parts: &[i64]) -> Value {
167 Value::List(parts.iter().map(|p| Value::Integer(*p)).collect())
168 }
169
170 fn read(parts: &[i64], axis: Axis, version: SchemaVersion) -> GeorefResult<f64> {
171 read_angle(Some(&list(parts)), EntityId(1), 9, axis, version)
172 .map(|a| a.expect("present").decimal_degrees())
173 }
174
175 fn rule_of(result: GeorefResult<f64>) -> &'static str {
176 match result {
177 Err(GeorefError::InvalidCompoundAngle { rule, .. }) => rule,
178 other => panic!("expected a compound-angle violation, got {other:?}"),
179 }
180 }
181
182 #[test]
183 fn converts_degrees_minutes_seconds_and_millionths() {
184 let v = read(&[41, 53, 30, 500_000], Axis::Latitude, SchemaVersion::Ifc4).unwrap();
185 assert!((v - (41.0 + 53.0 / 60.0 + 30.5 / 3600.0)).abs() < 1e-12);
186 let w = read(&[-87, -35, -40], Axis::Longitude, SchemaVersion::Ifc4x3).unwrap();
187 assert!((w + (87.0 + 35.0 / 60.0 + 40.0 / 3600.0)).abs() < 1e-12);
188 }
189
190 #[test]
191 fn ifc4_and_ifc4x3_rules_are_named() {
192 for version in [SchemaVersion::Ifc4, SchemaVersion::Ifc4x3] {
193 let lat = Axis::Latitude;
194 assert_eq!(rule_of(read(&[1, 60, 0], lat, version)), "MinutesInRange");
195 assert_eq!(rule_of(read(&[1, 0, -60], lat, version)), "SecondsInRange");
196 assert_eq!(
197 rule_of(read(&[1, 0, 0, 1_000_000], lat, version)),
198 "MicrosecondsInRange"
199 );
200 assert_eq!(rule_of(read(&[1, -2, 0], lat, version)), "ConsistentSign");
201 assert_eq!(
202 rule_of(read(&[-1, 0, 0, 5], lat, version)),
203 "ConsistentSign"
204 );
205 }
206 }
207
208 #[test]
209 fn ifc2x3_rules_are_its_own() {
210 let v = SchemaVersion::Ifc2x3;
211 let lon = Axis::Longitude;
212 assert_eq!(rule_of(read(&[360, 0, 0], lon, v)), "WR1");
213 assert_eq!(rule_of(read(&[1, 60, 0], lon, v)), "WR2");
214 assert_eq!(rule_of(read(&[1, 0, 60], lon, v)), "WR3");
215 assert_eq!(rule_of(read(&[1, -1, 0], lon, v)), "WR4");
216 assert!(read(&[-1, 0, 0, 5], lon, v).is_ok());
219 assert!(read(&[1, 0, 0, 2_000_000], lon, v).is_ok());
220 assert_eq!(
221 rule_of(read(&[1, 0, 0, 2_000_000], lon, SchemaVersion::Ifc4)),
222 "MicrosecondsInRange"
223 );
224 }
225
226 #[test]
227 fn wgs84_ranges_are_enforced_per_axis() {
228 let v = SchemaVersion::Ifc4;
229 assert!(read(&[90, 0, 0], Axis::Latitude, v).is_ok());
230 assert_eq!(
231 rule_of(read(&[90, 0, 1], Axis::Latitude, v)),
232 "WGS84 latitude range [-90, 90]"
233 );
234 assert!(read(&[-180, 0, 0], Axis::Longitude, v).is_ok());
235 assert_eq!(
236 rule_of(read(&[181, 0, 0], Axis::Longitude, v)),
237 "WGS84 longitude range [-180, 180]"
238 );
239 }
240
241 #[test]
242 fn malformed_lists_are_invalid_attributes() {
243 for value in [
244 list(&[1, 2]),
245 list(&[1, 2, 3, 4, 5]),
246 Value::List(vec![Value::Integer(1), Value::Real(2.5), Value::Integer(0)]),
247 Value::Real(41.5),
248 ] {
249 assert!(matches!(
250 read_angle(
251 Some(&value),
252 EntityId(1),
253 9,
254 Axis::Latitude,
255 SchemaVersion::Ifc4
256 ),
257 Err(GeorefError::InvalidAttribute {
258 index: 9,
259 name: "RefLatitude",
260 ..
261 })
262 ));
263 }
264 assert_eq!(
265 read_angle(
266 Some(&Value::Null),
267 EntityId(1),
268 9,
269 Axis::Latitude,
270 SchemaVersion::Ifc4
271 ),
272 Ok(None)
273 );
274 }
275}