use serde::{Deserialize, Serialize};
use super::field::FieldId;
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum Falloff {
Hard,
Linear,
Smoothstep,
Quadratic,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ScalarField {
Const(f32),
CoordX,
CoordY,
Time,
Gaussian {
center: Box<VectorField>,
sigma: f32,
},
Disk {
center: Box<VectorField>,
radius: f32,
falloff: Falloff,
},
Linear {
normal: Box<VectorField>,
offset: f32,
},
Add(Box<ScalarField>, Box<ScalarField>),
Mul(Box<ScalarField>, Box<ScalarField>),
Scale(Box<ScalarField>, f32),
Negate(Box<ScalarField>),
Dot(Box<VectorField>, Box<VectorField>),
Sample(FieldId),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum VectorField {
ConstVec { x: f32, y: f32 },
Coord,
Gradient(Box<ScalarField>),
Perp(Box<VectorField>),
Add(Box<VectorField>, Box<VectorField>),
Scale(Box<VectorField>, Box<ScalarField>),
ScaleConst(Box<VectorField>, f32),
Sample(FieldId),
}
impl ScalarField {
pub fn gaussian_at(cx: f32, cy: f32, sigma: f32) -> Self {
Self::Gaussian {
center: Box::new(VectorField::ConstVec { x: cx, y: cy }),
sigma,
}
}
pub fn disk_at(cx: f32, cy: f32, radius: f32, falloff: Falloff) -> Self {
Self::Disk {
center: Box::new(VectorField::ConstVec { x: cx, y: cy }),
radius,
falloff,
}
}
pub fn linear(nx: f32, ny: f32, offset: f32) -> Self {
Self::Linear {
normal: Box::new(VectorField::ConstVec { x: nx, y: ny }),
offset,
}
}
}
impl VectorField {
pub fn const_vec(x: f32, y: f32) -> Self {
Self::ConstVec { x, y }
}
pub fn gradient_of(scalar: ScalarField) -> Self {
Self::Gradient(Box::new(scalar))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scalar_field_serde_roundtrip() {
let field = ScalarField::Add(
Box::new(ScalarField::gaussian_at(10.0, 20.0, 50.0)),
Box::new(ScalarField::Scale(Box::new(ScalarField::CoordX), 0.5)),
);
let s = serde_json::to_string(&field).unwrap();
let back: ScalarField = serde_json::from_str(&s).unwrap();
assert_eq!(field, back);
}
#[test]
fn vector_field_serde_roundtrip() {
let field = VectorField::Add(
Box::new(VectorField::Coord),
Box::new(VectorField::Gradient(Box::new(ScalarField::CoordX))),
);
let s = serde_json::to_string(&field).unwrap();
let back: VectorField = serde_json::from_str(&s).unwrap();
assert_eq!(field, back);
}
#[test]
fn disk_falloff_roundtrip() {
let f = ScalarField::disk_at(5.0, -3.0, 7.5, Falloff::Smoothstep);
let s = serde_json::to_string(&f).unwrap();
assert_eq!(f, serde_json::from_str::<ScalarField>(&s).unwrap());
}
}