numen/field_ast.rs
1//! Portable field-expression AST — kernel truth.
2//!
3//! Two mutually-recursive enums describe the algebra: [`ScalarField`] for
4//! `f: R^2 -> R` and [`VectorField`] for `f: R^2 -> R^2`. This is the
5//! *definition* the kernel owns and persists; **the kernel does not evaluate
6//! it** — `quint` does (closed forms + finite differences, optionally Burn).
7//!
8//! Ported from `quint::ast` (the field-system step-3 plan, 2026-05-31): the
9//! kernel becomes the owner of the portable definition, `quint` gains a
10//! `kernel` dependency and uses these types for evaluation. Two differences
11//! from the quint original: [`ScalarField::Sample`] / [`VectorField::Sample`]
12//! reference the kernel-stable [`FieldId`](super::field::FieldId) (UUID) rather
13//! than the original's registry-local `FieldId(u64)`; and there is no Rhai/Burn
14//! here.
15//!
16//! Derives are serde only for now. rkyv archiving is handled at the
17//! `Persisted*` DTO layer (plan Phase 2), where the recursive-Box rkyv decision
18//! (omit_bounds vs serde-blob) is settled against `snapshot/{to,from}.rs`.
19//!
20//! WASM-clean: plain data, no host dependencies.
21
22use serde::{Deserialize, Serialize};
23
24use super::field::FieldId;
25
26/// Falloff shape for spatially-bounded scalar kernels (e.g. [`ScalarField::Disk`]).
27#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
28pub enum Falloff {
29 /// Constant `1.0` inside, `0.0` outside (a step).
30 Hard,
31 /// Linear ramp from `1.0` at center to `0.0` at boundary.
32 Linear,
33 /// `1 - smoothstep(0,1,t)` ramp; smooth derivative at both ends.
34 Smoothstep,
35 /// `(1 - t)^2` quadratic ramp.
36 Quadratic,
37}
38
39/// A scalar field expression. Recursive cases use `Box` to keep the enum sized.
40#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
41pub enum ScalarField {
42 /// Constant value everywhere.
43 Const(f32),
44 /// The x-coordinate at the evaluation point.
45 CoordX,
46 /// The y-coordinate at the evaluation point.
47 CoordY,
48 /// The current time (seconds since a host-chosen epoch).
49 Time,
50 /// `exp(-||p - center||^2 / (2 sigma^2))`.
51 Gaussian {
52 center: Box<VectorField>,
53 sigma: f32,
54 },
55 /// `1.0` at center, `0.0` outside `radius`, with a falloff inside.
56 Disk {
57 center: Box<VectorField>,
58 radius: f32,
59 falloff: Falloff,
60 },
61 /// `dot(normal(p), p) + offset`.
62 Linear {
63 normal: Box<VectorField>,
64 offset: f32,
65 },
66 /// Pointwise sum.
67 Add(Box<ScalarField>, Box<ScalarField>),
68 /// Pointwise product.
69 Mul(Box<ScalarField>, Box<ScalarField>),
70 /// Pointwise multiply by a constant scalar.
71 Scale(Box<ScalarField>, f32),
72 /// Negation.
73 Negate(Box<ScalarField>),
74 /// Dot product of two vector fields.
75 Dot(Box<VectorField>, Box<VectorField>),
76 /// Reference to another registered scalar field by id.
77 Sample(FieldId),
78}
79
80/// A vector field expression.
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
82pub enum VectorField {
83 /// Constant vector everywhere.
84 ConstVec { x: f32, y: f32 },
85 /// The identity field returning `(x, y)` at the evaluation point.
86 Coord,
87 /// `grad(scalar)` — first-class so the evaluator can use closed forms.
88 Gradient(Box<ScalarField>),
89 /// 2D 90-degree rotation: `Perp((x, y)) = (-y, x)`.
90 Perp(Box<VectorField>),
91 /// Pointwise sum.
92 Add(Box<VectorField>, Box<VectorField>),
93 /// Pointwise scalar-times-vector.
94 Scale(Box<VectorField>, Box<ScalarField>),
95 /// Pointwise multiply by a constant scalar.
96 ScaleConst(Box<VectorField>, f32),
97 /// Reference to another registered vector field by id.
98 Sample(FieldId),
99}
100
101// ── Convenience constructors ────────────────────────────────────────────────
102
103impl ScalarField {
104 /// `Gaussian` centered at a constant point.
105 pub fn gaussian_at(cx: f32, cy: f32, sigma: f32) -> Self {
106 Self::Gaussian {
107 center: Box::new(VectorField::ConstVec { x: cx, y: cy }),
108 sigma,
109 }
110 }
111
112 /// `Disk` centered at a constant point.
113 pub fn disk_at(cx: f32, cy: f32, radius: f32, falloff: Falloff) -> Self {
114 Self::Disk {
115 center: Box::new(VectorField::ConstVec { x: cx, y: cy }),
116 radius,
117 falloff,
118 }
119 }
120
121 /// `Linear` with a constant normal: `dot((nx, ny), p) + offset`.
122 pub fn linear(nx: f32, ny: f32, offset: f32) -> Self {
123 Self::Linear {
124 normal: Box::new(VectorField::ConstVec { x: nx, y: ny }),
125 offset,
126 }
127 }
128}
129
130impl VectorField {
131 pub fn const_vec(x: f32, y: f32) -> Self {
132 Self::ConstVec { x, y }
133 }
134
135 pub fn gradient_of(scalar: ScalarField) -> Self {
136 Self::Gradient(Box::new(scalar))
137 }
138}
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143
144 #[test]
145 fn scalar_field_serde_roundtrip() {
146 let field = ScalarField::Add(
147 Box::new(ScalarField::gaussian_at(10.0, 20.0, 50.0)),
148 Box::new(ScalarField::Scale(Box::new(ScalarField::CoordX), 0.5)),
149 );
150 let s = serde_json::to_string(&field).unwrap();
151 let back: ScalarField = serde_json::from_str(&s).unwrap();
152 assert_eq!(field, back);
153 }
154
155 #[test]
156 fn vector_field_serde_roundtrip() {
157 let field = VectorField::Add(
158 Box::new(VectorField::Coord),
159 Box::new(VectorField::Gradient(Box::new(ScalarField::CoordX))),
160 );
161 let s = serde_json::to_string(&field).unwrap();
162 let back: VectorField = serde_json::from_str(&s).unwrap();
163 assert_eq!(field, back);
164 }
165
166 #[test]
167 fn disk_falloff_roundtrip() {
168 let f = ScalarField::disk_at(5.0, -3.0, 7.5, Falloff::Smoothstep);
169 let s = serde_json::to_string(&f).unwrap();
170 assert_eq!(f, serde_json::from_str::<ScalarField>(&s).unwrap());
171 }
172}