use super::contour::{inside_cell, iso_lines, ClosedPath, ScalarGrid};
use super::{GeometryError, Point, Positions};
use crate::core::hypergraph::Hypergraph;
pub const DEFAULT_LEVEL_FRACTION: f64 = 0.5;
pub const DEFAULT_MAX_GRID_NODES: usize = 4_194_304;
#[derive(Clone, Debug, PartialEq)]
pub struct OutlineParams {
pub reach: f64,
pub cell: f64,
pub share: f64,
pub level_fraction: f64,
pub max_grid_nodes: usize,
}
impl OutlineParams {
#[must_use]
pub fn new(reach: f64, cell: f64, share: f64) -> Self {
Self {
reach,
cell,
share,
level_fraction: DEFAULT_LEVEL_FRACTION,
max_grid_nodes: DEFAULT_MAX_GRID_NODES,
}
}
fn validate(&self) -> Result<(), GeometryError> {
let bad = |name: &'static str, value: f64| Err(GeometryError::BadParameter { name, value });
if !(self.reach.is_finite() && self.reach > 0.0) {
return bad("reach", self.reach);
}
if !(self.cell.is_finite() && self.cell > 0.0 && self.cell <= self.reach / 2.0) {
return bad("cell", self.cell);
}
if !(self.share > 0.0 && self.share <= 1.0) {
return bad("share", self.share);
}
if !(self.level_fraction > 0.0 && self.level_fraction <= 1.0) {
return bad("level_fraction", self.level_fraction);
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum Outline {
Ring {
center: Point,
radius: f64,
},
Capsule {
a: Point,
radius_a: f64,
b: Point,
radius_b: f64,
},
Membrane {
paths: Vec<ClosedPath>,
},
}
#[derive(Clone, Debug, PartialEq)]
pub struct WeightedOutline {
pub outline: Outline,
pub held: Vec<usize>,
pub held_weight: f64,
pub total_weight: f64,
}
struct Part {
index: usize,
at: Point,
weight: f64,
relative: f64,
}
fn radius_of(reach: f64, relative: f64) -> f64 {
reach * (0.5 + 0.5 * relative)
}
fn too_large(limit: usize) -> GeometryError {
GeometryError::GridTooLarge {
nodes: usize::MAX,
limit,
}
}
fn build_field(parts: &[Part], params: &OutlineParams) -> Result<ScalarGrid, GeometryError> {
let (reach, cell) = (params.reach, params.cell);
let margin = reach + cell;
let (mut min_x, mut min_y) = (f64::INFINITY, f64::INFINITY);
let (mut max_x, mut max_y) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
for part in parts {
min_x = min_x.min(part.at.0);
min_y = min_y.min(part.at.1);
max_x = max_x.max(part.at.0);
max_y = max_y.max(part.at.1);
}
let lo_col = ((min_x - margin) / cell).floor();
let lo_row = ((min_y - margin) / cell).floor();
let hi_col = ((max_x + margin) / cell).floor() + 1.0;
let hi_row = ((max_y + margin) / cell).floor() + 1.0;
let count = |lo: f64, hi: f64| -> Result<usize, GeometryError> {
let n = hi - lo + 1.0;
if n.is_finite() && n >= 1.0 && n < usize::MAX as f64 {
Ok(n as usize)
} else {
Err(too_large(params.max_grid_nodes))
}
};
let cols = count(lo_col, hi_col)?;
let rows = count(lo_row, hi_row)?;
let nodes = cols
.checked_mul(rows)
.ok_or_else(|| too_large(params.max_grid_nodes))?;
if nodes > params.max_grid_nodes {
return Err(GeometryError::GridTooLarge {
nodes,
limit: params.max_grid_nodes,
});
}
let mut grid = ScalarGrid::zeros((lo_col * cell, lo_row * cell), cell, cols, rows)?;
let reach2 = reach * reach;
let (ox, oy) = grid.origin;
let span = |p: f64, o: f64, n: usize| -> (usize, usize) {
let last = (n - 1) as f64;
let lo = ((p - reach - o) / cell).floor().max(0.0).min(last);
let hi = (((p + reach - o) / cell).floor() + 1.0).max(0.0).min(last);
(lo as usize, hi as usize)
};
for part in parts {
let (c0, c1) = span(part.at.0, ox, cols);
let (r0, r1) = span(part.at.1, oy, rows);
for r in r0..=r1 {
let dy = oy + r as f64 * cell - part.at.1;
for c in c0..=c1 {
let dx = ox + c as f64 * cell - part.at.0;
let d2 = dx * dx + dy * dy;
if d2 < reach2 {
let rest = 1.0 - d2 / reach2;
grid.values[r * cols + c] += part.relative * (rest * rest);
}
}
}
}
Ok(grid)
}
fn held_by(parts: &[Part], inside: impl Fn(Point) -> bool) -> (Vec<usize>, f64) {
let mut held = Vec::new();
let mut weight = 0.0;
for part in parts {
if inside(part.at) {
held.push(part.index);
weight += part.weight;
}
}
(held, weight)
}
fn in_capsule(at: Point, a: Point, ra: f64, b: Point, rb: f64) -> bool {
let (ex, ey) = (b.0 - a.0, b.1 - a.1);
let len2 = ex * ex + ey * ey;
let t = if len2 > 0.0 {
(((at.0 - a.0) * ex + (at.1 - a.1) * ey) / len2).clamp(0.0, 1.0)
} else {
0.0
};
let (dx, dy) = (at.0 - (a.0 + ex * t), at.1 - (a.1 + ey * t));
let r = ra + (rb - ra) * t;
dx * dx + dy * dy <= r * r
}
pub fn weighted_outline(
members: &[(Point, f64)],
params: &OutlineParams,
) -> Result<Option<WeightedOutline>, GeometryError> {
params.validate()?;
let mut total = 0.0_f64;
let mut largest = 0.0_f64;
for (index, &(at, weight)) in members.iter().enumerate() {
if !(weight.is_finite() && weight >= 0.0) {
return Err(GeometryError::BadWeight {
item: format!("#{index}"),
value: weight,
});
}
if weight > 0.0 {
if !(at.0.is_finite() && at.1.is_finite()) {
return Err(GeometryError::NonFinitePosition {
item: format!("#{index}"),
});
}
total += weight;
if !total.is_finite() {
return Err(GeometryError::BadWeight {
item: format!("#{index}"),
value: total,
});
}
largest = largest.max(weight);
}
}
let parts: Vec<Part> = members
.iter()
.enumerate()
.filter(|(_, &(_, weight))| weight > 0.0)
.map(|(index, &(at, weight))| Part {
index,
at,
weight,
relative: weight / largest,
})
.collect();
if parts.is_empty() {
return Ok(None);
}
let grid = build_field(&parts, params)?;
let level = |part: &Part| grid.sample(part.at).unwrap_or(0.0);
let mut order: Vec<usize> = (0..parts.len()).collect();
let levels: Vec<f64> = parts.iter().map(level).collect();
order.sort_by(|&a, &b| levels[b].total_cmp(&levels[a]).then(a.cmp(&b)));
let wanted = params.share * total;
let mut prefix = 0.0;
let mut k = order.len();
for (taken, &p) in order.iter().enumerate() {
prefix += parts[p].weight;
if prefix >= wanted {
k = taken + 1;
break;
}
}
let radius = |p: &Part| radius_of(params.reach, p.relative);
let (outline, (held, held_weight)) = match k {
1 => {
let part = &parts[order[0]];
let (center, r) = (part.at, radius(part));
let held = held_by(&parts, |at| {
let (dx, dy) = (at.0 - center.0, at.1 - center.1);
dx * dx + dy * dy <= r * r
});
(Outline::Ring { center, radius: r }, held)
}
2 => {
let (first, second) = (order[0].min(order[1]), order[0].max(order[1]));
let (pa, pb) = (&parts[first], &parts[second]);
let (a, ra, b, rb) = (pa.at, radius(pa), pb.at, radius(pb));
let held = held_by(&parts, |at| in_capsule(at, a, ra, b, rb));
(
Outline::Capsule {
a,
radius_a: ra,
b,
radius_b: rb,
},
held,
)
}
_ => {
let threshold_of = |j: usize| params.level_fraction * levels[order[j - 1]];
let reaches = |j: usize| {
held_by(&parts, |at| inside_cell(&grid, threshold_of(j), at)).1 >= wanted
};
let n = order.len();
let chosen = if k == n || reaches(k) {
k
} else if !reaches(n) {
n
} else {
let (mut lo, mut hi) = (k, n);
while hi - lo > 1 {
let mid = lo + (hi - lo) / 2;
if reaches(mid) {
hi = mid;
} else {
lo = mid;
}
}
hi
};
let threshold = threshold_of(chosen);
let held = held_by(&parts, |at| inside_cell(&grid, threshold, at));
(
Outline::Membrane {
paths: iso_lines(&grid, threshold),
},
held,
)
}
};
Ok(Some(WeightedOutline {
outline,
held,
held_weight,
total_weight: total,
}))
}
#[derive(Clone, Debug, PartialEq)]
pub struct EdgeOutline {
pub edge: String,
pub members: Vec<String>,
pub outline: WeightedOutline,
}
pub fn edge_outline<N, E, M>(
h: &Hypergraph<N, E, M>,
edge_id: &str,
positions: &Positions,
weight: impl Fn(&M) -> f64,
params: &OutlineParams,
) -> Result<Option<EdgeOutline>, GeometryError> {
let Some(listing) = h.members_with_data(edge_id) else {
return Err(GeometryError::UnknownEdge(edge_id.to_string()));
};
let mut members = Vec::new();
let mut points: Vec<(Point, f64)> = Vec::new();
let mut total = 0.0_f64;
for (node, data) in listing {
let w = weight(data);
if !(w.is_finite() && w >= 0.0) {
return Err(GeometryError::BadWeight {
item: node,
value: w,
});
}
if w == 0.0 {
continue;
}
let Some(at) = positions.get(&node) else {
return Err(GeometryError::NoPosition {
edge: edge_id.to_string(),
node,
});
};
if !(at.0.is_finite() && at.1.is_finite()) {
return Err(GeometryError::NonFinitePosition { item: node });
}
total += w;
if !total.is_finite() {
return Err(GeometryError::BadWeight {
item: node,
value: total,
});
}
members.push(node);
points.push((at, w));
}
Ok(
weighted_outline(&points, params)?.map(|outline| EdgeOutline {
edge: edge_id.to_string(),
members,
outline,
}),
)
}