1use ifc_model::guid::Guid;
19use ifc_model::{Edit, Entity, EntityId, Model, Transaction, Value};
20use ifc_schema::TypeKind;
21
22use crate::error::GeometryError;
23
24use super::release::bind;
25use super::{invalid, refs};
26
27const ENTITY: &str = "IFCGRID";
28
29pub fn grid(
49 tx: &mut Transaction,
50 global_id: &str,
51 placement: Option<EntityId>,
52 axes: (&[EntityId], &[EntityId], &[EntityId]),
53 predefined_type: Option<&str>,
54) -> Result<EntityId, GeometryError> {
55 check(global_id, axes)?;
56 let (u_axes, v_axes, w_axes) = axes;
57 let mut attrs = vec![Value::Null; 11];
58 attrs[0] = Value::Text(global_id.into());
59 attrs[5] = placement.map_or(Value::Null, Value::Ref);
60 attrs[7] = refs(u_axes);
61 attrs[8] = refs(v_axes);
62 if !w_axes.is_empty() {
63 attrs[9] = refs(w_axes);
64 }
65 attrs[10] = predefined_type.map_or(Value::Null, |t| Value::Enum(t.into()));
66 Ok(tx.create(Entity::new(ENTITY, attrs)))
67}
68
69pub fn grid_with_owner_history(
88 tx: &mut Transaction,
89 model: &Model,
90 global_id: &str,
91 placement: Option<EntityId>,
92 axes: (&[EntityId], &[EntityId], &[EntityId]),
93 predefined_type: Option<&str>,
94 owner_history: EntityId,
95) -> Result<EntityId, GeometryError> {
96 let release = bind(model, ENTITY)?;
97 check(global_id, axes)?;
98 let (schema, version) = (release.schema(), release.version());
99 let declared = schema.attributes(ENTITY);
100 if let Some(token) = predefined_type {
101 let predefined = declared
102 .iter()
103 .find(|attribute| attribute.name.eq_ignore_ascii_case("PredefinedType"))
104 .ok_or_else(|| {
105 invalid(
106 ENTITY,
107 "PredefinedType",
108 format!("{version:?} declares no such attribute"),
109 )
110 })?;
111 let members = match schema.type_def(&predefined.type_name).map(|t| &t.kind) {
112 Some(TypeKind::Enumeration(members)) => members.as_slice(),
113 _ => &[],
114 };
115 if !members.iter().any(|member| member == token) {
116 return Err(invalid(
117 ENTITY,
118 "PredefinedType",
119 format!("{token} is not a {} token", predefined.type_name),
120 ));
121 }
122 }
123 require_owner_history(tx, model, owner_history)?;
124
125 let (u_axes, v_axes, w_axes) = axes;
126 let w_axes = if w_axes.is_empty() {
127 Value::Null
128 } else {
129 refs(w_axes)
130 };
131 let values = [
132 ("GlobalId", Value::Text(global_id.into())),
133 ("OwnerHistory", Value::Ref(owner_history)),
134 ("ObjectPlacement", placement.map_or(Value::Null, Value::Ref)),
135 ("UAxes", refs(u_axes)),
136 ("VAxes", refs(v_axes)),
137 ("WAxes", w_axes),
138 (
139 "PredefinedType",
140 predefined_type.map_or(Value::Null, |t| Value::Enum(t.into())),
141 ),
142 ];
143 let mut attrs = vec![Value::Null; declared.len()];
144 for (attribute, value) in values {
145 match declared
146 .iter()
147 .position(|found| found.name.eq_ignore_ascii_case(attribute))
148 {
149 Some(slot) => attrs[slot] = value,
150 None if value == Value::Null => {}
151 None => {
152 return Err(invalid(
153 ENTITY,
154 attribute,
155 format!("{version:?} declares no such attribute"),
156 ))
157 }
158 }
159 }
160 release.require(ENTITY, &attrs)?;
161 Ok(tx.create(Entity::new(ENTITY, attrs)))
162}
163
164fn check(
166 global_id: &str,
167 (u_axes, v_axes, w_axes): (&[EntityId], &[EntityId], &[EntityId]),
168) -> Result<(), GeometryError> {
169 if Guid::parse(global_id).is_none() {
170 return Err(invalid(ENTITY, "GlobalId", global_id));
171 }
172 for (values, attribute) in [(u_axes, "UAxes"), (v_axes, "VAxes")] {
173 if values.is_empty() {
174 return Err(invalid(
175 ENTITY,
176 attribute,
177 "expected at least one axis, per LIST [1:?]",
178 ));
179 }
180 }
181 for (values, attribute) in [(u_axes, "UAxes"), (v_axes, "VAxes"), (w_axes, "WAxes")] {
182 let mut seen = std::collections::HashSet::new();
183 if let Some(repeat) = values.iter().find(|axis| !seen.insert(**axis)) {
184 return Err(invalid(
185 ENTITY,
186 attribute,
187 format!("axis {repeat:?} appears twice in a UNIQUE list"),
188 ));
189 }
190 }
191 Ok(())
192}
193
194fn require_owner_history(
196 tx: &Transaction,
197 model: &Model,
198 id: EntityId,
199) -> Result<(), GeometryError> {
200 let mut found = model.get(id).map(|entity| entity.type_name.to_string());
201 for edit in tx.edits() {
202 match edit {
203 Edit::Create { id: target, entity } if *target == id => {
204 found = Some(entity.type_name.to_string());
205 }
206 Edit::Retype {
207 id: target,
208 type_name,
209 } if *target == id => found = Some(type_name.to_string()),
210 Edit::Remove { id: target } if *target == id => found = None,
211 _ => {}
212 }
213 }
214 match found {
215 Some(found) if found.eq_ignore_ascii_case("IFCOWNERHISTORY") => Ok(()),
216 Some(found) => Err(invalid(
217 ENTITY,
218 "OwnerHistory",
219 format!("#{} is a {found}, not an IfcOwnerHistory", id.0),
220 )),
221 None => Err(invalid(
222 ENTITY,
223 "OwnerHistory",
224 format!("#{} does not resolve", id.0),
225 )),
226 }
227}