use serde::{Deserialize, Serialize};
use uuid::Uuid;
use super::field_ast::{ScalarField, VectorField};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct FieldId(pub Uuid);
impl FieldId {
#[cfg(not(target_arch = "wasm32"))]
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn from_uuid(id: Uuid) -> Self {
Self(id)
}
pub fn as_uuid(self) -> Uuid {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CouplingId(pub Uuid);
impl CouplingId {
#[cfg(not(target_arch = "wasm32"))]
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn from_uuid(id: Uuid) -> Self {
Self(id)
}
pub fn as_uuid(self) -> Uuid {
self.0
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FieldDefinition {
Scalar(ScalarField),
Vector(VectorField),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FieldExtent {
Global,
Region {
min_x: f32,
min_y: f32,
max_x: f32,
max_y: f32,
},
AttachedToNode(Uuid),
Polygon { points: Vec<(f32, f32)> },
}
impl FieldExtent {
pub fn contains(&self, x: f32, y: f32) -> Option<bool> {
match self {
FieldExtent::Global => Some(true),
FieldExtent::Region {
min_x,
min_y,
max_x,
max_y,
} => Some(x >= *min_x && x <= *max_x && y >= *min_y && y <= *max_y),
FieldExtent::AttachedToNode(_) => None,
FieldExtent::Polygon { points } => Some(polygon_contains(points, x, y)),
}
}
pub fn boundary_distance(&self, x: f32, y: f32) -> Option<f32> {
match self {
FieldExtent::Global => None,
FieldExtent::AttachedToNode(_) => None,
FieldExtent::Region {
min_x,
min_y,
max_x,
max_y,
} => {
let inside = (x - min_x).min(max_x - x).min(y - min_y).min(max_y - y);
Some(inside)
},
FieldExtent::Polygon { points } => {
if points.len() < 3 {
return None;
}
let nearest = points
.iter()
.enumerate()
.map(|(index, a)| {
let b = points[(index + 1) % points.len()];
segment_distance(*a, b, (x, y))
})
.fold(f32::INFINITY, f32::min);
Some(if polygon_contains(points, x, y) {
nearest
} else {
-nearest
})
},
}
}
}
fn polygon_contains(points: &[(f32, f32)], x: f32, y: f32) -> bool {
if points.len() < 3 {
return false;
}
if !x.is_finite()
|| !y.is_finite()
|| points.iter().any(|(x, y)| !x.is_finite() || !y.is_finite())
{
return false;
}
let a = points[0];
let Some(b) = points.iter().find(|b| **b != a) else {
return false;
};
let collinear = points.iter().all(|p| {
(f64::from(b.0) - f64::from(a.0)) * (f64::from(p.1) - f64::from(a.1))
== (f64::from(b.1) - f64::from(a.1)) * (f64::from(p.0) - f64::from(a.0))
});
if collinear {
return false;
}
let (x, y) = (f64::from(x), f64::from(y));
let mut inside = false;
for (index, a) in points.iter().enumerate() {
let b = points[(index + 1) % points.len()];
let (ax, ay, bx, by) = (
f64::from(a.0),
f64::from(a.1),
f64::from(b.0),
f64::from(b.1),
);
let cross = (bx - ax) * (y - ay) - (by - ay) * (x - ax);
if cross == 0.0 && x >= ax.min(bx) && x <= ax.max(bx) && y >= ay.min(by) && y <= ay.max(by)
{
return true;
}
if (ay > y) != (by > y) && x < ax + (bx - ax) * (y - ay) / (by - ay) {
inside = !inside;
}
}
inside
}
fn segment_distance(a: (f32, f32), b: (f32, f32), p: (f32, f32)) -> f32 {
let (abx, aby) = (b.0 - a.0, b.1 - a.1);
let (apx, apy) = (p.0 - a.0, p.1 - a.1);
let length_sq = abx * abx + aby * aby;
let t = if length_sq <= f32::EPSILON {
0.0
} else {
((apx * abx + apy * aby) / length_sq).clamp(0.0, 1.0)
};
let (dx, dy) = (apx - abx * t, apy - aby * t);
(dx * dx + dy * dy).sqrt()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FieldLifecycle {
Active,
Retired,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Field {
pub id: FieldId,
pub name: Option<String>,
pub definition: FieldDefinition,
pub extent: FieldExtent,
pub lifecycle: FieldLifecycle,
}
impl Field {
pub fn new(id: FieldId, definition: FieldDefinition) -> Self {
Self {
id,
name: None,
definition,
extent: FieldExtent::Global,
lifecycle: FieldLifecycle::Active,
}
}
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn with_extent(mut self, extent: FieldExtent) -> Self {
self.extent = extent;
self
}
pub fn is_active(&self) -> bool {
self.lifecycle == FieldLifecycle::Active
}
}
#[cfg(test)]
mod tests {
use super::super::field_ast::Falloff;
use super::*;
fn sample_uuid(n: u8) -> Uuid {
Uuid::from_bytes([n; 16])
}
#[test]
fn field_serde_roundtrip() {
let field = Field::new(
FieldId::from_uuid(sample_uuid(1)),
FieldDefinition::Scalar(ScalarField::disk_at(0.0, 0.0, 50.0, Falloff::Smoothstep)),
)
.with_name("focus")
.with_extent(FieldExtent::AttachedToNode(sample_uuid(2)));
let s = serde_json::to_string(&field).unwrap();
let back: Field = serde_json::from_str(&s).unwrap();
assert_eq!(field, back);
}
#[test]
fn defaults_are_global_active() {
let f = Field::new(
FieldId::from_uuid(sample_uuid(3)),
FieldDefinition::Vector(VectorField::Coord),
);
assert_eq!(f.extent, FieldExtent::Global);
assert!(f.is_active());
assert!(f.name.is_none());
}
#[test]
fn a_polygon_extent_contains_and_measures() {
let extent = FieldExtent::Polygon {
points: vec![(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)],
};
assert_eq!(extent.contains(2.0, 2.0), Some(true));
assert_eq!(extent.contains(9.0, 9.0), Some(false));
assert!(extent.boundary_distance(2.0, 2.0).unwrap() > 0.0);
assert!(extent.boundary_distance(20.0, 20.0).unwrap() < 0.0);
let inside = extent.boundary_distance(3.0, 1.0).unwrap();
assert!((inside - 1.0).abs() < 1e-4, "got {inside}");
}
#[test]
fn a_degenerate_polygon_contains_nothing() {
let extent = FieldExtent::Polygon {
points: vec![(0.0, 0.0), (10.0, 0.0)],
};
assert_eq!(extent.contains(5.0, 0.0), Some(false));
assert_eq!(extent.boundary_distance(5.0, 0.0), None);
}
#[test]
fn attachment_is_a_question_for_a_graph() {
let extent = FieldExtent::AttachedToNode(sample_uuid(9));
assert_eq!(extent.contains(0.0, 0.0), None);
assert_eq!(extent.boundary_distance(0.0, 0.0), None);
}
#[test]
fn a_polygon_extent_round_trips() {
let field = Field::new(
FieldId::from_uuid(sample_uuid(7)),
FieldDefinition::Scalar(ScalarField::Const(1.0)),
)
.with_extent(FieldExtent::Polygon {
points: vec![(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)],
});
let json = serde_json::to_string(&field).unwrap();
assert_eq!(serde_json::from_str::<Field>(&json).unwrap(), field);
}
#[test]
fn ids_are_distinct_types_but_uuid_backed() {
let fid = FieldId::from_uuid(sample_uuid(4));
let cid = CouplingId::from_uuid(sample_uuid(4));
assert_eq!(fid.as_uuid(), cid.as_uuid());
}
}
#[cfg(test)]
mod inclusive_boundary_tests {
use super::*;
#[test]
fn polygon_reference_points_include_every_edge_and_vertex_in_both_windings() {
let mut points = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)];
for _ in 0..2 {
let extent = FieldExtent::Polygon {
points: points.clone(),
};
for (x, y) in [
(0., 0.),
(10., 0.),
(10., 10.),
(0., 10.),
(0., 5.),
(10., 5.),
(5., 0.),
(5., 10.),
(5., 5.),
] {
assert_eq!(extent.contains(x, y), Some(true), "({x}, {y})");
}
assert_eq!(
extent.contains(f32::from_bits(10.0_f32.to_bits() + 1), 5.0),
Some(false)
);
assert_eq!(extent.contains(f32::NAN, 5.0), Some(false));
points.reverse();
assert_eq!(
FieldExtent::Polygon {
points: vec![(0.0, 0.0), (5.0, 0.0), (10.0, 0.0)]
}
.contains(5.0, 0.0),
Some(false)
);
}
}
}