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 values.resize(len, value);
78 Ok(Self {
79 width,
80 height,
81 values,
82 })
83 }
84
85 pub fn width(&self) -> usize {
87 self.width
88 }
89
90 pub fn height(&self) -> usize {
92 self.height
93 }
94
95 pub fn values(&self) -> &[f32] {
97 &self.values
98 }
99
100 pub fn value_at(&self, x: usize, y: usize) -> Option<f32> {
102 self.index(x, y).map(|index| self.values[index])
103 }
104
105 pub fn set(&mut self, x: usize, y: usize, value: f32) -> Result<(), ScalarFieldError> {
107 if !value.is_finite() {
108 return Err(ScalarFieldError::NonFiniteValue);
109 }
110 let index = self
111 .index(x, y)
112 .ok_or(ScalarFieldError::OutOfBounds { x, y })?;
113 self.values[index] = value;
114 Ok(())
115 }
116
117 pub fn replace_values(&mut self, values: Vec<f32>) -> Result<(), ScalarFieldError> {
119 if values.len() != self.values.len() {
120 return Err(ScalarFieldError::InvalidValueCount {
121 expected: self.values.len(),
122 actual: values.len(),
123 });
124 }
125 if values.iter().any(|value| !value.is_finite()) {
126 return Err(ScalarFieldError::NonFiniteValue);
127 }
128 self.values = values;
129 Ok(())
130 }
131
132 pub fn replace_region(
134 &mut self,
135 x: usize,
136 y: usize,
137 width: usize,
138 height: usize,
139 values: &[f32],
140 ) -> Result<(), ScalarFieldError> {
141 let expected = checked_len(width, height)?;
142 if values.len() != expected {
143 return Err(ScalarFieldError::InvalidValueCount {
144 expected,
145 actual: values.len(),
146 });
147 }
148 if values.iter().any(|value| !value.is_finite()) {
149 return Err(ScalarFieldError::NonFiniteValue);
150 }
151 let end_x = x
152 .checked_add(width)
153 .ok_or(ScalarFieldError::OutOfBounds { x, y })?;
154 let end_y = y
155 .checked_add(height)
156 .ok_or(ScalarFieldError::OutOfBounds { x, y })?;
157 if end_x > self.width || end_y > self.height {
158 return Err(ScalarFieldError::OutOfBounds { x, y });
159 }
160 for row in 0..height {
161 let destination = (y + row) * self.width + x;
162 let source = row * width;
163 self.values[destination..destination + width]
164 .copy_from_slice(&values[source..source + width]);
165 }
166 Ok(())
167 }
168
169 pub fn value_range(&self) -> (f32, f32) {
171 let mut minimum = self.values[0];
172 let mut maximum = minimum;
173 for value in &self.values[1..] {
174 minimum = minimum.min(*value);
175 maximum = maximum.max(*value);
176 }
177 (minimum, maximum)
178 }
179
180 fn index(&self, x: usize, y: usize) -> Option<usize> {
181 (x < self.width && y < self.height).then_some(y * self.width + x)
182 }
183}
184
185fn checked_len(width: usize, height: usize) -> Result<usize, ScalarFieldError> {
186 if width == 0 || height == 0 {
187 return Err(ScalarFieldError::ZeroDimension);
188 }
189 width
190 .checked_mul(height)
191 .ok_or(ScalarFieldError::DimensionsOverflow)
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum ScalarFieldError {
197 ZeroDimension,
199 DimensionsOverflow,
201 InvalidValueCount {
203 expected: usize,
205 actual: usize,
207 },
208 NonFiniteValue,
210 AllocationLimitExceeded {
212 requested_bytes: usize,
214 maximum_bytes: usize,
216 },
217 AllocationFailed {
219 requested_bytes: usize,
221 },
222 OutOfBounds {
224 x: usize,
226 y: usize,
228 },
229}
230
231impl fmt::Display for ScalarFieldError {
232 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
233 match self {
234 Self::ZeroDimension => write!(formatter, "scalar field dimensions must be non-zero"),
235 Self::DimensionsOverflow => write!(formatter, "scalar field dimensions overflow"),
236 Self::InvalidValueCount { expected, actual } => {
237 write!(
238 formatter,
239 "scalar field needs {expected} values, got {actual}"
240 )
241 }
242 Self::NonFiniteValue => write!(formatter, "scalar field values must be finite"),
243 Self::AllocationLimitExceeded {
244 requested_bytes,
245 maximum_bytes,
246 } => write!(
247 formatter,
248 "scalar field needs {requested_bytes} bytes, exceeding the {maximum_bytes}-byte allocation limit"
249 ),
250 Self::AllocationFailed { requested_bytes } => write!(
251 formatter,
252 "scalar field could not reserve {requested_bytes} bytes"
253 ),
254 Self::OutOfBounds { x, y } => {
255 write!(formatter, "scalar field cell ({x}, {y}) is out of bounds")
256 }
257 }
258 }
259}
260
261impl Error for ScalarFieldError {}
262
263#[derive(Debug, Clone, Copy, PartialEq)]
265pub struct ColorStop {
266 position: f32,
267 color: Color,
268}
269
270impl ColorStop {
271 pub fn new(position: f32, color: Color) -> Result<Self, ColorMapError> {
276 if !position.is_finite() || !color.is_finite() {
277 return Err(ColorMapError::NonFiniteStop);
278 }
279 if !(0.0..=1.0).contains(&position) {
280 return Err(ColorMapError::PositionOutOfRange);
281 }
282 if !color.is_normalized() {
283 return Err(ColorMapError::ColorOutOfRange);
284 }
285 Ok(Self { position, color })
286 }
287
288 pub fn position(self) -> f32 {
290 self.position
291 }
292
293 pub fn color(self) -> Color {
295 self.color
296 }
297}
298
299#[derive(Debug, Clone, PartialEq)]
305pub struct ColorMap {
306 stops: Vec<ColorStop>,
307}
308
309impl ColorMap {
310 pub fn new(stops: Vec<ColorStop>) -> Result<Self, ColorMapError> {
312 if stops.len() < 2 {
313 return Err(ColorMapError::TooFewStops);
314 }
315 if stops
316 .windows(2)
317 .any(|pair| pair[0].position >= pair[1].position)
318 {
319 return Err(ColorMapError::StopsNotIncreasing);
320 }
321 Ok(Self { stops })
322 }
323
324 pub fn linear(start: Color, end: Color) -> Result<Self, ColorMapError> {
326 Self::new(vec![ColorStop::new(0.0, start)?, ColorStop::new(1.0, end)?])
327 }
328
329 pub fn stops(&self) -> &[ColorStop] {
331 &self.stops
332 }
333
334 pub fn sample(&self, value: f32) -> Result<Color, ColorMapError> {
336 if !value.is_finite() {
337 return Err(ColorMapError::NonFiniteSample);
338 }
339 Ok(self.sample_normalized(value))
340 }
341
342 pub(crate) fn sample_normalized(&self, value: f32) -> Color {
343 let value = value.clamp(0.0, 1.0);
344 let upper = self.stops.partition_point(|stop| stop.position < value);
345 if upper == 0 {
346 return self.stops[0].color;
347 }
348 if upper == self.stops.len() {
349 return self.stops[upper - 1].color;
350 }
351 let start = self.stops[upper - 1];
352 let end = self.stops[upper];
353 let amount = (value - start.position) / (end.position - start.position);
354 Color::rgba(
355 start.color.red() + (end.color.red() - start.color.red()) * amount,
356 start.color.green() + (end.color.green() - start.color.green()) * amount,
357 start.color.blue() + (end.color.blue() - start.color.blue()) * amount,
358 start.color.alpha() + (end.color.alpha() - start.color.alpha()) * amount,
359 )
360 }
361}
362
363#[derive(Debug, Clone, Copy, PartialEq, Eq)]
365pub enum ColorMapError {
366 NonFiniteStop,
368 PositionOutOfRange,
370 ColorOutOfRange,
372 TooFewStops,
374 StopsNotIncreasing,
376 NonFiniteSample,
378}
379
380impl fmt::Display for ColorMapError {
381 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
382 write!(formatter, "{self:?}")
383 }
384}
385
386impl Error for ColorMapError {}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391
392 #[test]
393 fn scalar_field_validates_shape_finiteness_and_updates() {
394 let mut field = ScalarField::new(2, 2, vec![1.0, -3.0, 2.0, 4.0]).unwrap();
395 assert_eq!(field.value_range(), (-3.0, 4.0));
396 field.set(1, 0, 6.0).unwrap();
397 assert_eq!(field.value_at(1, 0), Some(6.0));
398 assert_eq!(
399 field.set(2, 0, 0.0),
400 Err(ScalarFieldError::OutOfBounds { x: 2, y: 0 })
401 );
402 assert_eq!(
403 ScalarField::filled(0, 1, 0.0),
404 Err(ScalarFieldError::ZeroDimension)
405 );
406 assert_eq!(
407 ScalarField::new(2, 2, vec![0.0; 3]),
408 Err(ScalarFieldError::InvalidValueCount {
409 expected: 4,
410 actual: 3
411 })
412 );
413 assert_eq!(
414 ScalarField::filled(1, 1, f32::NAN),
415 Err(ScalarFieldError::NonFiniteValue)
416 );
417 assert_eq!(
418 ScalarField::filled(usize::MAX, 1, 0.0),
419 Err(ScalarFieldError::DimensionsOverflow)
420 );
421 let first_over_default_limit =
422 ScalarField::DEFAULT_MAX_FILLED_BYTES / std::mem::size_of::<f32>() + 1;
423 assert_eq!(
424 ScalarField::filled(first_over_default_limit, 1, 0.0),
425 Err(ScalarFieldError::AllocationLimitExceeded {
426 requested_bytes: first_over_default_limit * std::mem::size_of::<f32>(),
427 maximum_bytes: ScalarField::DEFAULT_MAX_FILLED_BYTES,
428 })
429 );
430 assert_eq!(
431 ScalarField::filled_with_byte_limit(2, 2, 0.0, 15),
432 Err(ScalarFieldError::AllocationLimitExceeded {
433 requested_bytes: 16,
434 maximum_bytes: 15,
435 })
436 );
437 assert_eq!(
438 ScalarField::filled_with_byte_limit(2, 2, 3.0, 16)
439 .unwrap()
440 .values(),
441 &[3.0; 4]
442 );
443 let first_vector_capacity_overflow = isize::MAX as usize / std::mem::size_of::<f32>() + 1;
444 assert_eq!(
445 ScalarField::filled_with_byte_limit(first_vector_capacity_overflow, 1, 0.0, usize::MAX,),
446 Err(ScalarFieldError::AllocationFailed {
447 requested_bytes: first_vector_capacity_overflow * std::mem::size_of::<f32>(),
448 })
449 );
450 field.replace_region(0, 1, 2, 1, &[7.0, 8.0]).unwrap();
451 assert_eq!(field.values(), &[1.0, 6.0, 7.0, 8.0]);
452 assert_eq!(
453 field.replace_region(1, 1, 2, 1, &[0.0, 1.0]),
454 Err(ScalarFieldError::OutOfBounds { x: 1, y: 1 })
455 );
456 assert_eq!(
457 field.replace_region(0, 0, 1, 2, &[0.0]),
458 Err(ScalarFieldError::InvalidValueCount {
459 expected: 2,
460 actual: 1
461 })
462 );
463 assert_eq!(
464 field.replace_region(0, 0, 1, 1, &[f32::INFINITY]),
465 Err(ScalarFieldError::NonFiniteValue)
466 );
467 }
468
469 #[test]
470 fn color_map_interpolates_and_rejects_invalid_contracts() {
471 let map = ColorMap::linear(Color::BLACK, Color::WHITE).unwrap();
472 assert_eq!(map.sample(-1.0).unwrap(), Color::BLACK);
473 assert_eq!(map.sample(2.0).unwrap(), Color::WHITE);
474 assert_eq!(map.sample(0.5).unwrap(), Color::rgba(0.5, 0.5, 0.5, 1.0));
475 assert_eq!(map.sample(f32::NAN), Err(ColorMapError::NonFiniteSample));
476 let first = ColorStop::new(0.75, Color::WHITE).unwrap();
477 let second = ColorStop::new(0.5, Color::BLACK).unwrap();
478 assert_eq!(
479 ColorMap::new(vec![first, second]),
480 Err(ColorMapError::StopsNotIncreasing)
481 );
482 assert_eq!(
483 ColorStop::new(0.5, Color::rgba(1.1, 0.0, 0.0, 1.0)),
484 Err(ColorMapError::ColorOutOfRange)
485 );
486 }
487}