1use std::{error::Error, fmt};
2
3use crate::Color;
4
5#[derive(Debug, Clone, PartialEq)]
7pub struct ScalarField {
8 width: usize,
9 height: usize,
10 values: Vec<f32>,
11}
12
13impl ScalarField {
14 pub const DEFAULT_MAX_FILLED_BYTES: usize = 256 * 1024 * 1024;
20
21 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 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 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 pub fn width(&self) -> usize {
94 self.width
95 }
96
97 pub fn height(&self) -> usize {
99 self.height
100 }
101
102 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 pub fn value_at(&self, x: usize, y: usize) -> Option<f32> {
116 self.index(x, y).map(|index| self.values[index])
117 }
118
119 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum ScalarFieldError {
211 ZeroDimension,
213 DimensionsOverflow,
215 InvalidValueCount {
217 expected: usize,
219 actual: usize,
221 },
222 NonFiniteValue,
224 AllocationLimitExceeded {
226 requested_bytes: usize,
228 maximum_bytes: usize,
230 },
231 AllocationFailed {
233 requested_bytes: usize,
235 },
236 OutOfBounds {
238 x: usize,
240 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#[derive(Debug, Clone, Copy, PartialEq)]
279pub struct ColorStop {
280 position: f32,
281 color: Color,
282}
283
284impl ColorStop {
285 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 pub fn position(self) -> f32 {
304 self.position
305 }
306
307 pub fn color(self) -> Color {
309 self.color
310 }
311}
312
313#[derive(Debug, Clone, PartialEq)]
319pub struct ColorMap {
320 stops: Vec<ColorStop>,
321}
322
323impl ColorMap {
324 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 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 pub fn stops(&self) -> &[ColorStop] {
345 &self.stops
346 }
347
348 pub fn allocation_bytes(&self) -> usize {
350 self.stops
351 .capacity()
352 .saturating_mul(std::mem::size_of::<ColorStop>())
353 }
354
355 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
386pub enum ColorMapError {
387 NonFiniteStop,
389 PositionOutOfRange,
391 ColorOutOfRange,
393 TooFewStops,
395 StopsNotIncreasing,
397 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}