ferravex_play/ui/
meters.rs

1//! Bounded horizontal meter geometry in logical UI units, without rendering,
2//! clocks, input, smoothing, allocation or gameplay availability decisions.
3//!
4//! Values are validated, never clamped. `Empty` explicitly means no capacity;
5//! it differs from a known zero with a positive capacity and from `Unknown`.
6//! A known zero denominator is rejected; callers must choose `Empty` or
7//! `Unknown`. Geometry rounds to f32 logical units, not simulation precision.
8//!
9//! ```
10//! use ferravex_play::ui::{Rect, meters::*};
11//! let track = Rect { min: [-10., 2.5], size: [120., 8.] };
12//! let meter = MeterGeometry::new(track,
13//!     MeterValue::Known { current: 3., capacity: 6. })?;
14//! assert_eq!(meter.fill().unwrap().size, [60., 8.]);
15//! let mut markers = [track; MAX_METER_MARKERS];
16//! assert_eq!(meter.markers_into(&[0., 0.25, 1.], 2., &mut markers)?, 3);
17//! assert_eq!(markers[0].min[0], -10.);
18//! assert_eq!(markers[2].min[0] + markers[2].size[0], 110.);
19//! # Ok::<(), MeterError>(())
20//! ```
21use super::Rect;
22
23/// Maximum explicit thresholds per continuous meter.
24pub const MAX_METER_MARKERS: usize = 16;
25/// Maximum segments per strip; callers must choose a smaller representation
26/// explicitly when their telemetry exceeds this bound.
27pub const MAX_METER_SEGMENTS: usize = 64;
28
29/// Supplied telemetry. `Unknown` has no implied fraction; `Empty` fills zero.
30#[derive(Clone, Copy, Debug, PartialEq)]
31pub enum MeterValue {
32    Known { current: f64, capacity: f64 },
33    Empty,
34    Unknown,
35}
36impl MeterValue {
37    /// Validate finite `0 <= current <= capacity`, `capacity > 0`. Returns
38    /// `Some(0)` for Empty, `None` for Unknown. Underflow to a false zero rejects.
39    pub fn fraction(self) -> Result<Option<f64>, MeterError> {
40        match self {
41            Self::Known { current, capacity } => {
42                if !current.is_finite()
43                    || !capacity.is_finite()
44                    || capacity <= 0.
45                    || current < 0.
46                    || current > capacity
47                {
48                    return Err(MeterError::InvalidValue);
49                }
50                let fraction = current / capacity;
51                if current > 0. && fraction == 0. {
52                    return Err(MeterError::InvalidValue);
53                }
54                Ok(Some(fraction))
55            }
56            Self::Empty => Ok(Some(0.)),
57            Self::Unknown => Ok(None),
58        }
59    }
60}
61
62/// Count telemetry, with no fractional/invented segments. Empty has zero cells;
63/// Unknown may reserve zero through 64 cells, without marking any as accepted.
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum SegmentValue {
66    Known { filled: usize, capacity: usize },
67    Empty,
68    Unknown { capacity: usize },
69}
70impl SegmentValue {
71    /// Validated cell count. Known requires positive capacity and filled <= it.
72    pub fn count(self) -> Result<usize, MeterError> {
73        let count = match self {
74            Self::Known { filled, capacity } => {
75                if capacity == 0 || filled > capacity {
76                    return Err(MeterError::InvalidValue);
77                }
78                capacity
79            }
80            Self::Empty => 0,
81            Self::Unknown { capacity } => capacity,
82        };
83        if count > MAX_METER_SEGMENTS {
84            return Err(MeterError::Capacity);
85        }
86        Ok(count)
87    }
88}
89
90/// Validation/capacity errors are reported before changing caller buffers.
91#[derive(Clone, Copy, Debug, PartialEq, Eq)]
92pub enum MeterError {
93    InvalidValue,
94    InvalidGeometry,
95    Capacity,
96}
97impl std::fmt::Display for MeterError {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        f.write_str(match self {
100            Self::InvalidValue => "invalid meter telemetry",
101            Self::InvalidGeometry => "invalid or unrepresentable meter geometry",
102            Self::Capacity => "meter capacity exceeded",
103        })
104    }
105}
106impl std::error::Error for MeterError {}
107
108/// Immutable continuous geometry. Zero extents are valid (and paint nothing);
109/// positive extents must have representable edges. Negative origins are valid.
110#[derive(Clone, Copy, Debug, PartialEq)]
111pub struct MeterGeometry {
112    bounds: Rect,
113    value: MeterValue,
114    fill: Option<Rect>,
115}
116impl MeterGeometry {
117    pub fn new(bounds: Rect, value: MeterValue) -> Result<Self, MeterError> {
118        valid(bounds)?;
119        let fill = value
120            .fraction()?
121            .map(|fraction| {
122                let width = (f64::from(bounds.size[0]) * fraction) as f32;
123                if fraction > 0. && bounds.size[0] > 0. && width == 0. {
124                    return Err(MeterError::InvalidGeometry);
125                }
126                let rect = Rect {
127                    size: [width, bounds.size[1]],
128                    ..bounds
129                };
130                inside(bounds, rect)?;
131                Ok(rect)
132            })
133            .transpose()?;
134        Ok(Self {
135            bounds,
136            value,
137            fill,
138        })
139    }
140    pub fn bounds(self) -> Rect {
141        self.bounds
142    }
143    pub fn value(self) -> MeterValue {
144        self.value
145    }
146    pub fn fill(self) -> Option<Rect> {
147        self.fill
148    }
149
150    /// Write threshold rectangles inside the track. Fractions must be finite
151    /// in 0..=1, width positive and no wider than the track. Marker centers follow
152    /// fraction * width; endpoint marks move inward just enough to fit. No value
153    /// is clamped. All validation precedes writes; unused output stays unchanged.
154    /// Empty input succeeds even on a zero-width track (width still validates).
155    pub fn markers_into(
156        self,
157        fractions: &[f64],
158        width: f32,
159        output: &mut [Rect],
160    ) -> Result<usize, MeterError> {
161        if fractions.len() > MAX_METER_MARKERS || output.len() < fractions.len() {
162            return Err(MeterError::Capacity);
163        }
164        if !width.is_finite()
165            || width <= 0.
166            || (!fractions.is_empty() && width > self.bounds.size[0])
167        {
168            return Err(MeterError::InvalidGeometry);
169        }
170        let mut checked = [self.bounds; MAX_METER_MARKERS];
171        for (i, &fraction) in fractions.iter().enumerate() {
172            if !fraction.is_finite() || !(0. ..=1.).contains(&fraction) {
173                return Err(MeterError::InvalidValue);
174            }
175            let offset = (f64::from(self.bounds.size[0]) * fraction - f64::from(width) / 2.)
176                .max(0.)
177                .min(f64::from(self.bounds.size[0] - width));
178            let r = Rect {
179                min: [
180                    (f64::from(self.bounds.min[0]) + offset) as f32,
181                    self.bounds.min[1],
182                ],
183                size: [width, self.bounds.size[1]],
184            };
185            inside(self.bounds, r)?;
186            checked[i] = r;
187        }
188        output[..fractions.len()].copy_from_slice(&checked[..fractions.len()]);
189        Ok(fractions.len())
190    }
191}
192
193/// Geometry and accepted-count state for one cell; Unknown has filled=false,
194/// and must be distinguished by the enclosing SegmentGeometry::value.
195#[derive(Clone, Copy, Debug, PartialEq)]
196pub struct SegmentRect {
197    pub bounds: Rect,
198    pub filled: bool,
199}
200
201/// Immutable strip descriptor; results use caller-owned storage.
202///
203/// ```
204/// use ferravex_play::ui::{Rect, meters::*};
205/// let r = Rect { min: [0.; 2], size: [118., 10.] };
206/// let strip = SegmentGeometry::new(r,
207///     SegmentValue::Known { filled: 2, capacity: 6 }, 2.)?;
208/// let mut cells = [SegmentRect { bounds: r, filled: false }; MAX_METER_SEGMENTS];
209/// assert_eq!(strip.write_into(&mut cells)?, 6);
210/// assert_eq!(cells[..6].iter().filter(|c| c.filled).count(), 2);
211/// assert_eq!(cells[5].bounds.min[0] + cells[5].bounds.size[0], 118.);
212/// # Ok::<(), MeterError>(())
213/// ```
214#[derive(Clone, Copy, Debug, PartialEq)]
215pub struct SegmentGeometry {
216    bounds: Rect,
217    value: SegmentValue,
218    gap: f32,
219    count: usize,
220}
221impl SegmentGeometry {
222    pub fn new(bounds: Rect, value: SegmentValue, gap: f32) -> Result<Self, MeterError> {
223        valid(bounds)?;
224        let count = value.count()?;
225        if !gap.is_finite() || gap < 0. {
226            return Err(MeterError::InvalidGeometry);
227        }
228        let result = Self {
229            bounds,
230            value,
231            gap,
232            count,
233        };
234        // Validate every derived rectangle before returning a usable descriptor.
235        for i in 0..count {
236            result.cell(i)?;
237        }
238        Ok(result)
239    }
240    pub fn bounds(self) -> Rect {
241        self.bounds
242    }
243    pub fn value(self) -> SegmentValue {
244        self.value
245    }
246    pub fn count(self) -> usize {
247        self.count
248    }
249    /// Full prevalidation and output-length check precede writes. The output
250    /// tail is unchanged on success, and the entire slice is unchanged on error.
251    pub fn write_into(self, output: &mut [SegmentRect]) -> Result<usize, MeterError> {
252        if output.len() < self.count {
253            return Err(MeterError::Capacity);
254        }
255        for (i, dest) in output[..self.count].iter_mut().enumerate() {
256            // Constructor checked these immutable inputs already.
257            *dest = self.cell(i).expect("validated immutable segment geometry");
258        }
259        Ok(self.count)
260    }
261    fn cell(self, index: usize) -> Result<SegmentRect, MeterError> {
262        let width = (f64::from(self.bounds.size[0])
263            - f64::from(self.gap) * (self.count - 1) as f64)
264            / self.count as f64;
265        if width <= 0. || !width.is_finite() {
266            return Err(MeterError::InvalidGeometry);
267        }
268        let left =
269            (f64::from(self.bounds.min[0]) + (width + f64::from(self.gap)) * index as f64) as f32;
270        let right = if index + 1 == self.count {
271            self.bounds.min[0] + self.bounds.size[0]
272        } else {
273            (f64::from(self.bounds.min[0]) + (width + f64::from(self.gap)) * index as f64 + width)
274                as f32
275        };
276        let bounds = Rect {
277            min: [left, self.bounds.min[1]],
278            size: [right - left, self.bounds.size[1]],
279        };
280        if bounds.size[0] <= 0. {
281            return Err(MeterError::InvalidGeometry);
282        }
283        inside(self.bounds, bounds)?;
284        Ok(SegmentRect {
285            bounds,
286            filled: matches!(self.value, SegmentValue::Known { filled, .. } if index < filled),
287        })
288    }
289}
290
291fn valid(rect: Rect) -> Result<(), MeterError> {
292    if !rect.valid()
293        || (0..2).any(|i| rect.size[i] > 0. && rect.min[i] + rect.size[i] <= rect.min[i])
294    {
295        Err(MeterError::InvalidGeometry)
296    } else {
297        Ok(())
298    }
299}
300fn inside(parent: Rect, rect: Rect) -> Result<(), MeterError> {
301    valid(rect)?;
302    if (0..2).any(|i| {
303        rect.min[i] < parent.min[i] || rect.min[i] + rect.size[i] > parent.min[i] + parent.size[i]
304    }) {
305        Err(MeterError::InvalidGeometry)
306    } else {
307        Ok(())
308    }
309}