use std::{error::Error, fmt};
use crate::Color;
#[derive(Debug, Clone, PartialEq)]
pub struct ScalarField {
width: usize,
height: usize,
values: Vec<f32>,
}
impl ScalarField {
pub const DEFAULT_MAX_FILLED_BYTES: usize = 256 * 1024 * 1024;
pub fn new(width: usize, height: usize, values: Vec<f32>) -> Result<Self, ScalarFieldError> {
let expected_len = checked_len(width, height)?;
if values.len() != expected_len {
return Err(ScalarFieldError::InvalidValueCount {
expected: expected_len,
actual: values.len(),
});
}
if values.iter().any(|value| !value.is_finite()) {
return Err(ScalarFieldError::NonFiniteValue);
}
Ok(Self {
width,
height,
values,
})
}
pub fn filled(width: usize, height: usize, value: f32) -> Result<Self, ScalarFieldError> {
Self::filled_with_byte_limit(width, height, value, Self::DEFAULT_MAX_FILLED_BYTES)
}
pub fn filled_with_byte_limit(
width: usize,
height: usize,
value: f32,
maximum_bytes: usize,
) -> Result<Self, ScalarFieldError> {
let len = checked_len(width, height)?;
if !value.is_finite() {
return Err(ScalarFieldError::NonFiniteValue);
}
let requested_bytes = len
.checked_mul(std::mem::size_of::<f32>())
.ok_or(ScalarFieldError::DimensionsOverflow)?;
if requested_bytes > maximum_bytes {
return Err(ScalarFieldError::AllocationLimitExceeded {
requested_bytes,
maximum_bytes,
});
}
let mut values = Vec::new();
values
.try_reserve_exact(len)
.map_err(|_| ScalarFieldError::AllocationFailed { requested_bytes })?;
let actual_bytes = values.capacity().saturating_mul(std::mem::size_of::<f32>());
if actual_bytes > maximum_bytes {
return Err(ScalarFieldError::AllocationLimitExceeded {
requested_bytes: actual_bytes,
maximum_bytes,
});
}
values.resize(len, value);
Ok(Self {
width,
height,
values,
})
}
pub fn width(&self) -> usize {
self.width
}
pub fn height(&self) -> usize {
self.height
}
pub fn values(&self) -> &[f32] {
&self.values
}
#[cfg(feature = "wgpu")]
pub(crate) fn value_allocation_bytes(&self) -> usize {
self.values
.capacity()
.saturating_mul(std::mem::size_of::<f32>())
}
pub fn value_at(&self, x: usize, y: usize) -> Option<f32> {
self.index(x, y).map(|index| self.values[index])
}
pub fn set(&mut self, x: usize, y: usize, value: f32) -> Result<(), ScalarFieldError> {
if !value.is_finite() {
return Err(ScalarFieldError::NonFiniteValue);
}
let index = self
.index(x, y)
.ok_or(ScalarFieldError::OutOfBounds { x, y })?;
self.values[index] = value;
Ok(())
}
pub fn replace_values(&mut self, values: Vec<f32>) -> Result<(), ScalarFieldError> {
if values.len() != self.values.len() {
return Err(ScalarFieldError::InvalidValueCount {
expected: self.values.len(),
actual: values.len(),
});
}
if values.iter().any(|value| !value.is_finite()) {
return Err(ScalarFieldError::NonFiniteValue);
}
self.values = values;
Ok(())
}
pub fn replace_region(
&mut self,
x: usize,
y: usize,
width: usize,
height: usize,
values: &[f32],
) -> Result<(), ScalarFieldError> {
let expected = checked_len(width, height)?;
if values.len() != expected {
return Err(ScalarFieldError::InvalidValueCount {
expected,
actual: values.len(),
});
}
if values.iter().any(|value| !value.is_finite()) {
return Err(ScalarFieldError::NonFiniteValue);
}
let end_x = x
.checked_add(width)
.ok_or(ScalarFieldError::OutOfBounds { x, y })?;
let end_y = y
.checked_add(height)
.ok_or(ScalarFieldError::OutOfBounds { x, y })?;
if end_x > self.width || end_y > self.height {
return Err(ScalarFieldError::OutOfBounds { x, y });
}
for row in 0..height {
let destination = (y + row) * self.width + x;
let source = row * width;
self.values[destination..destination + width]
.copy_from_slice(&values[source..source + width]);
}
Ok(())
}
pub fn value_range(&self) -> (f32, f32) {
let mut minimum = self.values[0];
let mut maximum = minimum;
for value in &self.values[1..] {
minimum = minimum.min(*value);
maximum = maximum.max(*value);
}
(minimum, maximum)
}
fn index(&self, x: usize, y: usize) -> Option<usize> {
(x < self.width && y < self.height).then_some(y * self.width + x)
}
}
fn checked_len(width: usize, height: usize) -> Result<usize, ScalarFieldError> {
if width == 0 || height == 0 {
return Err(ScalarFieldError::ZeroDimension);
}
width
.checked_mul(height)
.ok_or(ScalarFieldError::DimensionsOverflow)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScalarFieldError {
ZeroDimension,
DimensionsOverflow,
InvalidValueCount {
expected: usize,
actual: usize,
},
NonFiniteValue,
AllocationLimitExceeded {
requested_bytes: usize,
maximum_bytes: usize,
},
AllocationFailed {
requested_bytes: usize,
},
OutOfBounds {
x: usize,
y: usize,
},
}
impl fmt::Display for ScalarFieldError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ZeroDimension => write!(formatter, "scalar field dimensions must be non-zero"),
Self::DimensionsOverflow => write!(formatter, "scalar field dimensions overflow"),
Self::InvalidValueCount { expected, actual } => {
write!(
formatter,
"scalar field needs {expected} values, got {actual}"
)
}
Self::NonFiniteValue => write!(formatter, "scalar field values must be finite"),
Self::AllocationLimitExceeded {
requested_bytes,
maximum_bytes,
} => write!(
formatter,
"scalar field needs {requested_bytes} bytes, exceeding the {maximum_bytes}-byte allocation limit"
),
Self::AllocationFailed { requested_bytes } => write!(
formatter,
"scalar field could not reserve {requested_bytes} bytes"
),
Self::OutOfBounds { x, y } => {
write!(formatter, "scalar field cell ({x}, {y}) is out of bounds")
}
}
}
}
impl Error for ScalarFieldError {}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ColorStop {
position: f32,
color: Color,
}
impl ColorStop {
pub fn new(position: f32, color: Color) -> Result<Self, ColorMapError> {
if !position.is_finite() || !color.is_finite() {
return Err(ColorMapError::NonFiniteStop);
}
if !(0.0..=1.0).contains(&position) {
return Err(ColorMapError::PositionOutOfRange);
}
if !color.is_normalized() {
return Err(ColorMapError::ColorOutOfRange);
}
Ok(Self { position, color })
}
pub fn position(self) -> f32 {
self.position
}
pub fn color(self) -> Color {
self.color
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ColorMap {
stops: Vec<ColorStop>,
}
impl ColorMap {
pub fn new(stops: Vec<ColorStop>) -> Result<Self, ColorMapError> {
if stops.len() < 2 {
return Err(ColorMapError::TooFewStops);
}
if stops
.windows(2)
.any(|pair| pair[0].position >= pair[1].position)
{
return Err(ColorMapError::StopsNotIncreasing);
}
Ok(Self { stops })
}
pub fn linear(start: Color, end: Color) -> Result<Self, ColorMapError> {
Self::new(vec![ColorStop::new(0.0, start)?, ColorStop::new(1.0, end)?])
}
pub fn stops(&self) -> &[ColorStop] {
&self.stops
}
pub fn allocation_bytes(&self) -> usize {
self.stops
.capacity()
.saturating_mul(std::mem::size_of::<ColorStop>())
}
pub fn sample(&self, value: f32) -> Result<Color, ColorMapError> {
if !value.is_finite() {
return Err(ColorMapError::NonFiniteSample);
}
Ok(self.sample_normalized(value))
}
pub(crate) fn sample_normalized(&self, value: f32) -> Color {
let value = value.clamp(0.0, 1.0);
let upper = self.stops.partition_point(|stop| stop.position < value);
if upper == 0 {
return self.stops[0].color;
}
if upper == self.stops.len() {
return self.stops[upper - 1].color;
}
let start = self.stops[upper - 1];
let end = self.stops[upper];
let amount = (value - start.position) / (end.position - start.position);
Color::rgba(
start.color.red() + (end.color.red() - start.color.red()) * amount,
start.color.green() + (end.color.green() - start.color.green()) * amount,
start.color.blue() + (end.color.blue() - start.color.blue()) * amount,
start.color.alpha() + (end.color.alpha() - start.color.alpha()) * amount,
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorMapError {
NonFiniteStop,
PositionOutOfRange,
ColorOutOfRange,
TooFewStops,
StopsNotIncreasing,
NonFiniteSample,
}
impl fmt::Display for ColorMapError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{self:?}")
}
}
impl Error for ColorMapError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scalar_field_validates_shape_finiteness_and_updates() {
let mut field = ScalarField::new(2, 2, vec![1.0, -3.0, 2.0, 4.0]).unwrap();
assert_eq!(field.value_range(), (-3.0, 4.0));
field.set(1, 0, 6.0).unwrap();
assert_eq!(field.value_at(1, 0), Some(6.0));
assert_eq!(
field.set(2, 0, 0.0),
Err(ScalarFieldError::OutOfBounds { x: 2, y: 0 })
);
assert_eq!(
ScalarField::filled(0, 1, 0.0),
Err(ScalarFieldError::ZeroDimension)
);
assert_eq!(
ScalarField::new(2, 2, vec![0.0; 3]),
Err(ScalarFieldError::InvalidValueCount {
expected: 4,
actual: 3
})
);
assert_eq!(
ScalarField::filled(1, 1, f32::NAN),
Err(ScalarFieldError::NonFiniteValue)
);
assert_eq!(
ScalarField::filled(usize::MAX, 1, 0.0),
Err(ScalarFieldError::DimensionsOverflow)
);
let first_over_default_limit =
ScalarField::DEFAULT_MAX_FILLED_BYTES / std::mem::size_of::<f32>() + 1;
assert_eq!(
ScalarField::filled(first_over_default_limit, 1, 0.0),
Err(ScalarFieldError::AllocationLimitExceeded {
requested_bytes: first_over_default_limit * std::mem::size_of::<f32>(),
maximum_bytes: ScalarField::DEFAULT_MAX_FILLED_BYTES,
})
);
assert_eq!(
ScalarField::filled_with_byte_limit(2, 2, 0.0, 15),
Err(ScalarFieldError::AllocationLimitExceeded {
requested_bytes: 16,
maximum_bytes: 15,
})
);
assert_eq!(
ScalarField::filled_with_byte_limit(2, 2, 3.0, 16)
.unwrap()
.values(),
&[3.0; 4]
);
let first_vector_capacity_overflow = isize::MAX as usize / std::mem::size_of::<f32>() + 1;
assert_eq!(
ScalarField::filled_with_byte_limit(first_vector_capacity_overflow, 1, 0.0, usize::MAX,),
Err(ScalarFieldError::AllocationFailed {
requested_bytes: first_vector_capacity_overflow * std::mem::size_of::<f32>(),
})
);
field.replace_region(0, 1, 2, 1, &[7.0, 8.0]).unwrap();
assert_eq!(field.values(), &[1.0, 6.0, 7.0, 8.0]);
assert_eq!(
field.replace_region(1, 1, 2, 1, &[0.0, 1.0]),
Err(ScalarFieldError::OutOfBounds { x: 1, y: 1 })
);
assert_eq!(
field.replace_region(0, 0, 1, 2, &[0.0]),
Err(ScalarFieldError::InvalidValueCount {
expected: 2,
actual: 1
})
);
assert_eq!(
field.replace_region(0, 0, 1, 1, &[f32::INFINITY]),
Err(ScalarFieldError::NonFiniteValue)
);
}
#[test]
fn color_map_interpolates_and_rejects_invalid_contracts() {
let map = ColorMap::linear(Color::BLACK, Color::WHITE).unwrap();
assert_eq!(map.sample(-1.0).unwrap(), Color::BLACK);
assert_eq!(map.sample(2.0).unwrap(), Color::WHITE);
assert_eq!(map.sample(0.5).unwrap(), Color::rgba(0.5, 0.5, 0.5, 1.0));
assert_eq!(map.sample(f32::NAN), Err(ColorMapError::NonFiniteSample));
let first = ColorStop::new(0.75, Color::WHITE).unwrap();
let second = ColorStop::new(0.5, Color::BLACK).unwrap();
assert_eq!(
ColorMap::new(vec![first, second]),
Err(ColorMapError::StopsNotIncreasing)
);
assert_eq!(
ColorStop::new(0.5, Color::rgba(1.1, 0.0, 0.0, 1.0)),
Err(ColorMapError::ColorOutOfRange)
);
}
}