ruviz 0.6.0

High-performance 2D plotting library for Rust
Documentation
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Coordinate transformation utilities
//!
//! This module provides unified coordinate transformation between data space
//! and screen (pixel) space. It consolidates the coordinate mapping logic
//! that was previously duplicated in `PlotArea` and `map_data_to_pixels`.
//!
//! # Overview
//!
//! The [`CoordinateTransform`] struct handles the mapping between:
//! - **Data space**: The coordinate system of your data (e.g., x: 0.0..100.0, y: -10.0..50.0)
//! - **Screen space**: Pixel coordinates on the canvas (e.g., x: 50..750, y: 50..550)
//!
//! # Example
//!
//! ```rust,ignore
//! use ruviz::core::CoordinateTransform;
//!
//! let transform = CoordinateTransform::new(
//!     0.0..100.0,   // data x range
//!     0.0..50.0,    // data y range
//!     50.0..750.0,  // screen x range (pixels)
//!     50.0..550.0,  // screen y range (pixels)
//! );
//!
//! let (screen_x, screen_y) = transform.data_to_screen(50.0, 25.0);
//! let (data_x, data_y) = transform.screen_to_data(screen_x, screen_y);
//! ```

use crate::axes::AxisScale;
use std::ops::Range;

/// Unified coordinate transformation between data space and screen space.
///
/// This struct provides methods to convert coordinates between the data domain
/// (typically f64 values representing your plot data) and screen coordinates
/// (f32 pixel positions on the canvas).
///
/// # Y-axis Inversion
///
/// Screen coordinates typically have Y=0 at the top, while data coordinates
/// usually have Y increasing upward. This struct handles the inversion
/// automatically based on the `y_inverted` flag (true by default for standard plots).
#[derive(Debug, Clone)]
pub struct CoordinateTransform {
    /// Data bounds for x-axis (min..max)
    pub data_x: Range<f64>,
    /// Data bounds for y-axis (min..max)
    pub data_y: Range<f64>,
    /// Screen bounds for x-axis in pixels (left..right)
    pub screen_x: Range<f32>,
    /// Screen bounds for y-axis in pixels (top..bottom)
    pub screen_y: Range<f32>,
    /// Whether Y-axis should be inverted (true for standard screen coordinates)
    pub y_inverted: bool,
}

impl CoordinateTransform {
    /// Create a new coordinate transform with the given bounds.
    ///
    /// By default, Y-axis is inverted to match standard screen coordinates
    /// where Y=0 is at the top.
    ///
    /// # Arguments
    ///
    /// * `data_x` - Data x-axis range (min..max)
    /// * `data_y` - Data y-axis range (min..max)
    /// * `screen_x` - Screen x-axis range in pixels (left..right)
    /// * `screen_y` - Screen y-axis range in pixels (top..bottom)
    pub fn new(
        data_x: Range<f64>,
        data_y: Range<f64>,
        screen_x: Range<f32>,
        screen_y: Range<f32>,
    ) -> Self {
        Self {
            data_x,
            data_y,
            screen_x,
            screen_y,
            y_inverted: true,
        }
    }

    /// Create a coordinate transform without Y-axis inversion.
    ///
    /// Useful for coordinate systems where Y increases downward.
    pub fn new_non_inverted(
        data_x: Range<f64>,
        data_y: Range<f64>,
        screen_x: Range<f32>,
        screen_y: Range<f32>,
    ) -> Self {
        Self {
            data_x,
            data_y,
            screen_x,
            screen_y,
            y_inverted: false,
        }
    }

    /// Create a coordinate transform from plot area parameters.
    ///
    /// This is a convenience constructor for creating a transform from
    /// the typical plot area representation used in the crate.
    ///
    /// # Arguments
    ///
    /// * `area_x` - Left edge of plot area in pixels
    /// * `area_y` - Top edge of plot area in pixels
    /// * `area_width` - Width of plot area in pixels
    /// * `area_height` - Height of plot area in pixels
    /// * `x_min` - Minimum x value in data space
    /// * `x_max` - Maximum x value in data space
    /// * `y_min` - Minimum y value in data space
    /// * `y_max` - Maximum y value in data space
    pub fn from_plot_area(
        area_x: f32,
        area_y: f32,
        area_width: f32,
        area_height: f32,
        x_min: f64,
        x_max: f64,
        y_min: f64,
        y_max: f64,
    ) -> Self {
        Self::new(
            x_min..x_max,
            y_min..y_max,
            area_x..(area_x + area_width),
            area_y..(area_y + area_height),
        )
    }

    /// Transform data coordinates to screen coordinates.
    ///
    /// # Arguments
    ///
    /// * `data_x` - X coordinate in data space
    /// * `data_y` - Y coordinate in data space
    ///
    /// # Returns
    ///
    /// A tuple of (screen_x, screen_y) in pixel coordinates
    #[inline]
    pub fn data_to_screen(&self, data_x: f64, data_y: f64) -> (f32, f32) {
        let x_range = self.data_x.end - self.data_x.start;
        let y_range = self.data_y.end - self.data_y.start;
        let normalized_x = if x_range.abs() > f64::EPSILON {
            crate::axes::scale::linear_normalized_position_with_range(
                data_x,
                self.data_x.start,
                self.data_x.end,
                x_range,
            )
        } else {
            0.5
        };
        let normalized_y = if y_range.abs() > f64::EPSILON {
            crate::axes::scale::linear_normalized_position_with_range(
                data_y,
                self.data_y.start,
                self.data_y.end,
                y_range,
            )
        } else {
            0.5
        };
        self.normalized_to_screen(normalized_x, normalized_y)
    }

    /// Transform data coordinates to screen coordinates using axis scales.
    ///
    /// This is the core scale-aware forward transform. It preserves the direction
    /// of both data and screen ranges and applies the configured Y-axis inversion.
    #[inline]
    pub fn data_to_screen_scaled(
        &self,
        data_x: f64,
        data_y: f64,
        x_scale: &AxisScale,
        y_scale: &AxisScale,
    ) -> (f32, f32) {
        let normalized_x = x_scale.normalized_position(data_x, self.data_x.start, self.data_x.end);
        let normalized_y = y_scale.normalized_position(data_y, self.data_y.start, self.data_y.end);
        self.normalized_to_screen(normalized_x, normalized_y)
    }

    /// Transform data coordinates to screen coordinates, rejecting samples the
    /// axis scales cannot represent.
    ///
    /// Returns `None` when either coordinate fails [`AxisScale::is_valid_value`]
    /// — a non-finite sample on any scale, or a zero/negative sample on a log
    /// scale. [`Self::data_to_screen_scaled`] maps those to `NaN` pixels, which
    /// is only safe for a caller that is about to drop the point anyway.
    ///
    /// **Renderers must use this one.** A line series has to *break* its
    /// polyline at a rejected sample rather than joining across the gap, and a
    /// marker series has to drop it; both need to know a sample was rejected,
    /// which a `NaN` pixel pair only communicates by accident.
    ///
    /// ```
    /// use ruviz::axes::AxisScale;
    /// use ruviz::core::CoordinateTransform;
    ///
    /// let transform = CoordinateTransform::new(1.0..10.0, 1.0..10.0, 0.0..100.0, 0.0..100.0);
    /// assert!(
    ///     transform
    ///         .try_data_to_screen_scaled(5.0, 5.0, &AxisScale::Linear, &AxisScale::Log)
    ///         .is_some()
    /// );
    /// // Zero has no position on a log axis.
    /// assert!(
    ///     transform
    ///         .try_data_to_screen_scaled(5.0, 0.0, &AxisScale::Linear, &AxisScale::Log)
    ///         .is_none()
    /// );
    /// ```
    #[inline]
    pub fn try_data_to_screen_scaled(
        &self,
        data_x: f64,
        data_y: f64,
        x_scale: &AxisScale,
        y_scale: &AxisScale,
    ) -> Option<(f32, f32)> {
        if !x_scale.is_valid_value(data_x) || !y_scale.is_valid_value(data_y) {
            return None;
        }
        Some(self.data_to_screen_scaled(data_x, data_y, x_scale, y_scale))
    }

    /// Transform screen coordinates to data coordinates.
    ///
    /// # Arguments
    ///
    /// * `screen_x` - X coordinate in pixels
    /// * `screen_y` - Y coordinate in pixels
    ///
    /// # Returns
    ///
    /// A tuple of (data_x, data_y) in data space
    #[inline]
    pub fn screen_to_data(&self, screen_x: f32, screen_y: f32) -> (f64, f64) {
        self.screen_to_data_scaled(screen_x, screen_y, &AxisScale::Linear, &AxisScale::Linear)
    }

    /// Transform screen coordinates to data coordinates using axis scales.
    ///
    /// This is the core scale-aware inverse transform and is the inverse of
    /// [`Self::data_to_screen_scaled`] for valid, non-degenerate ranges.
    #[inline]
    pub fn screen_to_data_scaled(
        &self,
        screen_x: f32,
        screen_y: f32,
        x_scale: &AxisScale,
        y_scale: &AxisScale,
    ) -> (f64, f64) {
        let (normalized_x, normalized_y) = self.screen_to_normalized(screen_x, screen_y);
        let data_x =
            x_scale.inverse_normalized_position(normalized_x, self.data_x.start, self.data_x.end);
        let data_y =
            y_scale.inverse_normalized_position(normalized_y, self.data_y.start, self.data_y.end);
        (data_x, data_y)
    }

    #[inline]
    fn normalized_to_screen(&self, normalized_x: f64, normalized_y: f64) -> (f32, f32) {
        let screen_width = self.screen_x.end - self.screen_x.start;
        let screen_height = self.screen_y.end - self.screen_y.start;
        let screen_x = self.screen_x.start + normalized_x as f32 * screen_width;
        let screen_y = if self.y_inverted {
            self.screen_y.start + (1.0 - normalized_y as f32) * screen_height
        } else {
            self.screen_y.start + normalized_y as f32 * screen_height
        };
        (screen_x, screen_y)
    }

    #[inline]
    fn screen_to_normalized(&self, screen_x: f32, screen_y: f32) -> (f64, f64) {
        let screen_width = self.screen_x.end - self.screen_x.start;
        let screen_height = self.screen_y.end - self.screen_y.start;
        let normalized_x = (screen_x - self.screen_x.start) / screen_width;
        let normalized_y = if self.y_inverted {
            1.0 - (screen_y - self.screen_y.start) / screen_height
        } else {
            (screen_y - self.screen_y.start) / screen_height
        };
        (normalized_x as f64, normalized_y as f64)
    }

    /// Check if a data point is within the data bounds.
    #[inline]
    pub fn contains_data(&self, data_x: f64, data_y: f64) -> bool {
        data_x >= self.data_x.start
            && data_x <= self.data_x.end
            && data_y >= self.data_y.start
            && data_y <= self.data_y.end
    }

    /// Check if a screen point is within the screen bounds.
    #[inline]
    pub fn contains_screen(&self, screen_x: f32, screen_y: f32) -> bool {
        screen_x >= self.screen_x.start
            && screen_x <= self.screen_x.end
            && screen_y >= self.screen_y.start
            && screen_y <= self.screen_y.end
    }

    /// Get the center point in data coordinates.
    pub fn data_center(&self) -> (f64, f64) {
        (
            (self.data_x.start + self.data_x.end) / 2.0,
            (self.data_y.start + self.data_y.end) / 2.0,
        )
    }

    /// Get the center point in screen coordinates.
    pub fn screen_center(&self) -> (f32, f32) {
        (
            (self.screen_x.start + self.screen_x.end) / 2.0,
            (self.screen_y.start + self.screen_y.end) / 2.0,
        )
    }

    /// Get the width of the screen area in pixels.
    pub fn screen_width(&self) -> f32 {
        self.screen_x.end - self.screen_x.start
    }

    /// Get the height of the screen area in pixels.
    pub fn screen_height(&self) -> f32 {
        self.screen_y.end - self.screen_y.start
    }

    /// Get the width of the data range.
    pub fn data_width(&self) -> f64 {
        self.data_x.end - self.data_x.start
    }

    /// Get the height of the data range.
    pub fn data_height(&self) -> f64 {
        self.data_y.end - self.data_y.start
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_data_to_screen_basic() {
        let transform = CoordinateTransform::new(0.0..100.0, 0.0..100.0, 0.0..1000.0, 0.0..500.0);

        // Origin in data space
        let (x, y) = transform.data_to_screen(0.0, 0.0);
        assert!((x - 0.0).abs() < f32::EPSILON);
        assert!((y - 500.0).abs() < f32::EPSILON); // Y inverted: 0 in data -> bottom in screen

        // Max corner
        let (x, y) = transform.data_to_screen(100.0, 100.0);
        assert!((x - 1000.0).abs() < f32::EPSILON);
        assert!((y - 0.0).abs() < f32::EPSILON); // Y inverted: 100 in data -> top in screen

        // Center
        let (x, y) = transform.data_to_screen(50.0, 50.0);
        assert!((x - 500.0).abs() < f32::EPSILON);
        assert!((y - 250.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_screen_to_data_basic() {
        let transform = CoordinateTransform::new(0.0..100.0, 0.0..100.0, 0.0..1000.0, 0.0..500.0);

        // Top-left of screen
        let (x, y) = transform.screen_to_data(0.0, 0.0);
        assert!((x - 0.0).abs() < f64::EPSILON);
        assert!((y - 100.0).abs() < f64::EPSILON); // Y inverted

        // Bottom-right of screen
        let (x, y) = transform.screen_to_data(1000.0, 500.0);
        assert!((x - 100.0).abs() < f64::EPSILON);
        assert!((y - 0.0).abs() < f64::EPSILON); // Y inverted
    }

    #[test]
    fn test_roundtrip() {
        let transform =
            CoordinateTransform::new(-50.0..150.0, -10.0..90.0, 100.0..900.0, 50.0..550.0);

        let test_points = [(0.0, 0.0), (100.0, 50.0), (-25.0, 45.0), (75.0, -5.0)];

        // Note: tolerance is higher due to f64 -> f32 -> f64 conversion
        // f32 has ~7 significant digits, so we use 1e-4 relative tolerance
        let tolerance = 1e-4;

        for (data_x, data_y) in test_points {
            let (screen_x, screen_y) = transform.data_to_screen(data_x, data_y);
            let (recovered_x, recovered_y) = transform.screen_to_data(screen_x, screen_y);

            // Use relative tolerance for non-zero values, absolute for near-zero
            let x_tol = if data_x.abs() > 1.0 {
                data_x.abs() * tolerance
            } else {
                tolerance
            };
            let y_tol = if data_y.abs() > 1.0 {
                data_y.abs() * tolerance
            } else {
                tolerance
            };

            assert!(
                (data_x - recovered_x).abs() < x_tol,
                "X roundtrip failed: {} -> {} -> {} (tolerance: {})",
                data_x,
                screen_x,
                recovered_x,
                x_tol
            );
            assert!(
                (data_y - recovered_y).abs() < y_tol,
                "Y roundtrip failed: {} -> {} -> {} (tolerance: {})",
                data_y,
                screen_y,
                recovered_y,
                y_tol
            );
        }
    }

    #[test]
    fn test_from_plot_area() {
        let transform = CoordinateTransform::from_plot_area(
            50.0,  // area_x
            50.0,  // area_y
            700.0, // area_width
            500.0, // area_height
            0.0,   // x_min
            100.0, // x_max
            0.0,   // y_min
            100.0, // y_max
        );

        assert!((transform.screen_x.start - 50.0).abs() < f32::EPSILON);
        assert!((transform.screen_x.end - 750.0).abs() < f32::EPSILON);
        assert!((transform.screen_y.start - 50.0).abs() < f32::EPSILON);
        assert!((transform.screen_y.end - 550.0).abs() < f32::EPSILON);

        // Test a point
        let (x, y) = transform.data_to_screen(50.0, 50.0);
        assert!((x - 400.0).abs() < f32::EPSILON); // 50 + 700/2
        assert!((y - 300.0).abs() < f32::EPSILON); // 50 + 500/2
    }

    #[test]
    fn test_non_inverted() {
        let transform =
            CoordinateTransform::new_non_inverted(0.0..100.0, 0.0..100.0, 0.0..100.0, 0.0..100.0);

        // Without inversion, data Y=0 should map to screen Y=0
        let (_, y) = transform.data_to_screen(0.0, 0.0);
        assert!((y - 0.0).abs() < f32::EPSILON);

        let (_, y) = transform.data_to_screen(0.0, 100.0);
        assert!((y - 100.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_contains_data() {
        let transform = CoordinateTransform::new(0.0..100.0, 0.0..100.0, 0.0..100.0, 0.0..100.0);

        assert!(transform.contains_data(50.0, 50.0));
        assert!(transform.contains_data(0.0, 0.0));
        assert!(transform.contains_data(100.0, 100.0));
        assert!(!transform.contains_data(-1.0, 50.0));
        assert!(!transform.contains_data(50.0, 101.0));
    }

    #[test]
    fn test_zero_range() {
        // Edge case: zero range should return center
        let transform = CoordinateTransform::new(
            50.0..50.0, // zero range
            50.0..50.0, // zero range
            0.0..100.0,
            0.0..100.0,
        );

        let (x, y) = transform.data_to_screen(50.0, 50.0);
        assert!((x - 50.0).abs() < f32::EPSILON); // Center of screen range
        assert!((y - 50.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_helper_methods() {
        let transform = CoordinateTransform::new(0.0..200.0, 0.0..100.0, 50.0..850.0, 100.0..600.0);

        assert!((transform.screen_width() - 800.0).abs() < f32::EPSILON);
        assert!((transform.screen_height() - 500.0).abs() < f32::EPSILON);
        assert!((transform.data_width() - 200.0).abs() < f64::EPSILON);
        assert!((transform.data_height() - 100.0).abs() < f64::EPSILON);

        let (cx, cy) = transform.data_center();
        assert!((cx - 100.0).abs() < f64::EPSILON);
        assert!((cy - 50.0).abs() < f64::EPSILON);

        let (sx, sy) = transform.screen_center();
        assert!((sx - 450.0).abs() < f32::EPSILON);
        assert!((sy - 350.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_scaled_transform_endpoints_midpoints_and_reversed_screen_ranges() {
        let transform =
            CoordinateTransform::new(1.0..100.0, -100.0..100.0, 700.0..100.0, 500.0..50.0);
        let x_scale = AxisScale::Log;
        let y_scale = AxisScale::symlog(1.0);

        let (start_x, start_y) = transform.data_to_screen_scaled(1.0, -100.0, &x_scale, &y_scale);
        assert!((start_x - 700.0).abs() < f32::EPSILON);
        assert!((start_y - 50.0).abs() < f32::EPSILON);

        let (mid_x, mid_y) = transform.data_to_screen_scaled(10.0, 0.0, &x_scale, &y_scale);
        assert!((mid_x - 400.0).abs() < f32::EPSILON);
        assert!((mid_y - 275.0).abs() < f32::EPSILON);

        let (end_x, end_y) = transform.data_to_screen_scaled(100.0, 100.0, &x_scale, &y_scale);
        assert!((end_x - 100.0).abs() < f32::EPSILON);
        assert!((end_y - 500.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_scaled_transform_roundtrips_reversed_data_and_screen_ranges() {
        let transform =
            CoordinateTransform::new(1000.0..1.0, 100.0..-100.0, 900.0..75.0, 40.0..640.0);
        let x_scale = AxisScale::Log;
        let y_scale = AxisScale::symlog(2.0);
        let points = [(1000.0, 100.0), (100.0, 10.0), (10.0, 0.0), (1.0, -100.0)];

        for (data_x, data_y) in points {
            let (screen_x, screen_y) =
                transform.data_to_screen_scaled(data_x, data_y, &x_scale, &y_scale);
            let (recovered_x, recovered_y) =
                transform.screen_to_data_scaled(screen_x, screen_y, &x_scale, &y_scale);
            let x_tolerance = data_x.abs().max(1.0) * 1e-5;
            let y_tolerance = data_y.abs().max(1.0) * 1e-5;
            assert!((recovered_x - data_x).abs() <= x_tolerance);
            assert!((recovered_y - data_y).abs() <= y_tolerance);
        }
    }

    #[test]
    fn test_scaled_linear_transform_uses_exact_epsilon_and_extreme_range_rules() {
        let min = 1.0;
        let max = min + f64::EPSILON;
        let transform =
            CoordinateTransform::new(min..max, -f64::MAX..f64::MAX, 10.0..210.0, 20.0..120.0);
        let linear = AxisScale::Linear;

        assert_eq!(
            transform.data_to_screen_scaled(min, -f64::MAX, &linear, &linear),
            (10.0, 120.0)
        );
        assert_eq!(
            transform.data_to_screen_scaled(max, f64::MAX, &linear, &linear),
            (210.0, 20.0)
        );
        assert_eq!(
            transform.screen_to_data_scaled(10.0, 120.0, &linear, &linear),
            (min, -f64::MAX)
        );
        assert_eq!(
            transform.screen_to_data_scaled(210.0, 20.0, &linear, &linear),
            (max, f64::MAX)
        );
    }

    #[test]
    fn test_linear_transform_preserves_exact_epsilon_degeneracy_semantics() {
        let transform =
            CoordinateTransform::new(1.0..1.0 + f64::EPSILON, 0.0..1.0, 10.0..210.0, 20.0..120.0);

        assert_eq!(transform.data_to_screen(1.0, 0.5).0, 110.0);
        assert_eq!(transform.data_to_screen(1.0 + f64::EPSILON, 0.5).0, 110.0);
    }
}