egui_plotter/chart.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
//! Structs used to simplify the process of making interactive charts
use std::any::Any;
use egui::{PointerState, Ui};
use plotters::{
    coord::Shift,
    prelude::{DrawingArea, IntoDrawingArea},
};
use crate::EguiBackend;
/// Default pitch and yaw scale for mouse rotations.
pub const DEFAULT_MOVE_SCALE: f32 = 0.01;
/// Default zoom scale for scroll wheel zooming.
pub const DEFAULT_SCROLL_SCALE: f32 = 0.001;
#[derive(Debug, Copy, Clone)]
/// Transformations to be applied to your chart. Is modified by user input(if the mouse is enabled) and
/// used by Chart::draw() and your builder callback.
///
/// Chart::draw() applies the scale and the x/y offset to your plot, so unless
/// you want to create some effects on your own you don't need to worry about them.
///
/// If you are creating a 3d plot however you will have to manually apply the pitch and
/// yaw to your chart with the following code:
///
/// ```ignore
/// chart.with_projection(|mut pb| {
///     pb.yaw = transform.yaw;
///     pb.pitch = transform.pitch;
///     pb.scale = 0.7; // Set scale to 0.7 to avoid artifacts caused by plotter's renderer
///     pb.into_matrix()
/// });
///```
pub struct Transform {
    /// Pitch of your graph in 3d
    pub pitch: f64,
    /// Yaw of your graph in 3d
    pub yaw: f64,
    /// Scale of your graph. Applied in Chart::draw()
    pub scale: f64,
    /// X offset of your graph. Applied in Chart::draw()
    pub x: i32,
    /// Y offset of your graph. Applied in Chart::draw()
    pub y: i32,
}
impl Default for Transform {
    fn default() -> Self {
        Self {
            pitch: 0.0,
            yaw: 0.0,
            scale: 1.0,
            x: 0,
            y: 0,
        }
    }
}
#[derive(Debug, Copy, Clone)]
/// Mouse buttons that can be bound to chart actions
pub enum MouseButton {
    Primary,
    Middle,
    Secondary,
}
impl MouseButton {
    /// See if the mouse button is down given a PointerState
    pub fn is_down(&self, pointer: &PointerState) -> bool {
        match self {
            Self::Primary => pointer.primary_down(),
            Self::Middle => pointer.middle_down(),
            Self::Secondary => pointer.secondary_down(),
        }
    }
}
#[derive(Debug, Copy, Clone)]
/// Used to configure how the mouse interacts with the chart.
///
/// ## Usage
/// MouseConfig allows you to change the ways the user interacts with your chart in the following
/// ways:
///  * `drag`, `rotate`, & `zoom` - Enables dragging, rotating, and zooming in on your plots with
///  mouse controls.
///  * `pitch_scale` & `yaw_scale` - Modifies how quickly the pitch and yaw are rotated when rotating with the
///  mouse.
///  * `zoom_scale` - Modifies how quickly you zoom in/out.
///  * `drag_bind` - Mouse button bound to dragging your plot.
///  * `rotate_bind` - Mouse button bound to rotating your plot.
pub struct MouseConfig {
    drag: bool,
    rotate: bool,
    zoom: bool,
    yaw_scale: f32,
    pitch_scale: f32,
    zoom_scale: f32,
    drag_bind: MouseButton,
    rotate_bind: MouseButton,
}
impl Default for MouseConfig {
    fn default() -> Self {
        Self {
            drag: false,
            rotate: false,
            zoom: false,
            yaw_scale: DEFAULT_MOVE_SCALE,
            pitch_scale: DEFAULT_MOVE_SCALE,
            zoom_scale: DEFAULT_SCROLL_SCALE,
            drag_bind: MouseButton::Middle,
            rotate_bind: MouseButton::Primary,
        }
    }
}
impl MouseConfig {
    #[inline]
    /// Create a new MouseConfig with dragging, rotationg, and zooming enabled.
    pub fn enabled() -> Self {
        Self {
            drag: true,
            rotate: true,
            zoom: true,
            yaw_scale: DEFAULT_MOVE_SCALE,
            pitch_scale: DEFAULT_MOVE_SCALE,
            zoom_scale: DEFAULT_SCROLL_SCALE,
            drag_bind: MouseButton::Middle,
            rotate_bind: MouseButton::Primary,
        }
    }
    #[inline]
    /// Enables dragging, rotating, and zooming in on your plots.
    fn set_enable_all(&mut self) {
        self.set_drag(true);
        self.set_zoom(true);
        self.set_rotate(true);
    }
    #[inline]
    /// Enables dragging, rotating, and zooming in on your plots. Consumes self.
    pub fn enable_all(mut self) -> Self {
        self.set_enable_all();
        self
    }
    #[inline]
    /// Enable/disable dragging of the chart.
    pub fn set_drag(&mut self, drag: bool) {
        self.drag = drag
    }
    #[inline]
    /// Enable/disable dragging of the chart. Consumes self.
    pub fn drag(mut self, drag: bool) -> Self {
        self.set_drag(drag);
        self
    }
    #[inline]
    /// Enable/disable rotation of the chart.
    pub fn set_rotate(&mut self, rotate: bool) {
        self.rotate = rotate
    }
    #[inline]
    /// Enable/disable rotation of the chart. Consumes self.
    pub fn rotate(mut self, rotate: bool) -> Self {
        self.set_rotate(rotate);
        self
    }
    #[inline]
    /// Enable/disable zoom of the chart.
    pub fn set_zoom(&mut self, zoom: bool) {
        self.zoom = zoom;
    }
    #[inline]
    /// Enable/disable zoom of the chart. Consumes self.
    pub fn zoom(mut self, zoom: bool) -> Self {
        self.set_zoom(zoom);
        self
    }
    #[inline]
    /// Change the pitch scale.
    pub fn set_pitch_scale(&mut self, scale: f32) {
        self.pitch_scale = scale
    }
    #[inline]
    /// Change the pitch scale. Consumes self.
    pub fn pitch_scale(mut self, scale: f32) -> Self {
        self.set_pitch_scale(scale);
        self
    }
}
/// Allows users to drag, rotate, and zoom in/out on your plots.
///
/// ## Usage
/// Charts are designed to be easy to implement and use, while simultaniously
/// being powerful enough for your application. You can manipulate the
/// following properties of a chart to get the effects you want:
///  * `builder_cb` - Callback used to populate the chart. Is provided a DrawingArea and the
///  chart's `data`.
///  * `mouse` - Mouse configuration. Configure how you wish the mouse to affect/manipulate the
///  chart.
///  * `data` - A Box of data of any type to be stored with the chart. Provided so that you can modify data
///  without having to specify a new callback during runtime. For example, `examples/parachart.rs`
///  uses it to store the range so it can be changed during runtime.
///
///  ## Examples
///  See `examples/3dchart.rs` and `examples/parachart.rs` for examples of usage.
pub struct Chart {
    transform: Transform,
    mouse: MouseConfig,
    builder_cb: Option<
        Box<dyn FnMut(&mut DrawingArea<EguiBackend, Shift>, &Transform, &Option<Box<dyn Any>>)>,
    >,
    data: Option<Box<dyn Any>>,
}
impl Chart {
    /// Create a new 3d chart with default settings.
    pub fn new() -> Self {
        Self {
            transform: Transform::default(),
            mouse: MouseConfig::default(),
            builder_cb: None,
            data: None,
        }
    }
    #[inline]
    /// Enable or disable mouse controls.
    pub fn set_mouse(&mut self, mouse: MouseConfig) {
        self.mouse = mouse
    }
    #[inline]
    /// Enable or disable mouse controls. Consumes self.
    pub fn mouse(mut self, mouse: MouseConfig) -> Self {
        self.set_mouse(mouse);
        self
    }
    #[inline]
    /// Set the builder callback.
    pub fn set_builder_cb(
        &mut self,
        builder_cb: Box<
            dyn FnMut(&mut DrawingArea<EguiBackend, Shift>, &Transform, &Option<Box<dyn Any>>),
        >,
    ) {
        self.builder_cb = Some(builder_cb)
    }
    #[inline]
    /// Set the builder callback. Consumes self.
    pub fn builder_cb(
        mut self,
        builder_cb: Box<
            dyn FnMut(&mut DrawingArea<EguiBackend, Shift>, &Transform, &Option<Box<dyn Any>>),
        >,
    ) -> Self {
        self.set_builder_cb(builder_cb);
        self
    }
    #[inline]
    /// Set the pitch of the chart.
    pub fn set_pitch(&mut self, pitch: f64) {
        self.transform.pitch = pitch
    }
    #[inline]
    /// Set the pitch of the chart. Consumes self.
    pub fn pitch(mut self, pitch: f64) -> Self {
        self.set_pitch(pitch);
        self
    }
    #[inline]
    /// Set the yaw of the chart.
    pub fn set_yaw(&mut self, yaw: f64) {
        self.transform.yaw = yaw
    }
    #[inline]
    /// Set the yaw of the chart. Consumes self.
    pub fn yaw(mut self, yaw: f64) -> Self {
        self.set_yaw(yaw);
        self
    }
    #[inline]
    /// Set the scale of the chart.
    pub fn set_scale(&mut self, scale: f64) {
        self.transform.scale = scale
    }
    #[inline]
    /// Set the scale of the chart. Consumes self.
    pub fn scale(mut self, scale: f64) -> Self {
        self.set_scale(scale);
        self
    }
    #[inline]
    /// Set the data of the chart.
    pub fn set_data(&mut self, data: Box<dyn Any>) {
        self.data = Some(data)
    }
    #[inline]
    /// Set the data of the chart. Consumes self.
    pub fn data(mut self, data: Box<dyn Any>) -> Self {
        self.set_data(data);
        self
    }
    /// Call the callback and draw the chart to a UI element.
    pub fn draw(&mut self, ui: &Ui) {
        let transform = &mut self.transform;
        // First, get mouse data
        ui.input(|input| {
            let pointer = &input.pointer;
            let delta = pointer.delta();
            // Adjust the pitch/yaw if the primary button is pressed and rotation is enabled
            if self.mouse.rotate && self.mouse.rotate_bind.is_down(pointer) {
                let pitch_delta = delta.y * self.mouse.pitch_scale;
                let yaw_delta = delta.x * self.mouse.yaw_scale;
                transform.pitch += pitch_delta as f64;
                transform.yaw += -yaw_delta as f64;
            }
            // Adjust the x/y if the middle button is down and dragging is enabled
            if self.mouse.drag && self.mouse.drag_bind.is_down(pointer) {
                let x_delta = delta.x;
                let y_delta = delta.y;
                transform.x += x_delta as i32;
                transform.y += y_delta as i32;
            }
            // Adjust zoom if zoom is enabled
            if self.mouse.zoom {
                let scale_delta = input.scroll_delta.y * self.mouse.zoom_scale;
                // !TODO! make scaling exponential
                transform.scale = (transform.scale + scale_delta as f64).abs();
            }
        });
        let mut area = EguiBackend::new(ui)
            .offset((transform.x, transform.y))
            .scale(transform.scale as f32)
            .into_drawing_area();
        match &mut self.builder_cb {
            Some(cb) => {
                cb(&mut area, transform, &self.data);
            }
            None => {}
        }
        area.present().unwrap();
    }
}