ifc_lite_diff/
content_match.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Ordered content tiers: geometry+data, geometry-only, then residue/position.
6use crate::JsString;
7use crate::content_helpers::*;
8use crate::content_types::*;
9use crate::geometry_compare::*;
10use crate::key_diff::changed_components;
11use crate::model::{DiffEntry, DiffState, KeyDiff};
12
13fn split<R>(entries: &[DiffEntry<'_, R>], indices: &[usize]) -> (Vec<usize>, Vec<usize>) {
14    indices.iter().copied().partition(|i| entries[*i].state == DiffState::Deleted)
15}
16fn live(indices: &[usize], retired: &[bool]) -> Vec<usize> {
17    indices.iter().copied().filter(|i| !retired[*i]).collect()
18}
19fn retire(indices: impl IntoIterator<Item = usize>, retired: &mut [bool]) {
20    for i in indices { retired[i] = true; }
21}
22
23pub fn apply_content_matching<'a, R>(core: KeyDiff<'a, R>, tolerances: GeometryTolerances) -> ContentDiff<'a, R> {
24    apply_content_matching_impl(core, tolerances, true)
25}
26
27pub(crate) fn apply_content_matching_for_transport<'a, R>(core: KeyDiff<'a, R>, tolerances: GeometryTolerances) -> ContentDiff<'a, R> {
28    apply_content_matching_impl(core, tolerances, false)
29}
30
31fn apply_content_matching_impl<'a, R>(mut core: KeyDiff<'a, R>, tolerances: GeometryTolerances, build_index: bool) -> ContentDiff<'a, R> {
32    let entries = &core.entries;
33    let strip = core.strip_placement_geometry;
34    let mut bases = Buckets::default();
35    let mut heads = Buckets::default();
36    for (i, entry) in entries.iter().enumerate() {
37        let bucket = match entry.state {
38            DiffState::Added => &mut heads, DiffState::Deleted => &mut bases, _ => continue,
39        };
40        let entity = fingerprint(entries, i);
41        bucket.push(JsString::concat(&[&entity.ifc_type, &entity.data_hash], "\0"), i);
42    }
43    let mut retired = vec![false; entries.len()];
44    let mut matches = Vec::new();
45    let mut geometry_groups = Vec::new();
46    if core.use_geometry {
47        // Phase 1: equal-cardinality geometry subgroups inside each data bucket.
48        for (key, head_group) in &heads.groups {
49            let Some(base_group) = bases.get(key) else { continue };
50            let mut geometry = Buckets::default();
51            for i in base_group.iter().chain(head_group) {
52                if let Some(hash) = fingerprint(entries, *i).geometry_hash(strip) { geometry.push(hash.clone(), *i); }
53            }
54            for (_, group) in geometry.groups {
55                let (base, head) = split(entries, &group);
56                if base.is_empty() || base.len() != head.len() || !components_agree(entries, group.iter().copied()) { continue; }
57                matches.push(make_match(entries, &base, &head, ContentMatchKind::Renamed,
58                    ContentMatchTier::GeometryHash, &fingerprint(entries, head[0]).data_hash, None));
59                retire(group, &mut retired);
60            }
61        }
62        // Phase 2: regroup the union residue by class and geometry. Traversal
63        // follows data-bucket insertion order, exactly as in TypeScript.
64        let mut geometry = Buckets::default();
65        for (_, group) in bases.groups.iter().chain(&heads.groups) {
66            for i in live(group, &retired) {
67                let entity = fingerprint(entries, i);
68                let (Some(hash), Some(aabb)) = (entity.geometry_hash(strip), &entity.aabb) else { continue };
69                if usable_aabb(aabb) { geometry.push(JsString::concat(&[&entity.ifc_type, hash], "\0"), i); }
70            }
71        }
72        for (_, group) in geometry.groups {
73            let (base, head) = split(entries, &group);
74            if base.is_empty() || head.is_empty() { continue; }
75            let geometry_hash = fingerprint(entries, head[0]).geometry_hash(strip).cloned();
76            if base.len() == 1 && head.len() == 1 {
77                let a = fingerprint(entries, base[0]);
78                let b = fingerprint(entries, head[0]);
79                let (Some(ab), Some(bb)) = (&a.aabb, &b.aabb) else { continue };
80                if !size_agrees(ab, bb, tolerances.reshape_tolerance)
81                    || centre_distance(centre(ab), centre(bb)).partial_cmp(&tolerances.move_tolerance)
82                        .is_none_or(|order| order.is_gt())
83                    || a.data_hash == b.data_hash { continue; }
84                let mut matched = make_match(entries, &base, &head, ContentMatchKind::Respecified,
85                    ContentMatchTier::GeometryOnly, &b.data_hash, None);
86                matched.geometry_hash = geometry_hash;
87                if let (Some(ac), Some(bc)) = (&a.components, &b.components) {
88                    matched.changed_components = Some(changed_components(ac, bc));
89                }
90                matches.push(matched);
91                retire(group, &mut retired);
92            } else if base.len() == head.len() {
93                geometry_groups.push((base, head, geometry_hash));
94            }
95        }
96    }
97    // Phase 3: unique residue pairs, then mutual-nearest positions, then groups.
98    for (key, head_group) in &heads.groups {
99        let Some(base_group) = bases.get(key) else { continue };
100        let base = live(base_group, &retired);
101        let head = live(head_group, &retired);
102        if base.is_empty() || head.is_empty() { continue; }
103        let data_hash = &fingerprint(entries, head_group[0]).data_hash;
104        if base.len() == 1 && head.len() == 1 {
105            if components_agree(entries, [base[0], head[0]]) {
106                let (kind, distance) = classify_pair(fingerprint(entries, base[0]), fingerprint(entries, head[0]), core.use_geometry, strip, tolerances);
107                matches.push(make_match(entries, &base, &head, kind, ContentMatchTier::ResidueOneToOne, data_hash, distance));
108                retire([base[0], head[0]], &mut retired);
109            }
110            continue;
111        }
112        for (b, h) in pair_by_position(entries, &base, &head, core.use_geometry, tolerances) {
113            let (kind, distance) = classify_pair(fingerprint(entries, b), fingerprint(entries, h), core.use_geometry, strip, tolerances);
114            matches.push(make_match(entries, &[b], &[h], kind, ContentMatchTier::Positional, data_hash, distance));
115            retire([b, h], &mut retired);
116        }
117        let base = live(&base, &retired);
118        let head = live(&head, &retired);
119        if !base.is_empty() && !head.is_empty() {
120            matches.push(make_match(entries, &base, &head, group_kind(base.len(), head.len()), ContentMatchTier::Unresolved, data_hash, None));
121        }
122    }
123    for (base, head, geometry_hash) in geometry_groups {
124        let base = live(&base, &retired);
125        let head = live(&head, &retired);
126        if base.is_empty() || head.is_empty() { continue; }
127        let mut group = make_match(entries, &base, &head, group_kind(base.len(), head.len()), ContentMatchTier::Unresolved, &JsString::default(), None);
128        group.geometry_hash = geometry_hash;
129        matches.push(group);
130    }
131    if !retired.iter().any(|retired| *retired) {
132        return ContentDiff { core, content_matches: matches };
133    }
134    for (i, entry) in entries.iter().enumerate() {
135        if retired[i] {
136            match entry.state {
137                DiffState::Added => core.counts.added -= 1,
138                DiffState::Deleted => core.counts.deleted -= 1,
139                _ => unreachable!("only added/deleted entries can be candidates"),
140            }
141        }
142    }
143    let mut index = 0;
144    core.entries.retain(|_| { let keep = !retired[index]; index += 1; keep });
145    if build_index {
146        core.by_key = core.entries.iter().enumerate().map(|(i, entry)| (entry.key.clone(), i)).collect();
147    }
148    ContentDiff { core, content_matches: matches }
149}