Skip to main content

sim_engine/
field.rs

1use std::{error::Error, fmt};
2
3use crate::Color;
4
5/// A finite, rectangular scalar grid for dense simulation data.
6#[derive(Debug, Clone, PartialEq)]
7pub struct ScalarField {
8    width: usize,
9    height: usize,
10    values: Vec<f32>,
11}
12
13impl ScalarField {
14    /// Default maximum allocation performed by [`ScalarField::filled`].
15    ///
16    /// Hosts needing a different explicit budget can use
17    /// [`ScalarField::filled_with_byte_limit`] or pass an already allocated
18    /// buffer to [`ScalarField::new`].
19    pub const DEFAULT_MAX_FILLED_BYTES: usize = 256 * 1024 * 1024;
20
21    /// Creates a field from row-major values, validating dimensions and finiteness.
22    pub fn new(width: usize, height: usize, values: Vec<f32>) -> Result<Self, ScalarFieldError> {
23        let expected_len = checked_len(width, height)?;
24        if values.len() != expected_len {
25            return Err(ScalarFieldError::InvalidValueCount {
26                expected: expected_len,
27                actual: values.len(),
28            });
29        }
30        if values.iter().any(|value| !value.is_finite()) {
31            return Err(ScalarFieldError::NonFiniteValue);
32        }
33        Ok(Self {
34            width,
35            height,
36            values,
37        })
38    }
39
40    /// Creates a finite field filled with one finite scalar value.
41    ///
42    /// Allocation is limited to [`ScalarField::DEFAULT_MAX_FILLED_BYTES`] and
43    /// uses fallible reservation before initialization.
44    pub fn filled(width: usize, height: usize, value: f32) -> Result<Self, ScalarFieldError> {
45        Self::filled_with_byte_limit(width, height, value, Self::DEFAULT_MAX_FILLED_BYTES)
46    }
47
48    /// Creates a filled field under an explicit host-memory byte limit.
49    ///
50    /// `maximum_bytes` applies to the row-major `f32` value buffer. Reservation
51    /// failure is returned without partially constructing the field. Supplying
52    /// a larger limit is an explicit host decision; system overcommit can still
53    /// make physical memory exhaustion unrecoverable on some platforms.
54    pub fn filled_with_byte_limit(
55        width: usize,
56        height: usize,
57        value: f32,
58        maximum_bytes: usize,
59    ) -> Result<Self, ScalarFieldError> {
60        let len = checked_len(width, height)?;
61        if !value.is_finite() {
62            return Err(ScalarFieldError::NonFiniteValue);
63        }
64        let requested_bytes = len
65            .checked_mul(std::mem::size_of::<f32>())
66            .ok_or(ScalarFieldError::DimensionsOverflow)?;
67        if requested_bytes > maximum_bytes {
68            return Err(ScalarFieldError::AllocationLimitExceeded {
69                requested_bytes,
70                maximum_bytes,
71            });
72        }
73        let mut values = Vec::new();
74        values
75            .try_reserve_exact(len)
76            .map_err(|_| ScalarFieldError::AllocationFailed { requested_bytes })?;
77        let actual_bytes = values.capacity().saturating_mul(std::mem::size_of::<f32>());
78        if actual_bytes > maximum_bytes {
79            return Err(ScalarFieldError::AllocationLimitExceeded {
80                requested_bytes: actual_bytes,
81                maximum_bytes,
82            });
83        }
84        values.resize(len, value);
85        Ok(Self {
86            width,
87            height,
88            values,
89        })
90    }
91
92    /// Returns the horizontal cell count.
93    pub fn width(&self) -> usize {
94        self.width
95    }
96
97    /// Returns the vertical cell count.
98    pub fn height(&self) -> usize {
99        self.height
100    }
101
102    /// Returns row-major scalar values.
103    pub fn values(&self) -> &[f32] {
104        &self.values
105    }
106
107    #[cfg(feature = "wgpu")]
108    pub(crate) fn value_allocation_bytes(&self) -> usize {
109        self.values
110            .capacity()
111            .saturating_mul(std::mem::size_of::<f32>())
112    }
113
114    /// Returns a cell value, or `None` outside field bounds.
115    pub fn value_at(&self, x: usize, y: usize) -> Option<f32> {
116        self.index(x, y).map(|index| self.values[index])
117    }
118
119    /// Replaces one cell with a finite value.
120    pub fn set(&mut self, x: usize, y: usize, value: f32) -> Result<(), ScalarFieldError> {
121        if !value.is_finite() {
122            return Err(ScalarFieldError::NonFiniteValue);
123        }
124        let index = self
125            .index(x, y)
126            .ok_or(ScalarFieldError::OutOfBounds { x, y })?;
127        self.values[index] = value;
128        Ok(())
129    }
130
131    /// Replaces all values while preserving the field dimensions.
132    pub fn replace_values(&mut self, values: Vec<f32>) -> Result<(), ScalarFieldError> {
133        if values.len() != self.values.len() {
134            return Err(ScalarFieldError::InvalidValueCount {
135                expected: self.values.len(),
136                actual: values.len(),
137            });
138        }
139        if values.iter().any(|value| !value.is_finite()) {
140            return Err(ScalarFieldError::NonFiniteValue);
141        }
142        self.values = values;
143        Ok(())
144    }
145
146    /// Replaces a contiguous rectangular region with finite row-major values.
147    pub fn replace_region(
148        &mut self,
149        x: usize,
150        y: usize,
151        width: usize,
152        height: usize,
153        values: &[f32],
154    ) -> Result<(), ScalarFieldError> {
155        let expected = checked_len(width, height)?;
156        if values.len() != expected {
157            return Err(ScalarFieldError::InvalidValueCount {
158                expected,
159                actual: values.len(),
160            });
161        }
162        if values.iter().any(|value| !value.is_finite()) {
163            return Err(ScalarFieldError::NonFiniteValue);
164        }
165        let end_x = x
166            .checked_add(width)
167            .ok_or(ScalarFieldError::OutOfBounds { x, y })?;
168        let end_y = y
169            .checked_add(height)
170            .ok_or(ScalarFieldError::OutOfBounds { x, y })?;
171        if end_x > self.width || end_y > self.height {
172            return Err(ScalarFieldError::OutOfBounds { x, y });
173        }
174        for row in 0..height {
175            let destination = (y + row) * self.width + x;
176            let source = row * width;
177            self.values[destination..destination + width]
178                .copy_from_slice(&values[source..source + width]);
179        }
180        Ok(())
181    }
182
183    /// Returns finite minimum and maximum scalar values.
184    pub fn value_range(&self) -> (f32, f32) {
185        let mut minimum = self.values[0];
186        let mut maximum = minimum;
187        for value in &self.values[1..] {
188            minimum = minimum.min(*value);
189            maximum = maximum.max(*value);
190        }
191        (minimum, maximum)
192    }
193
194    fn index(&self, x: usize, y: usize) -> Option<usize> {
195        (x < self.width && y < self.height).then_some(y * self.width + x)
196    }
197}
198
199fn checked_len(width: usize, height: usize) -> Result<usize, ScalarFieldError> {
200    if width == 0 || height == 0 {
201        return Err(ScalarFieldError::ZeroDimension);
202    }
203    width
204        .checked_mul(height)
205        .ok_or(ScalarFieldError::DimensionsOverflow)
206}
207
208/// Rejection reason for scalar-field construction or mutation.
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum ScalarFieldError {
211    /// Width and height must both be non-zero.
212    ZeroDimension,
213    /// Width multiplied by height overflowed `usize`.
214    DimensionsOverflow,
215    /// Input values did not match the grid dimensions.
216    InvalidValueCount {
217        /// Required row-major cell count.
218        expected: usize,
219        /// Supplied value count.
220        actual: usize,
221    },
222    /// A scalar value was NaN or infinite.
223    NonFiniteValue,
224    /// A filled field exceeds the explicit host-memory budget.
225    AllocationLimitExceeded {
226        /// Bytes required by the row-major `f32` values.
227        requested_bytes: usize,
228        /// Maximum bytes authorized by the caller or default policy.
229        maximum_bytes: usize,
230    },
231    /// The allocator rejected a value-buffer reservation within the byte limit.
232    AllocationFailed {
233        /// Bytes requested from the allocator.
234        requested_bytes: usize,
235    },
236    /// A requested cell lies outside the field dimensions.
237    OutOfBounds {
238        /// Horizontal cell index.
239        x: usize,
240        /// Vertical cell index.
241        y: usize,
242    },
243}
244
245impl fmt::Display for ScalarFieldError {
246    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
247        match self {
248            Self::ZeroDimension => write!(formatter, "scalar field dimensions must be non-zero"),
249            Self::DimensionsOverflow => write!(formatter, "scalar field dimensions overflow"),
250            Self::InvalidValueCount { expected, actual } => {
251                write!(
252                    formatter,
253                    "scalar field needs {expected} values, got {actual}"
254                )
255            }
256            Self::NonFiniteValue => write!(formatter, "scalar field values must be finite"),
257            Self::AllocationLimitExceeded {
258                requested_bytes,
259                maximum_bytes,
260            } => write!(
261                formatter,
262                "scalar field needs {requested_bytes} bytes, exceeding the {maximum_bytes}-byte allocation limit"
263            ),
264            Self::AllocationFailed { requested_bytes } => write!(
265                formatter,
266                "scalar field could not reserve {requested_bytes} bytes"
267            ),
268            Self::OutOfBounds { x, y } => {
269                write!(formatter, "scalar field cell ({x}, {y}) is out of bounds")
270            }
271        }
272    }
273}
274
275impl Error for ScalarFieldError {}
276
277/// One normalized color-map control point.
278#[derive(Debug, Clone, Copy, PartialEq)]
279pub struct ColorStop {
280    position: f32,
281    color: Color,
282}
283
284impl ColorStop {
285    /// Creates a stop with normalized position and normalized linear RGBA color.
286    ///
287    /// Normalized colors keep the CPU sampler consistent with the renderer's
288    /// `Rgba8Unorm` heatmap lookup texture instead of silently clipping HDR values.
289    pub fn new(position: f32, color: Color) -> Result<Self, ColorMapError> {
290        if !position.is_finite() || !color.is_finite() {
291            return Err(ColorMapError::NonFiniteStop);
292        }
293        if !(0.0..=1.0).contains(&position) {
294            return Err(ColorMapError::PositionOutOfRange);
295        }
296        if !color.is_normalized() {
297            return Err(ColorMapError::ColorOutOfRange);
298        }
299        Ok(Self { position, color })
300    }
301
302    /// Returns the normalized stop position.
303    pub fn position(self) -> f32 {
304        self.position
305    }
306
307    /// Returns the linear RGBA stop color.
308    pub fn color(self) -> Color {
309        self.color
310    }
311}
312
313/// A piecewise-linear map from normalized scalar values to linear RGBA colors.
314///
315/// [`Self::sample`] evaluates the control points exactly on the CPU. The `wgpu`
316/// heatmap renderer samples a documented 256-entry, 8-bit lookup table, so
317/// transitions narrower than one LUT interval can be quantized away.
318#[derive(Debug, Clone, PartialEq)]
319pub struct ColorMap {
320    stops: Vec<ColorStop>,
321}
322
323impl ColorMap {
324    /// Builds a color map from at least two strictly increasing stops.
325    pub fn new(stops: Vec<ColorStop>) -> Result<Self, ColorMapError> {
326        if stops.len() < 2 {
327            return Err(ColorMapError::TooFewStops);
328        }
329        if stops
330            .windows(2)
331            .any(|pair| pair[0].position >= pair[1].position)
332        {
333            return Err(ColorMapError::StopsNotIncreasing);
334        }
335        Ok(Self { stops })
336    }
337
338    /// Builds a two-color normalized gradient.
339    pub fn linear(start: Color, end: Color) -> Result<Self, ColorMapError> {
340        Self::new(vec![ColorStop::new(0.0, start)?, ColorStop::new(1.0, end)?])
341    }
342
343    /// Returns the immutable control points.
344    pub fn stops(&self) -> &[ColorStop] {
345        &self.stops
346    }
347
348    /// Returns CPU bytes currently allocated for retained color stops.
349    pub fn allocation_bytes(&self) -> usize {
350        self.stops
351            .capacity()
352            .saturating_mul(std::mem::size_of::<ColorStop>())
353    }
354
355    /// Samples the map, clamping a finite normalized input to its endpoints.
356    pub fn sample(&self, value: f32) -> Result<Color, ColorMapError> {
357        if !value.is_finite() {
358            return Err(ColorMapError::NonFiniteSample);
359        }
360        Ok(self.sample_normalized(value))
361    }
362
363    pub(crate) fn sample_normalized(&self, value: f32) -> Color {
364        let value = value.clamp(0.0, 1.0);
365        let upper = self.stops.partition_point(|stop| stop.position < value);
366        if upper == 0 {
367            return self.stops[0].color;
368        }
369        if upper == self.stops.len() {
370            return self.stops[upper - 1].color;
371        }
372        let start = self.stops[upper - 1];
373        let end = self.stops[upper];
374        let amount = (value - start.position) / (end.position - start.position);
375        Color::rgba(
376            start.color.red() + (end.color.red() - start.color.red()) * amount,
377            start.color.green() + (end.color.green() - start.color.green()) * amount,
378            start.color.blue() + (end.color.blue() - start.color.blue()) * amount,
379            start.color.alpha() + (end.color.alpha() - start.color.alpha()) * amount,
380        )
381    }
382}
383
384/// Rejection reason for color-map construction or sampling.
385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
386pub enum ColorMapError {
387    /// A stop position or color channel was NaN or infinite.
388    NonFiniteStop,
389    /// A stop position was outside `0.0..=1.0`.
390    PositionOutOfRange,
391    /// A linear RGBA stop color had a channel outside `0.0..=1.0`.
392    ColorOutOfRange,
393    /// A map needs at least two stops.
394    TooFewStops,
395    /// Stops must have strictly increasing positions.
396    StopsNotIncreasing,
397    /// A sampled normalized value was NaN or infinite.
398    NonFiniteSample,
399}
400
401impl fmt::Display for ColorMapError {
402    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
403        write!(formatter, "{self:?}")
404    }
405}
406
407impl Error for ColorMapError {}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412
413    #[test]
414    fn scalar_field_validates_shape_finiteness_and_updates() {
415        let mut field = ScalarField::new(2, 2, vec![1.0, -3.0, 2.0, 4.0]).unwrap();
416        assert_eq!(field.value_range(), (-3.0, 4.0));
417        field.set(1, 0, 6.0).unwrap();
418        assert_eq!(field.value_at(1, 0), Some(6.0));
419        assert_eq!(
420            field.set(2, 0, 0.0),
421            Err(ScalarFieldError::OutOfBounds { x: 2, y: 0 })
422        );
423        assert_eq!(
424            ScalarField::filled(0, 1, 0.0),
425            Err(ScalarFieldError::ZeroDimension)
426        );
427        assert_eq!(
428            ScalarField::new(2, 2, vec![0.0; 3]),
429            Err(ScalarFieldError::InvalidValueCount {
430                expected: 4,
431                actual: 3
432            })
433        );
434        assert_eq!(
435            ScalarField::filled(1, 1, f32::NAN),
436            Err(ScalarFieldError::NonFiniteValue)
437        );
438        assert_eq!(
439            ScalarField::filled(usize::MAX, 1, 0.0),
440            Err(ScalarFieldError::DimensionsOverflow)
441        );
442        let first_over_default_limit =
443            ScalarField::DEFAULT_MAX_FILLED_BYTES / std::mem::size_of::<f32>() + 1;
444        assert_eq!(
445            ScalarField::filled(first_over_default_limit, 1, 0.0),
446            Err(ScalarFieldError::AllocationLimitExceeded {
447                requested_bytes: first_over_default_limit * std::mem::size_of::<f32>(),
448                maximum_bytes: ScalarField::DEFAULT_MAX_FILLED_BYTES,
449            })
450        );
451        assert_eq!(
452            ScalarField::filled_with_byte_limit(2, 2, 0.0, 15),
453            Err(ScalarFieldError::AllocationLimitExceeded {
454                requested_bytes: 16,
455                maximum_bytes: 15,
456            })
457        );
458        assert_eq!(
459            ScalarField::filled_with_byte_limit(2, 2, 3.0, 16)
460                .unwrap()
461                .values(),
462            &[3.0; 4]
463        );
464        let first_vector_capacity_overflow = isize::MAX as usize / std::mem::size_of::<f32>() + 1;
465        assert_eq!(
466            ScalarField::filled_with_byte_limit(first_vector_capacity_overflow, 1, 0.0, usize::MAX,),
467            Err(ScalarFieldError::AllocationFailed {
468                requested_bytes: first_vector_capacity_overflow * std::mem::size_of::<f32>(),
469            })
470        );
471        field.replace_region(0, 1, 2, 1, &[7.0, 8.0]).unwrap();
472        assert_eq!(field.values(), &[1.0, 6.0, 7.0, 8.0]);
473        assert_eq!(
474            field.replace_region(1, 1, 2, 1, &[0.0, 1.0]),
475            Err(ScalarFieldError::OutOfBounds { x: 1, y: 1 })
476        );
477        assert_eq!(
478            field.replace_region(0, 0, 1, 2, &[0.0]),
479            Err(ScalarFieldError::InvalidValueCount {
480                expected: 2,
481                actual: 1
482            })
483        );
484        assert_eq!(
485            field.replace_region(0, 0, 1, 1, &[f32::INFINITY]),
486            Err(ScalarFieldError::NonFiniteValue)
487        );
488    }
489
490    #[test]
491    fn color_map_interpolates_and_rejects_invalid_contracts() {
492        let map = ColorMap::linear(Color::BLACK, Color::WHITE).unwrap();
493        assert_eq!(map.sample(-1.0).unwrap(), Color::BLACK);
494        assert_eq!(map.sample(2.0).unwrap(), Color::WHITE);
495        assert_eq!(map.sample(0.5).unwrap(), Color::rgba(0.5, 0.5, 0.5, 1.0));
496        assert_eq!(map.sample(f32::NAN), Err(ColorMapError::NonFiniteSample));
497        let first = ColorStop::new(0.75, Color::WHITE).unwrap();
498        let second = ColorStop::new(0.5, Color::BLACK).unwrap();
499        assert_eq!(
500            ColorMap::new(vec![first, second]),
501            Err(ColorMapError::StopsNotIncreasing)
502        );
503        assert_eq!(
504            ColorStop::new(0.5, Color::rgba(1.1, 0.0, 0.0, 1.0)),
505            Err(ColorMapError::ColorOutOfRange)
506        );
507    }
508}