1#![cfg(feature = "cityjson")]
23
24mod attributes;
25mod footprint;
26mod geometry;
27mod georef;
28mod structure;
29mod vertices;
30
31#[cfg(test)]
32#[path = "../cityjson_tests.rs"]
33mod tests;
34#[cfg(test)]
35#[path = "../cityjson_fixture_tests.rs"]
36mod fixture_tests;
37
38use std::collections::{HashMap, HashSet};
39
40use ifc_lite_core::IfcType;
41use ifc_lite_processing::MeshData;
42use serde_json::{json, Map, Value};
43
44use crate::model::{build_export_model_with_options, EntityRow, ModelOptions};
45use crate::scene_input::gather;
46use geometry::Geometry;
47use structure::{Kind, Node};
48use vertices::VertexPool;
49
50#[derive(Debug, Clone)]
52#[non_exhaustive]
53pub struct CityJsonOptions {
54 pub scale: f64,
57 pub element_geometry: bool,
61 pub sequence: bool,
64}
65
66impl Default for CityJsonOptions {
67 fn default() -> Self {
68 Self { scale: 0.001, element_geometry: true, sequence: false }
69 }
70}
71
72#[derive(Debug, Clone)]
74pub struct CityJsonExport {
75 pub text: String,
77 pub reference_system: Option<String>,
79 pub warnings: Vec<String>,
81 pub buildings: usize,
82 pub city_objects: usize,
83 pub vertices: usize,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct CityJsonRefusal {
91 pub reason: String,
92}
93
94impl CityJsonRefusal {
95 pub const CODE: &'static str = "CITYJSON_REFUSED";
97}
98
99impl std::fmt::Display for CityJsonRefusal {
100 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101 write!(f, "{}: {}", Self::CODE, self.reason)
102 }
103}
104
105pub fn try_export_cityjson(content: &[u8], opts: &CityJsonOptions) -> Result<CityJsonExport, CityJsonRefusal> {
107 if !(opts.scale.is_finite() && opts.scale > 0.0 && opts.scale <= 1.0) {
108 return Err(CityJsonRefusal { reason: format!("scale {} is not in (0, 1]", opts.scale) });
109 }
110 let rels = crate::relationships::relationships(content);
111 let model = build_export_model_with_options(content, &ModelOptions::default().with_attributes(true).with_inherit_type_properties(true));
112 let rows: HashMap<u32, &EntityRow> = model.entities.iter().map(|r| (r.express_id, r)).collect();
113 let type_of: HashMap<u32, IfcType> = model.entities.iter().map(|r| (r.express_id, IfcType::from_str(&r.ifc_type))).collect();
114 let tree = structure::walk(rels.project, &rels.spatial_children, &type_of);
115 let buildings = tree.nodes.iter().filter(|n| n.kind == Kind::Building).count();
116 if buildings == 0 {
117 return Err(CityJsonRefusal { reason: "the model has no IfcBuilding in its spatial structure; CityJSON export writes buildings".into() });
118 }
119 let mut warnings = Vec::new();
120 if tree.outside_buildings > 0 {
121 warnings.push(format!("{} elements outside every IfcBuilding (site elements) are not exported", tree.outside_buildings));
122 }
123 let frame = georef::resolve(content, &mut warnings);
124 let to_out = |p: [f64; 3]| frame.apply(p);
125
126 let scene = gather(content, false, false, None);
127 let world = scene.result.frame.world_mapper();
128 let mut meshes: HashMap<u32, Vec<&MeshData>> = HashMap::new();
129 for m in scene.emittable() {
130 meshes.entry(m.express_id).or_default().push(m);
131 }
132
133 let ids = object_ids(&tree.nodes, &rows);
134 let site_of = site_rows(&rels.spatial_children, &rows, &tree.nodes);
135 let mut pool = VertexPool::new(opts.scale);
136 let mut objects: Vec<CityObject> = Vec::with_capacity(tree.nodes.len());
137 for node in &tree.nodes {
138 let mut geoms: Vec<Geometry> = Vec::new();
139 let mut measured_height = None;
140 if matches!(node.kind, Kind::Building | Kind::BuildingPart) {
141 let shaping: Vec<&MeshData> = tree.nodes.iter()
142 .filter(|n| n.kind.shapes_building() && n.containers.contains(&node.id))
143 .flat_map(|n| meshes.get(&n.id).into_iter().flatten().copied())
144 .collect();
145 let name = &ids[&node.id];
146 match footprint::footprint(&shaping, world, opts.scale / 2.0) {
147 Some(fp) => {
148 if fp.approximated > 0 {
149 warnings.push(format!("{name}: {} elements too dense to outline exactly were outlined by their convex hull", fp.approximated));
150 }
151 let grid = |z: f64| (to_out([0.0, 0.0, z])[2] / opts.scale).round();
153 measured_height = Some((grid(fp.z_max) - grid(fp.z_min)) * opts.scale);
154 let min_area2 = opts.scale * opts.scale;
155 let mut dropped = 0;
156 geoms.extend(geometry::lod0(&fp, &mut pool, &to_out, min_area2, &mut dropped));
157 let mut dropped_lod1 = 0;
159 match geometry::lod1(&fp, &mut pool, &to_out, min_area2, &mut dropped_lod1) {
160 Some(g) => geoms.push(g),
161 None => warnings.push(format!("{name}: the LoD1 block has no height at the export scale and is omitted")),
162 }
163 if dropped > 0 {
164 warnings.push(format!(
165 "{name}: {dropped} footprint rings could not be written as valid polygon rings (an island inside a hole, a hole outside every exterior, or a sliver that is collinear on the export grid) and are missing from LoD0 and LoD1"
166 ));
167 }
168 }
169 None => warnings.push(format!("{name}: no element geometry to derive a footprint from; written without geometry")),
170 }
171 } else if opts.element_geometry && node.kind != Kind::Storey {
172 if let Some(ms) = meshes.get(&node.id) {
173 geoms.extend(geometry::lod3_surfaces(ms, &world, &mut pool, &to_out));
174 }
175 }
176 let row = rows.get(&node.id).copied();
177 let ifc_class = type_of.get(&node.id).map(|t| t.name().to_string()).unwrap_or_default();
178 let vertical = |m: f64| frame.vertical_length(m);
179 let (attrs, conflicts) = attributes::attributes(&attributes::AttributeInput {
180 kind: node.kind,
181 row,
182 ifc_class: &ifc_class,
183 storey: node.storey.and_then(|s| ids.get(&s)).map(String::as_str),
184 site: node.containers.last().or(Some(&node.id)).and_then(|b| site_of.get(b)).copied(),
185 measured_height,
186 length_metres: model.units.length_unit_scale,
187 vertical: &vertical,
188 });
189 if !conflicts.is_empty() {
190 warnings.push(format!(
191 "{}: property sets of the same name were merged and these properties had conflicting values; the first value in model order is kept: {}",
192 ids[&node.id],
193 conflicts.join(", ")
194 ));
195 }
196 objects.push(CityObject { node: node.clone(), geoms, attrs });
197 }
198
199 let mut used = vec![false; pool.len()];
200 for g in objects.iter().flat_map(|o| &o.geoms) {
201 for &i in &g.used {
202 used[i as usize] = true;
203 }
204 }
205 let remap = pool.compact(&used);
206 for g in objects.iter_mut().flat_map(|o| &mut o.geoms) {
207 g.used.iter_mut().for_each(|i| *i = remap[*i as usize]);
208 if let Some(b) = g.value.get_mut("boundaries") {
209 remap_indices(b, &|i| u64::from(remap[i as usize]));
210 }
211 }
212
213 let mut doc = Document { ids: &ids, objects, pool, frame: &frame, opts };
214 let title = rels.project.and_then(|p| crate::ifc5::decode_one(content, p))
215 .and_then(|e| e.string_at(ifc_lite_core::slot::IfcProject::NAME).map(str::to_string))
216 .filter(|s| !s.trim().is_empty());
217 let text = if opts.sequence { doc.sequence(title.as_deref()) } else { doc.document(title.as_deref()) }
218 .map_err(|e| CityJsonRefusal { reason: format!("serialization failed: {e}") })?;
219 Ok(CityJsonExport {
220 text,
221 reference_system: frame.reference_system(),
222 warnings,
223 buildings,
224 city_objects: doc.objects.len(),
225 vertices: doc.pool.len(),
226 })
227}
228
229struct CityObject {
230 node: Node,
231 geoms: Vec<Geometry>,
232 attrs: Map<String, Value>,
233}
234
235fn object_ids(nodes: &[Node], rows: &HashMap<u32, &EntityRow>) -> HashMap<u32, String> {
238 let gid = |id: u32| rows.get(&id).and_then(|r| r.global_id.as_deref()).filter(|g| !g.is_empty());
239 let mut count: HashMap<&str, usize> = HashMap::new();
240 for n in nodes {
241 if let Some(g) = gid(n.id) {
242 *count.entry(g).or_default() += 1;
243 }
244 }
245 nodes.iter().map(|n| {
246 let id = match gid(n.id) {
247 Some(g) if count[g] == 1 && !g.starts_with("ifc-") => g.to_string(),
248 _ => format!("ifc-{}", n.id),
249 };
250 (n.id, id)
251 }).collect()
252}
253
254fn site_rows<'a>(children: &HashMap<u32, Vec<u32>>, rows: &HashMap<u32, &'a EntityRow>, nodes: &[Node]) -> HashMap<u32, &'a EntityRow> {
256 let buildings: HashSet<u32> = nodes.iter().filter(|n| n.kind == Kind::Building).map(|n| n.id).collect();
257 let mut out = HashMap::new();
258 for (parent, kids) in children {
259 let Some(row) = rows.get(parent).filter(|r| IfcType::from_str(&r.ifc_type).is_subtype_of(IfcType::IfcSite)) else { continue };
260 for kid in kids.iter().filter(|k| buildings.contains(k)) {
261 out.insert(*kid, *row);
262 }
263 }
264 out
265}
266
267struct Document<'a> {
268 ids: &'a HashMap<u32, String>,
269 objects: Vec<CityObject>,
270 pool: VertexPool,
271 frame: &'a georef::OutputFrame,
272 opts: &'a CityJsonOptions,
273}
274
275impl Document<'_> {
276 fn transform(&self) -> Value {
277 let s = self.opts.scale;
278 json!({ "scale": [s, s, s], "translate": self.pool.translate() })
279 }
280
281 fn metadata(&self, title: Option<&str>) -> Value {
282 let mut m = Map::new();
283 if let Some(e) = self.pool.extent(0..self.pool.len() as u32) {
284 m.insert("geographicalExtent".into(), json!(e));
285 }
286 if let Some(crs) = self.frame.reference_system() {
287 m.insert("referenceSystem".into(), json!(crs));
288 }
289 if let Some(t) = title {
290 m.insert("title".into(), json!(t));
291 }
292 Value::Object(m)
293 }
294
295 fn city_objects(&self, members: &[usize], remap: &impl Fn(u32) -> u64) -> Map<String, Value> {
298 let index: HashSet<u32> = members.iter().map(|&i| self.objects[i].node.id).collect();
299 let mut children: HashMap<u32, Vec<&str>> = HashMap::new();
300 for &i in members {
301 let n = &self.objects[i].node;
302 if let Some(p) = n.parent.filter(|p| index.contains(p)) {
303 children.entry(p).or_default().push(&self.ids[&n.id]);
304 }
305 }
306 let mut out = Map::new();
307 for &i in members {
308 let o = &self.objects[i];
309 let mut co = Map::new();
310 co.insert("type".into(), json!(o.node.kind.city_type()));
311 co.insert("attributes".into(), Value::Object(o.attrs.clone()));
312 if let Some(p) = o.node.parent {
313 co.insert("parents".into(), json!([self.ids[&p]]));
314 }
315 if let Some(kids) = children.get(&o.node.id) {
316 co.insert("children".into(), json!(kids));
317 }
318 if !o.geoms.is_empty() {
319 if let Some(e) = self.pool.extent(o.geoms.iter().flat_map(|g| g.used.iter().copied())) {
320 co.insert("geographicalExtent".into(), json!(e));
321 }
322 let geoms: Vec<Value> = o.geoms.iter().map(|g| {
323 let mut v = g.value.clone();
324 if let Some(b) = v.get_mut("boundaries") {
325 remap_indices(b, remap);
326 }
327 v
328 }).collect();
329 co.insert("geometry".into(), Value::Array(geoms));
330 }
331 out.insert(self.ids[&o.node.id].clone(), Value::Object(co));
332 }
333 out
334 }
335
336 fn document(&mut self, title: Option<&str>) -> serde_json::Result<String> {
337 let all: Vec<usize> = (0..self.objects.len()).collect();
338 let doc = json!({
339 "type": "CityJSON",
340 "version": "2.0",
341 "transform": self.transform(),
342 "metadata": self.metadata(title),
343 "CityObjects": self.city_objects(&all, &|i| u64::from(i)),
344 "vertices": self.pool.integers(),
345 });
346 serde_json::to_string(&doc)
347 }
348
349 fn sequence(&mut self, title: Option<&str>) -> serde_json::Result<String> {
353 let header = json!({
354 "type": "CityJSON",
355 "version": "2.0",
356 "transform": self.transform(),
357 "metadata": self.metadata(title),
358 "CityObjects": {},
359 "vertices": [],
360 });
361 let mut out = serde_json::to_string(&header)?;
362 out.push('\n');
363 let integers = self.pool.integers();
364 for (bi, b) in self.objects.iter().enumerate().filter(|(_, o)| o.node.kind == Kind::Building) {
365 let members: Vec<usize> = std::iter::once(bi)
366 .chain(self.objects.iter().enumerate().filter(|(_, o)| o.node.containers.last() == Some(&b.node.id)).map(|(i, _)| i))
367 .collect();
368 let mut used: Vec<u32> = members.iter().flat_map(|&i| self.objects[i].geoms.iter().flat_map(|g| g.used.iter().copied())).collect();
369 used.sort_unstable();
370 used.dedup();
371 let local: HashMap<u32, u64> = used.iter().enumerate().map(|(k, &g)| (g, k as u64)).collect();
372 let feature = json!({
373 "type": "CityJSONFeature",
374 "id": self.ids[&b.node.id],
375 "CityObjects": self.city_objects(&members, &|g| local[&g]),
376 "vertices": used.iter().map(|&g| integers[g as usize]).collect::<Vec<_>>(),
377 });
378 out.push_str(&serde_json::to_string(&feature)?);
379 out.push('\n');
380 }
381 Ok(out)
382 }
383}
384
385fn remap_indices(v: &mut Value, remap: &impl Fn(u32) -> u64) {
387 match v {
388 Value::Array(items) => items.iter_mut().for_each(|i| remap_indices(i, remap)),
389 Value::Number(n) => {
390 if let Some(i) = n.as_u64().and_then(|i| u32::try_from(i).ok()) {
391 *v = json!(remap(i));
392 }
393 }
394 _ => {}
395 }
396}