ifc_geometry/lower/tessellated/
texture.rs1use axiolid_mesh::{AttributeChannel, Blend};
28use ifc_model::{EntityId, Value};
29
30use crate::error::{GeometryError, GeometryResult};
31use crate::lower::session::LoweringSession;
32
33pub const UV_CHANNEL: &str = "uv";
38
39const TYPE: &str = "IFCINDEXEDTRIANGLETEXTUREMAP";
40const TEX_COORDS: usize = 2;
41const TEX_COORD_INDEX: usize = 3;
42
43pub(super) fn channels(
45 session: &mut LoweringSession<'_>,
46 face_set: EntityId,
47 triangle_count: usize,
48) -> GeometryResult<Vec<AttributeChannel>> {
49 let maps = session.triangle_texture_maps(face_set).to_vec();
50 let mut out = Vec::with_capacity(maps.len());
51 for map in maps {
52 if let Some(values) = channel(session, face_set, map, triangle_count)? {
53 let name = match out.len() {
54 0 => UV_CHANNEL.to_string(),
55 n => format!("{UV_CHANNEL}{n}"),
56 };
57 out.push(AttributeChannel::corner_indexed(
58 name,
59 values.0,
60 2,
61 Blend::Linear,
62 values.1,
63 ));
64 }
65 }
66 Ok(out)
67}
68
69fn channel(
72 session: &mut LoweringSession<'_>,
73 face_set: EntityId,
74 map: EntityId,
75 triangle_count: usize,
76) -> GeometryResult<Option<(Vec<f64>, Vec<u32>)>> {
77 let entity = session.entity(face_set, map)?;
78 let index = match entity.attributes.get(TEX_COORD_INDEX) {
79 None | Some(Value::Null) => return Ok(None),
80 Some(value) => triangles(map, value)?,
81 };
82 if index.len() > triangle_count {
83 return Err(invalid(
84 map,
85 "TexCoordIndex",
86 format!(
87 "maps {} triangles, but the face set has {triangle_count}",
88 index.len()
89 ),
90 ));
91 }
92 let list = entity
93 .attributes
94 .get(TEX_COORDS)
95 .and_then(Value::as_ref_id)
96 .ok_or_else(|| missing(map, TYPE, "TexCoords"))?;
97 let values = texture_vertices(session, map, list)?;
98 let pool = values.len() / 2;
99
100 let mut corners = Vec::with_capacity(triangle_count * 3);
101 for triangle in &index {
102 for &raw in triangle {
103 let slot = usize::try_from(raw)
105 .ok()
106 .filter(|&s| (1..=pool).contains(&s));
107 let Some(slot) = slot else {
108 return Err(invalid(
109 map,
110 "TexCoordIndex",
111 format!("holds {raw}; TexCoordsList has {pool} entries (1-based)"),
112 ));
113 };
114 corners.push((slot - 1) as u32);
115 }
116 }
117 corners.resize(triangle_count * 3, AttributeChannel::UNMAPPED);
118 Ok(Some((values, corners)))
119}
120
121fn triangles(map: EntityId, value: &Value) -> GeometryResult<Vec<[i64; 3]>> {
123 let rows = value
124 .unwrap_typed()
125 .as_list()
126 .ok_or_else(|| invalid(map, "TexCoordIndex", "is not a list".to_string()))?;
127 rows.iter()
128 .map(|row| {
129 let row = row.unwrap_typed().as_list();
130 let ints: Option<Vec<i64>> = row.map(|r| {
131 r.iter()
132 .map(|v| v.unwrap_typed().as_i64())
133 .collect::<Option<Vec<_>>>()
134 })?;
135 match ints.as_deref() {
136 Some(&[a, b, c]) => Some([a, b, c]),
137 _ => None,
138 }
139 })
140 .collect::<Option<Vec<_>>>()
141 .ok_or_else(|| {
142 invalid(
143 map,
144 "TexCoordIndex",
145 "every entry must be exactly three integers".to_string(),
146 )
147 })
148}
149
150fn texture_vertices(
152 session: &mut LoweringSession<'_>,
153 map: EntityId,
154 list: EntityId,
155) -> GeometryResult<Vec<f64>> {
156 let entity = session.entity(map, list)?;
157 let rows = entity
158 .attributes
159 .first()
160 .and_then(|v| v.unwrap_typed().as_list())
161 .ok_or_else(|| missing(list, "IFCTEXTUREVERTEXLIST", "TexCoordsList"))?;
162 let mut out = Vec::with_capacity(rows.len() * 2);
163 for row in rows {
164 let pair = row.unwrap_typed().as_list().and_then(|p| match p {
165 [s, t] => Some([s.unwrap_typed().as_f64()?, t.unwrap_typed().as_f64()?]),
166 _ => None,
167 });
168 let Some([s, t]) = pair else {
169 return Err(GeometryError::Degenerate {
170 entity: list,
171 type_name: "IFCTEXTUREVERTEXLIST".to_string(),
172 detail: "TexCoordsList entries must be (s, t) pairs of numbers".to_string(),
173 });
174 };
175 out.extend([s, t]);
176 }
177 Ok(out)
178}
179
180fn invalid(map: EntityId, attribute: &str, detail: String) -> GeometryError {
181 GeometryError::Degenerate {
182 entity: map,
183 type_name: TYPE.to_string(),
184 detail: format!("{attribute} {detail}"),
185 }
186}
187
188fn missing(entity: EntityId, type_name: &str, attribute: &'static str) -> GeometryError {
189 GeometryError::MissingAttribute {
190 entity,
191 type_name: type_name.to_string(),
192 attribute,
193 }
194}
195
196#[cfg(test)]
197mod tests;