Skip to main content

crisol_plot/plot/three/
series.rs

1//! 3D series: lines, scatter clouds, vertical bars, and regular surfaces.
2
3use std::borrow::Cow;
4
5use egui::Color32;
6
7use super::super::axis::Scale;
8use super::super::series::{LineStyle, Marker};
9use super::types::Bounds3D;
10
11/// A regular surface: `x` columns, `y` rows, and row-major `z` values.
12#[derive(Clone, Debug, PartialEq)]
13pub struct Surface<'a> {
14    /// Column coordinates, left to right.
15    pub x: Cow<'a, [f64]>,
16    /// Row coordinates, back to front.
17    pub y: Cow<'a, [f64]>,
18    /// Height at `y * x.len() + x`, row-major.
19    pub z: Cow<'a, [f64]>,
20}
21
22impl Surface<'_> {
23    pub(super) fn columns(&self) -> usize {
24        self.x.len()
25    }
26
27    pub(super) fn rows(&self) -> usize {
28        self.y.len()
29    }
30
31    pub(super) fn point(&self, index: usize) -> Option<[f64; 3]> {
32        let columns = self.x.len();
33        if columns == 0 {
34            return None;
35        }
36        let column = index % columns;
37        let row = index / columns;
38        Some([*self.x.get(column)?, *self.y.get(row)?, *self.z.get(index)?])
39    }
40}
41
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
43pub(super) enum Kind3D {
44    Line,
45    Scatter,
46    Bars,
47    Surface,
48}
49
50/// One named 3D data set. Build it with [`Series3D::line`], [`Series3D::scatter`],
51/// [`Series3D::bars`], [`Series3D::surface`], or [`Series3D::surface_fn`], then add it
52/// to a [`super::Plot3D`].
53#[derive(Clone, Debug)]
54pub struct Series3D<'a> {
55    pub(super) name: String,
56    pub(super) data: Cow<'a, [[f64; 3]]>,
57    pub(super) surface: Option<Surface<'a>>,
58    pub(super) kind: Kind3D,
59    pub(super) color: Option<Color32>,
60    pub(super) legend: bool,
61    pub(super) width: f32,
62    pub(super) line_style: LineStyle,
63    pub(super) marker: Option<Marker>,
64    pub(super) radius: f32,
65    pub(super) bar_width: Option<f64>,
66    pub(super) base: f64,
67}
68
69impl<'a> Series3D<'a> {
70    fn new(name: impl Into<String>, data: Cow<'a, [[f64; 3]]>, kind: Kind3D) -> Self {
71        Self {
72            name: name.into(),
73            data,
74            surface: None,
75            kind,
76            color: None,
77            legend: true,
78            width: 1.6,
79            line_style: LineStyle::Solid,
80            marker: None,
81            radius: 3.0,
82            bar_width: None,
83            base: 0.0,
84        }
85    }
86
87    /// A polyline through `[x, y, z]` points, in order.
88    pub fn line(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 3]]>>) -> Self {
89        Self::new(name, data.into(), Kind3D::Line)
90    }
91
92    /// Unconnected 3D markers.
93    pub fn scatter(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 3]]>>) -> Self {
94        Self::new(name, data.into(), Kind3D::Scatter)
95    }
96
97    /// Vertical bars from the z base (0 by default) to each `[x, y, z]` point.
98    pub fn bars(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 3]]>>) -> Self {
99        Self::new(name, data.into(), Kind3D::Bars)
100    }
101
102    /// A surface over the grid `x × y` with row-major `z`.
103    ///
104    /// ```
105    /// # use crisol_plot::plot::{Plot3D, Plot3DState, Series3D};
106    /// # let ctx = egui::Context::default();
107    /// # let mut icons = crisol_plot::Icons::new();
108    /// let x = vec![-1.0, 0.0, 1.0];
109    /// let y = vec![-1.0, 0.0, 1.0];
110    /// let z = vec![0.0, 1.0, 0.0, 1.0, 2.0, 1.0, 0.0, 1.0, 0.0];
111    /// let mut state = Plot3DState::default();
112    /// # let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
113    /// Plot3D::new("terrain")
114    ///     .series(Series3D::surface("terrain", x.clone(), y.clone(), z.clone()))
115    ///     .show(ui, &mut icons, &mut state);
116    /// # });
117    /// # output.textures_delta.clear();
118    /// ```
119    pub fn surface(
120        name: impl Into<String>,
121        x: impl Into<Cow<'a, [f64]>>,
122        y: impl Into<Cow<'a, [f64]>>,
123        z: impl Into<Cow<'a, [f64]>>,
124    ) -> Self {
125        let surface = Surface {
126            x: x.into(),
127            y: y.into(),
128            z: z.into(),
129        };
130        let mut series = Self::new(name, Cow::Owned(Vec::new()), Kind3D::Surface);
131        series.surface = Some(surface);
132        series
133    }
134
135    /// A surface sampled `columns × rows` times over two ranges.
136    pub fn surface_fn(
137        name: impl Into<String>,
138        x_range: std::ops::RangeInclusive<f64>,
139        y_range: std::ops::RangeInclusive<f64>,
140        samples: [usize; 2],
141        f: impl Fn(f64, f64) -> f64,
142    ) -> Series3D<'static> {
143        let columns = samples[0].max(2);
144        let rows = samples[1].max(2);
145        let (x0, x1) = (*x_range.start(), *x_range.end());
146        let (y0, y1) = (*y_range.start(), *y_range.end());
147        let x: Vec<f64> = (0..columns)
148            .map(|index| x0 + (x1 - x0) * index as f64 / (columns - 1) as f64)
149            .collect();
150        let y: Vec<f64> = (0..rows)
151            .map(|index| y0 + (y1 - y0) * index as f64 / (rows - 1) as f64)
152            .collect();
153        let mut z = Vec::with_capacity(columns * rows);
154        for &y_value in &y {
155            for &x_value in &x {
156                z.push(f(x_value, y_value));
157            }
158        }
159        Series3D::surface(name, x, y, z)
160    }
161
162    /// Explicit color; the theme palette is used in order otherwise.
163    pub fn color(mut self, color: Color32) -> Self {
164        self.color = Some(color);
165        self
166    }
167
168    /// Line width in points.
169    pub fn width(mut self, width: f32) -> Self {
170        self.width = width.max(0.5);
171        self
172    }
173
174    /// Solid, dashed, or dotted lines.
175    pub fn style(mut self, style: LineStyle) -> Self {
176        self.line_style = style;
177        self
178    }
179
180    /// A marker on every line vertex, or the scatter marker.
181    pub fn marker(mut self, marker: Marker) -> Self {
182        self.marker = Some(marker);
183        self
184    }
185
186    /// Marker radius in points.
187    pub fn radius(mut self, radius: f32) -> Self {
188        self.radius = radius.max(1.0);
189        self
190    }
191
192    /// Bar footprint in data units; the smallest x/y gap × 0.7 when `None`.
193    pub fn bar_width(mut self, width: f64) -> Self {
194        self.bar_width = Some(width);
195        self
196    }
197
198    /// Where bars start (default 0).
199    pub fn base(mut self, base: f64) -> Self {
200        self.base = base;
201        self
202    }
203
204    /// Leave the series out of the legend.
205    pub fn hide_from_legend(mut self) -> Self {
206        self.legend = false;
207        self
208    }
209
210    /// The series name (also the legend label).
211    pub fn name(&self) -> &str {
212        &self.name
213    }
214
215    /// The points, for line, scatter, and bar series (empty for surfaces).
216    pub fn data(&self) -> &[[f64; 3]] {
217        &self.data
218    }
219
220    /// The surface grid, when this is a surface series.
221    pub fn surface_grid(&self) -> Option<&Surface<'a>> {
222        self.surface.as_ref()
223    }
224
225    /// One data point by index: a grid vertex for surfaces.
226    pub fn point(&self, index: usize) -> Option<[f64; 3]> {
227        match &self.surface {
228            Some(surface) => surface.point(index),
229            None => self.data.get(index).copied(),
230        }
231    }
232
233    /// How many points the series has, including surface vertices.
234    pub fn len(&self) -> usize {
235        match &self.surface {
236            Some(surface) => surface.z.len(),
237            None => self.data.len(),
238        }
239    }
240
241    /// Whether the series has no points.
242    pub fn is_empty(&self) -> bool {
243        self.len() == 0
244    }
245
246    pub(super) fn has_direction(&self) -> bool {
247        self.kind == Kind3D::Line
248    }
249
250    pub(super) fn bar_width_value(&self) -> f64 {
251        self.bar_width
252            .filter(|width| width.is_finite() && *width > 0.0)
253            .unwrap_or_else(|| self.min_spacing() * 0.7)
254    }
255
256    /// The smallest positive x or y step (1 when there is none).
257    pub(super) fn min_spacing(&self) -> f64 {
258        let points: Vec<[f64; 3]> = match &self.surface {
259            Some(surface) => surface
260                .z
261                .iter()
262                .enumerate()
263                .filter_map(|(index, _)| surface.point(index))
264                .collect(),
265            None => self.data.iter().copied().collect(),
266        };
267        let x = smallest_step(points.iter().map(|point| point[0]));
268        let y = smallest_step(points.iter().map(|point| point[1]));
269        x.min(y)
270    }
271
272    /// Data extent in scaled space (log axes ignore values ≤ 0).
273    pub(super) fn bounds(&self, x_scale: Scale, y_scale: Scale, z_scale: Scale) -> Bounds3D {
274        let mut bounds = Bounds3D::NOTHING;
275        if let Some(surface) = &self.surface {
276            for index in 0..surface.z.len() {
277                if let Some(point) = surface.point(index) {
278                    bounds.extend([
279                        x_scale.forward(point[0]),
280                        y_scale.forward(point[1]),
281                        z_scale.forward(point[2]),
282                    ]);
283                }
284            }
285            return bounds;
286        }
287        for point in self.data.iter() {
288            bounds.extend([
289                x_scale.forward(point[0]),
290                y_scale.forward(point[1]),
291                z_scale.forward(point[2]),
292            ]);
293        }
294        if self.kind == Kind3D::Bars && bounds.is_valid() {
295            let half = self.bar_width_value() * 0.5;
296            bounds.extend([bounds.min_x - half, bounds.min_y - half, z_scale.forward(self.base)]);
297            bounds.extend([bounds.max_x + half, bounds.max_y + half, z_scale.forward(self.base)]);
298        }
299        bounds
300    }
301
302    /// A cheap key for [`Self::bounds`]: buffer addresses and lengths, the kind, the
303    /// scales, and sampled values.
304    pub(super) fn fingerprint(&self, x_scale: Scale, y_scale: Scale, z_scale: Scale) -> u64 {
305        use std::hash::{Hash, Hasher};
306        let mut hasher = std::collections::hash_map::DefaultHasher::new();
307        (self.data.as_ptr() as usize, self.data.len()).hash(&mut hasher);
308        if let Some(surface) = &self.surface {
309            for values in [&surface.x, &surface.y, &surface.z] {
310                (values.as_ptr() as usize, values.len()).hash(&mut hasher);
311                let step = (values.len() / 8).max(1);
312                for value in values.iter().step_by(step) {
313                    value.to_bits().hash(&mut hasher);
314                }
315            }
316        }
317        self.kind.hash(&mut hasher);
318        (x_scale, y_scale, z_scale).hash(&mut hasher);
319        let step = (self.data.len() / 16).max(1);
320        for point in self.data.iter().step_by(step).chain(self.data.last()) {
321            for value in point {
322                value.to_bits().hash(&mut hasher);
323            }
324        }
325        hasher.finish()
326    }
327}
328
329fn smallest_step(values: impl Iterator<Item = f64>) -> f64 {
330    let mut values: Vec<f64> = values.filter(|value| value.is_finite()).collect();
331    values.sort_by(f64::total_cmp);
332    let mut step = f64::INFINITY;
333    for pair in values.windows(2) {
334        let delta = pair[1] - pair[0];
335        if delta > 0.0 {
336            step = step.min(delta);
337        }
338    }
339    if step.is_finite() { step } else { 1.0 }
340}