hyperchad_renderer 0.3.0

HyperChad renderer package
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
//! Immediate mode viewport rendering with per-frame visibility calculations.
//!
//! This module provides viewport types for immediate mode rendering, where visibility
//! is recalculated every frame. Viewports track position and dimensions dynamically
//! and can be nested hierarchically for complex UI layouts.
//!
//! # Key Types
//!
//! * `Viewport` - Hierarchical viewport with parent-child relationships
//! * `ViewportListener` - Tracks visibility changes for a position within a viewport
//! * `Pos` - Position and dimensions for viewport calculations
//!
//! # Examples
//!
//! Creating a viewport listener to track visibility:
//!
//! ```rust
//! # #[cfg(feature = "viewport-immediate")]
//! # {
//! use hyperchad_renderer::viewport::immediate::{ViewportListener, Viewport, Pos};
//!
//! # fn example() {
//! let viewport = Viewport {
//!     parent: None,
//!     pos: Pos { x: 0.0, y: 0.0, w: 800.0, h: 600.0 },
//!     viewport: Pos { x: 0.0, y: 0.0, w: 800.0, h: 600.0 },
//! };
//!
//! let mut listener = ViewportListener::new(
//!     Some(viewport),
//!     100.0, 100.0, 50.0, 50.0
//! );
//!
//! let ((visible, _), (dist, _)) = listener.check();
//! # }
//! # }
//! ```

/// Viewport for immediate mode rendering with hierarchical positioning.
///
/// Represents a viewport in immediate mode, which recalculates visibility
/// on every frame. Viewports can be nested via the `parent` field to create
/// hierarchical visibility calculations.
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, Clone)]
pub struct Viewport {
    /// Parent viewport in the hierarchy, if any
    pub parent: Option<Box<Self>>,
    /// Position and dimensions of this viewport's content
    pub pos: Pos,
    /// Viewport's visible area position and dimensions
    pub viewport: Pos,
}

impl Viewport {
    fn is_visible(&self) -> (bool, f32) {
        if let Some((visible, dist)) = self.parent.as_ref().map(|x| x.is_visible()) {
            if visible {
                let pos = self.pos;
                let vp = self.viewport;
                super::is_visible(vp.x, vp.y, vp.w, vp.h, pos.x, pos.y, pos.w, pos.h)
            } else {
                (false, dist)
            }
        } else {
            (true, 0.0)
        }
    }
}

/// Position and dimensions for immediate mode viewport calculations.
///
/// Represents a rectangular area with x, y coordinates and width, height dimensions.
#[derive(Debug, Clone, Copy)]
pub struct Pos {
    /// X coordinate
    pub x: f32,
    /// Y coordinate
    pub y: f32,
    /// Width
    pub w: f32,
    /// Height
    pub h: f32,
}

/// Tracks visibility changes for a position within a viewport in immediate mode.
///
/// Monitors whether a specific position is visible within its viewport and tracks
/// changes in visibility state and distance from the viewport. Used in immediate
/// mode rendering where visibility is checked every frame.
#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
pub struct ViewportListener {
    /// The viewport to check visibility against
    pub viewport: Option<Viewport>,
    visible: bool,
    prev_visible: Option<bool>,
    initialized: bool,
    dist: f32,
    prev_dist: Option<f32>,
    /// The position and dimensions to check for visibility
    pub pos: Pos,
}

impl ViewportListener {
    /// Creates a new viewport listener with the specified viewport and position.
    ///
    /// # Parameters
    ///
    /// * `viewport` - Optional viewport to check visibility against
    /// * `x` - X coordinate of the position to monitor
    /// * `y` - Y coordinate of the position to monitor
    /// * `w` - Width of the area to monitor
    /// * `h` - Height of the area to monitor
    #[must_use]
    pub const fn new(viewport: Option<Viewport>, x: f32, y: f32, w: f32, h: f32) -> Self {
        Self {
            viewport,
            visible: false,
            prev_visible: None,
            initialized: false,
            dist: 0.0,
            prev_dist: None,
            pos: Pos { x, y, w, h },
        }
    }

    fn is_visible(&self) -> (bool, f32) {
        if let Some(((visible, dist), vp, pos)) = self
            .viewport
            .as_ref()
            .map(|x| (x.is_visible(), x.viewport, x.pos))
        {
            if visible {
                super::is_visible(
                    vp.x + pos.x,
                    vp.y + pos.y,
                    vp.w,
                    vp.h,
                    self.pos.x,
                    self.pos.y,
                    self.pos.w,
                    self.pos.h,
                )
            } else {
                (false, dist)
            }
        } else {
            (true, 0.0)
        }
    }

    /// Checks current visibility status and returns changes since last check.
    ///
    /// # Returns
    ///
    /// A tuple of two tuples:
    /// * First tuple: `(current_visible, previous_visible_if_changed)` - Current visibility
    ///   and the previous visibility state if it changed, otherwise `None`
    /// * Second tuple: `(current_distance, previous_distance_if_changed)` - Current distance
    ///   from viewport and the previous distance if it changed significantly, otherwise `None`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hyperchad_renderer::viewport::immediate::ViewportListener;
    ///
    /// let mut listener = ViewportListener::new(None, 10.0, 10.0, 20.0, 20.0);
    /// let ((visible, previous_visible), (distance, previous_distance)) = listener.check();
    ///
    /// assert!(visible);
    /// assert!(previous_visible.is_none());
    /// assert!(distance < 0.001);
    /// assert!(previous_distance.is_none());
    /// ```
    pub fn check(&mut self) -> ((bool, Option<bool>), (f32, Option<f32>)) {
        let (visible, dist) = self.is_visible();
        log::trace!("check: pos={:?} visible={visible} dist={dist}", self.pos);

        if self.initialized {
            let prev_visible = self.visible;
            let prev_dist = self.dist;
            self.prev_visible = if prev_visible == visible {
                None
            } else {
                self.visible = visible;
                Some(prev_visible)
            };
            self.prev_dist = if (prev_dist - dist) < 0.01 {
                None
            } else {
                self.dist = dist;
                Some(prev_dist)
            };

            ((visible, self.prev_visible), (dist, self.prev_dist))
        } else {
            self.initialized = true;
            self.visible = visible;
            self.dist = dist;
            ((visible, None), (dist, None))
        }
    }
}

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

    #[test_log::test]
    fn test_viewport_listener_initial_check_visible() {
        let viewport = Viewport {
            parent: None,
            pos: Pos {
                x: 0.0,
                y: 0.0,
                w: 800.0,
                h: 600.0,
            },
            viewport: Pos {
                x: 0.0,
                y: 0.0,
                w: 800.0,
                h: 600.0,
            },
        };

        let mut listener = ViewportListener::new(Some(viewport), 100.0, 100.0, 50.0, 50.0);

        let ((visible, prev_visible), (dist, prev_dist)) = listener.check();

        assert!(visible);
        assert!(prev_visible.is_none()); // First check has no previous
        assert!(dist < 0.001);
        assert!(prev_dist.is_none());
    }

    #[test_log::test]
    fn test_viewport_listener_initial_check_not_visible() {
        let viewport = Viewport {
            parent: None,
            pos: Pos {
                x: 0.0,
                y: 0.0,
                w: 800.0,
                h: 600.0,
            },
            viewport: Pos {
                x: 0.0,
                y: 0.0,
                w: 800.0,
                h: 600.0,
            },
        };

        // Widget outside viewport
        let mut listener = ViewportListener::new(Some(viewport), 1000.0, 1000.0, 50.0, 50.0);

        let ((visible, prev_visible), (_dist, prev_dist)) = listener.check();

        assert!(!visible);
        assert!(prev_visible.is_none());
        assert!(prev_dist.is_none());
    }

    #[test_log::test]
    fn test_viewport_listener_visibility_change() {
        let viewport = Viewport {
            parent: None,
            pos: Pos {
                x: 0.0,
                y: 0.0,
                w: 800.0,
                h: 600.0,
            },
            viewport: Pos {
                x: 0.0,
                y: 0.0,
                w: 800.0,
                h: 600.0,
            },
        };

        let mut listener = ViewportListener::new(Some(viewport), 100.0, 100.0, 50.0, 50.0);

        // Initial check - visible
        let ((visible, _), _) = listener.check();
        assert!(visible);

        // Update viewport to move away from widget
        listener.viewport = Some(Viewport {
            parent: None,
            pos: Pos {
                x: 1000.0,
                y: 1000.0,
                w: 800.0,
                h: 600.0,
            },
            viewport: Pos {
                x: 1000.0,
                y: 1000.0,
                w: 800.0,
                h: 600.0,
            },
        });

        // Second check - should now be not visible
        let ((visible, prev_visible), _) = listener.check();
        assert!(!visible);
        assert_eq!(prev_visible, Some(true)); // Previous state was visible
    }

    #[test_log::test]
    fn test_viewport_listener_no_viewport() {
        // No viewport means always visible
        let mut listener = ViewportListener::new(None, 100.0, 100.0, 50.0, 50.0);

        let ((visible, _), (dist, _)) = listener.check();

        assert!(visible);
        assert!(dist < 0.001);
    }

    #[test_log::test]
    fn test_viewport_listener_no_change() {
        let viewport = Viewport {
            parent: None,
            pos: Pos {
                x: 0.0,
                y: 0.0,
                w: 800.0,
                h: 600.0,
            },
            viewport: Pos {
                x: 0.0,
                y: 0.0,
                w: 800.0,
                h: 600.0,
            },
        };

        let mut listener = ViewportListener::new(Some(viewport), 100.0, 100.0, 50.0, 50.0);

        // Initial check
        listener.check();

        // Second check with no viewport change - should have no previous values
        let ((visible, prev_visible), (_, prev_dist)) = listener.check();

        assert!(visible);
        assert!(prev_visible.is_none()); // No change
        assert!(prev_dist.is_none()); // No significant distance change
    }

    #[test_log::test]
    fn test_viewport_with_parent_both_visible() {
        let parent = Viewport {
            parent: None,
            pos: Pos {
                x: 0.0,
                y: 0.0,
                w: 1000.0,
                h: 1000.0,
            },
            viewport: Pos {
                x: 0.0,
                y: 0.0,
                w: 1000.0,
                h: 1000.0,
            },
        };

        let child = Viewport {
            parent: Some(Box::new(parent)),
            pos: Pos {
                x: 100.0,
                y: 100.0,
                w: 600.0,
                h: 400.0,
            },
            viewport: Pos {
                x: 100.0,
                y: 100.0,
                w: 600.0,
                h: 400.0,
            },
        };

        let mut listener = ViewportListener::new(Some(child), 200.0, 200.0, 50.0, 50.0);

        let ((visible, _), _) = listener.check();

        assert!(visible);
    }

    #[test_log::test]
    fn test_viewport_with_parent_child_not_visible() {
        let parent = Viewport {
            parent: None,
            pos: Pos {
                x: 0.0,
                y: 0.0,
                w: 1000.0,
                h: 1000.0,
            },
            viewport: Pos {
                x: 0.0,
                y: 0.0,
                w: 1000.0,
                h: 1000.0,
            },
        };

        let child = Viewport {
            parent: Some(Box::new(parent)),
            pos: Pos {
                x: 100.0,
                y: 100.0,
                w: 600.0,
                h: 400.0,
            },
            viewport: Pos {
                x: 100.0,
                y: 100.0,
                w: 600.0,
                h: 400.0,
            },
        };

        // Widget outside child viewport
        let mut listener = ViewportListener::new(Some(child), 1000.0, 1000.0, 50.0, 50.0);

        let ((visible, _), _) = listener.check();

        assert!(!visible);
    }

    #[test_log::test]
    fn test_viewport_with_parent_not_visible_propagates_invisibility() {
        // Grandparent viewport at origin with 100x100 size
        let grandparent = Viewport {
            parent: None,
            pos: Pos {
                x: 0.0,
                y: 0.0,
                w: 100.0,
                h: 100.0,
            },
            viewport: Pos {
                x: 0.0,
                y: 0.0,
                w: 100.0,
                h: 100.0,
            },
        };

        // Parent viewport positioned OUTSIDE grandparent (at 500,500)
        // This makes parent NOT visible within grandparent
        let parent = Viewport {
            parent: Some(Box::new(grandparent)),
            pos: Pos {
                x: 500.0,
                y: 500.0,
                w: 200.0,
                h: 200.0,
            },
            viewport: Pos {
                x: 500.0,
                y: 500.0,
                w: 200.0,
                h: 200.0,
            },
        };

        // Child viewport positioned within parent's bounds
        let child = Viewport {
            parent: Some(Box::new(parent)),
            pos: Pos {
                x: 550.0,
                y: 550.0,
                w: 100.0,
                h: 100.0,
            },
            viewport: Pos {
                x: 550.0,
                y: 550.0,
                w: 100.0,
                h: 100.0,
            },
        };

        // Widget positioned within child's bounds
        // Even though widget is within child, the parent is not visible in grandparent
        // so visibility should propagate as not visible
        let mut listener = ViewportListener::new(Some(child), 560.0, 560.0, 20.0, 20.0);

        let ((visible, _), (dist, _)) = listener.check();

        // Widget should NOT be visible because parent is outside grandparent's bounds
        assert!(!visible);
        // Distance should be > 0 since parent is outside grandparent
        assert!(dist > 0.0);
    }

    #[test_log::test]
    fn test_viewport_listener_distance_change_threshold() {
        let viewport = Viewport {
            parent: None,
            pos: Pos {
                x: 0.0,
                y: 0.0,
                w: 100.0,
                h: 100.0,
            },
            viewport: Pos {
                x: 0.0,
                y: 0.0,
                w: 100.0,
                h: 100.0,
            },
        };

        // Widget outside viewport - will have distance > 0
        let mut listener = ViewportListener::new(Some(viewport), 200.0, 200.0, 50.0, 50.0);

        // Initial check
        let ((visible, _), (initial_dist, _)) = listener.check();
        assert!(!visible);
        assert!(initial_dist > 0.0);

        // Second check with same position - distance should not be reported as changed
        // because the change threshold is 0.01
        let ((_, _), (_, prev_dist)) = listener.check();
        assert!(
            prev_dist.is_none(),
            "Distance change below threshold should not report previous distance"
        );
    }

    #[test_log::test]
    fn test_viewport_listener_distance_change_above_threshold() {
        // Widget outside viewport - will have distance > 0
        let mut listener = ViewportListener::new(
            Some(Viewport {
                parent: None,
                pos: Pos {
                    x: 0.0,
                    y: 0.0,
                    w: 100.0,
                    h: 100.0,
                },
                viewport: Pos {
                    x: 0.0,
                    y: 0.0,
                    w: 100.0,
                    h: 100.0,
                },
            }),
            200.0,
            200.0,
            50.0,
            50.0,
        );

        // Initial check
        let ((_, _), (initial_dist, _)) = listener.check();
        assert!(initial_dist > 0.0);

        // Move viewport significantly to change distance
        listener.viewport = Some(Viewport {
            parent: None,
            pos: Pos {
                x: 0.0,
                y: 0.0,
                w: 100.0,
                h: 100.0,
            },
            viewport: Pos {
                x: 150.0,
                y: 150.0,
                w: 100.0,
                h: 100.0,
            },
        });

        // Check again - distance should have changed significantly
        let ((_, _), (new_dist, prev_dist)) = listener.check();
        assert!(
            prev_dist.is_some(),
            "Significant distance change should report previous distance"
        );
        assert!(
            (new_dist - initial_dist).abs() > 0.01,
            "Distance should have changed significantly"
        );
    }

    #[test_log::test]
    fn test_viewport_listener_visibility_toggle_back_and_forth() {
        let mut listener = ViewportListener::new(
            Some(Viewport {
                parent: None,
                pos: Pos {
                    x: 0.0,
                    y: 0.0,
                    w: 100.0,
                    h: 100.0,
                },
                viewport: Pos {
                    x: 0.0,
                    y: 0.0,
                    w: 100.0,
                    h: 100.0,
                },
            }),
            10.0,
            10.0,
            50.0,
            50.0,
        );

        // Initial check - should be visible
        let ((visible, _), _) = listener.check();
        assert!(visible);

        // Move to not visible
        listener.viewport = Some(Viewport {
            parent: None,
            pos: Pos {
                x: 500.0,
                y: 500.0,
                w: 100.0,
                h: 100.0,
            },
            viewport: Pos {
                x: 500.0,
                y: 500.0,
                w: 100.0,
                h: 100.0,
            },
        });

        let ((visible, prev_visible), _) = listener.check();
        assert!(!visible);
        assert_eq!(prev_visible, Some(true));

        // Move back to visible
        listener.viewport = Some(Viewport {
            parent: None,
            pos: Pos {
                x: 0.0,
                y: 0.0,
                w: 100.0,
                h: 100.0,
            },
            viewport: Pos {
                x: 0.0,
                y: 0.0,
                w: 100.0,
                h: 100.0,
            },
        });

        let ((visible, prev_visible), _) = listener.check();
        assert!(visible);
        assert_eq!(prev_visible, Some(false));
    }
}