crisol-plot-core 1.8.1

Crisol plot core: the egui-free math behind the plot, axis ticks, analysis, filters, and decimation.
Documentation
//! A data ↔ screen transform in plain numbers, with no egui types.

use crisol_core::data::Bounds;

use super::axis::Scale;

/// A point in screen coordinates (points, origin at the top-left).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ScreenPoint {
    /// Horizontal position.
    pub x: f32,
    /// Vertical position.
    pub y: f32,
}

impl ScreenPoint {
    /// The origin.
    pub const ZERO: Self = Self { x: 0.0, y: 0.0 };

    /// A point at `x`, `y`.
    pub fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }

    /// Whether both coordinates are finite.
    pub fn is_finite(self) -> bool {
        self.x.is_finite() && self.y.is_finite()
    }

    /// The Euclidean distance to `other`.
    pub fn distance(self, other: Self) -> f32 {
        ((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt()
    }

    /// The squared Euclidean distance to `other`.
    pub fn distance_sq(self, other: Self) -> f32 {
        (self.x - other.x).powi(2) + (self.y - other.y).powi(2)
    }

    /// The squared length of the vector.
    pub fn length_sq(self) -> f32 {
        self.x * self.x + self.y * self.y
    }

    /// The dot product with `other`.
    pub fn dot(self, other: Self) -> f32 {
        self.x * other.x + self.y * other.y
    }
}

impl std::ops::Sub for ScreenPoint {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        Self::new(self.x - other.x, self.y - other.y)
    }
}

impl std::ops::Mul<f32> for ScreenPoint {
    type Output = Self;

    fn mul(self, factor: f32) -> Self {
        Self::new(self.x * factor, self.y * factor)
    }
}

/// A rectangle in screen coordinates.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ScreenRect {
    /// The top-left corner.
    pub min: ScreenPoint,
    /// The bottom-right corner.
    pub max: ScreenPoint,
}

impl ScreenRect {
    /// A rectangle from two opposite corners in any order.
    pub fn from_min_max(a: ScreenPoint, b: ScreenPoint) -> Self {
        Self {
            min: ScreenPoint::new(a.x.min(b.x), a.y.min(b.y)),
            max: ScreenPoint::new(a.x.max(b.x), a.y.max(b.y)),
        }
    }

    /// A rectangle from its top-left corner and size.
    pub fn from_min_size(min: ScreenPoint, width: f32, height: f32) -> Self {
        Self {
            min,
            max: ScreenPoint::new(min.x + width, min.y + height),
        }
    }

    /// The left edge.
    pub fn left(self) -> f32 {
        self.min.x
    }

    /// The right edge.
    pub fn right(self) -> f32 {
        self.max.x
    }

    /// The top edge.
    pub fn top(self) -> f32 {
        self.min.y
    }

    /// The bottom edge.
    pub fn bottom(self) -> f32 {
        self.max.y
    }

    /// The width.
    pub fn width(self) -> f32 {
        self.max.x - self.min.x
    }

    /// The height.
    pub fn height(self) -> f32 {
        self.max.y - self.min.y
    }

    /// The center of the rectangle.
    pub fn center(self) -> ScreenPoint {
        ScreenPoint::new((self.min.x + self.max.x) * 0.5, (self.min.y + self.max.y) * 0.5)
    }

    /// Whether the rectangle has a positive area.
    pub fn is_positive(self) -> bool {
        self.width() > 0.0 && self.height() > 0.0
    }

    /// Whether `point` lies inside the rectangle (edges included).
    pub fn contains(self, point: ScreenPoint) -> bool {
        point.x >= self.min.x && point.x <= self.max.x && point.y >= self.min.y && point.y <= self.max.y
    }

    /// The rectangle grown by `amount` on every side.
    pub fn expand(self, amount: f32) -> Self {
        Self {
            min: ScreenPoint::new(self.min.x - amount, self.min.y - amount),
            max: ScreenPoint::new(self.max.x + amount, self.max.y + amount),
        }
    }
}

/// Which vertical axis a series is measured against.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum YAxis {
    /// The primary axis on the left.
    #[default]
    Left,
    /// The secondary axis on the right; it appears as soon as one series uses it.
    Right,
}

/// Maps data to screen and back. Works in "scaled" space (log10 already applied), so
/// zoom and pan are linear in what the user sees.
#[derive(Clone, Copy, Debug)]
pub struct Transform {
    /// The data area on screen.
    pub frame: ScreenRect,
    /// Visible range in scaled units.
    pub view: Bounds,
    /// The horizontal scale.
    pub x_scale: Scale,
    /// The left vertical scale.
    pub y_scale: Scale,
    /// The right axis: its visible range in scaled units, and its scale.
    pub y2: Option<SecondAxis>,
}

/// The visible range of the right y axis, in scaled units.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SecondAxis {
    /// Lower bound in scaled units.
    pub min: f64,
    /// Upper bound in scaled units.
    pub max: f64,
    /// The axis scale.
    pub scale: Scale,
}

impl Transform {
    /// The transform for series on `axis`: the right axis swaps in its range and scale.
    pub fn for_axis(self, axis: YAxis) -> Self {
        match (axis, self.y2) {
            (YAxis::Right, Some(y2)) => Self {
                view: Bounds {
                    min_y: y2.min,
                    max_y: y2.max,
                    ..self.view
                },
                y_scale: y2.scale,
                ..self
            },
            _ => self,
        }
    }

    /// Map a data point to screen coordinates.
    pub fn to_screen(self, point: [f64; 2]) -> ScreenPoint {
        let x = self.x_scale.forward(point[0]);
        let y = self.y_scale.forward(point[1]);
        self.scaled_to_screen(x, y)
    }

    /// Map scaled coordinates to screen coordinates.
    pub fn scaled_to_screen(&self, x: f64, y: f64) -> ScreenPoint {
        let tx = (x - self.view.min_x) / self.view.width();
        let ty = (y - self.view.min_y) / self.view.height();
        ScreenPoint::new(
            self.frame.left() + (tx * f64::from(self.frame.width())) as f32,
            self.frame.bottom() - (ty * f64::from(self.frame.height())) as f32,
        )
    }

    /// Map a screen position to scaled coordinates.
    pub fn to_scaled(self, pos: ScreenPoint) -> [f64; 2] {
        let tx = f64::from((pos.x - self.frame.left()) / self.frame.width());
        let ty = f64::from((self.frame.bottom() - pos.y) / self.frame.height());
        [
            self.view.min_x + tx * self.view.width(),
            self.view.min_y + ty * self.view.height(),
        ]
    }

    /// Map a screen position to data coordinates.
    pub fn to_data(self, pos: ScreenPoint) -> [f64; 2] {
        let [x, y] = self.to_scaled(pos);
        [self.x_scale.inverse(x), self.y_scale.inverse(y)]
    }

    /// Data units per screen point, in scaled space.
    pub fn units_per_point(&self) -> [f64; 2] {
        [
            self.view.width() / f64::from(self.frame.width().max(1.0)),
            self.view.height() / f64::from(self.frame.height().max(1.0)),
        ]
    }
}