gpui-fast 0.1.20

gpui: GPUI with gpui-fast rendering and layout optimizations
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
// Modified by Longbridge for gpui-fast.
//! gpui-fast's bounds tree, which `gpui.rs` puts in place of upstream's
//! `bounds_tree.rs`. It hands out the same orderings upstream's does, from a
//! grid of cells rather than a tree, and replays last frame's orderings,
//! which is what drawing a retained view again costs most.

use crate::{Bounds, Half};
use std::{
    fmt::Debug,
    ops::{Add, Sub},
};

/// How many bounds a replay may compare against, counted over every search
/// it makes — for bounds that changed, and for bounds that might meet them —
/// before building the grid costs less than going on without it.
const REPLAY_SEARCH_BUDGET: usize = 1 << 15;

/// The side of a grid cell, in the units of the bounds. A frame's bounds are
/// mostly a few dozen scaled pixels across, so each takes a cell or a few.
const CELL_SIZE: f64 = 64.;

/// The most cells the grid spans along either axis. Bounds reaching past the
/// last cell are kept in it.
const MAX_CELLS_PER_AXIS: usize = 256;

/// No entry: the end of a cell's list.
const NONE: u32 = u32::MAX;

/// Hands out orderings for bounds inserted one after another, each one
/// greater than that of every bounds inserted before it that it intersects,
/// and no greater than it has to be, so that primitives that don't overlap
/// share an ordering and are drawn in one batch.
///
/// The bounds are kept in a uniform grid over the plane. Each cell lists the
/// bounds that reach into it, newest first, except those that cover it
/// whole: every search that reaches into the cell meets those, so the cell
/// keeps only the greatest of their orderings. Upstream kept an R-tree,
/// whose searches and splits cost several times as much for the few
/// thousand bounds of a frame, most of them a cell or a few across.
#[derive(Debug)]
pub(crate) struct BoundsTree<U>
where
    U: Clone + Debug + Default + PartialEq,
{
    grid: Grid<U>,
    /// The bounds with the greatest ordering so far, and that ordering: a
    /// search that meets it has its answer at once.
    max: Option<(Bounds<U>, u32)>,
    /// The bounds inserted since the tree was last cleared, in order, each
    /// with the ordering it was given.
    recorded: Vec<(Bounds<U>, u32)>,
    /// What `recorded` held when the tree was cleared.
    previous: Vec<(Bounds<U>, u32)>,
    /// Whether the tree is still being replayed rather than built: every
    /// ordering since it was cleared has been found without it, and it is
    /// built from `recorded` once that stops paying.
    replaying: bool,
    /// While replaying, every bounds whose entry differs from the one in the
    /// same position in `previous` — in its bounds or in its ordering — in
    /// both its old and its new form. An insert that matches `previous` and
    /// meets none of them has the ordering it had then.
    changed: ChangedBounds<U>,
    /// How many more bounds replaying may compare against, over every search
    /// it makes, before the tree is built instead.
    replay_search_budget: usize,
}

/// The grid a [`BoundsTree`] keeps its bounds in. Cell `(column, row)`
/// spans `column * CELL_SIZE` to `(column + 1) * CELL_SIZE` across, and
/// likewise down, except that the first and last column and row reach on
/// without end, so every point of the plane is in exactly one cell.
#[derive(Debug)]
struct Grid<U>
where
    U: Clone + Debug + Default + PartialEq,
{
    columns: usize,
    rows: usize,
    /// Row by row.
    cells: Vec<Cell>,
    /// Every cell's list, linked through `next`.
    entries: Vec<Entry<U>>,
    /// Bounds without a positive width and height. Such bounds may still
    /// meet others, `intersects` being what it is, but have no cells.
    degenerate: Vec<(Bounds<U>, u32)>,
}

#[derive(Clone, Copy, Debug)]
struct Cell {
    /// The newest entry of the cell's list.
    head: u32,
    /// The greatest ordering among the bounds that cover the cell whole.
    cover: u32,
    /// The greatest ordering among all the cell's bounds, covering or not.
    max: u32,
}

impl Cell {
    const EMPTY: Cell = Cell {
        head: NONE,
        cover: 0,
        max: 0,
    };
}

#[derive(Clone, Debug)]
struct Entry<U>
where
    U: Clone + Debug + Default + PartialEq,
{
    bounds: Bounds<U>,
    order: u32,
    /// The greatest ordering of this entry and every one after it in its
    /// list, so a search stops as soon as the rest can't raise its result.
    rest_max: u32,
    next: u32,
}

/// A bounds' extent along one axis, as the grid sees it.
#[derive(Clone, Copy)]
struct Span {
    start: f64,
    end: f64,
    first_cell: usize,
    last_cell: usize,
}

impl Span {
    fn new(start: f64, end: f64, cells: usize) -> Self {
        Span {
            start,
            end,
            first_cell: cell_at(start, cells),
            last_cell: cell_at(end, cells),
        }
    }

    /// Whether this span reaches into the interior of `cell`, of `cells`,
    /// rather than stopping at one of its edges.
    fn enters(&self, cell: usize, cells: usize) -> bool {
        self.start < cell_end(cell, cells) && self.end > cell_start(cell)
    }

    /// Whether this span covers all of `cell`, of `cells`.
    fn covers(&self, cell: usize, cells: usize) -> bool {
        self.start <= cell_start(cell) && self.end >= cell_end(cell, cells)
    }
}

fn cell_at(coordinate: f64, cells: usize) -> usize {
    // `as` truncates toward zero, which is flooring for all that isn't
    // clamped to the first cell anyway; it saturates, and turns NaN into 0.
    ((coordinate * (1. / CELL_SIZE)) as isize).clamp(0, cells as isize - 1) as usize
}

fn cell_start(cell: usize) -> f64 {
    if cell == 0 {
        f64::NEG_INFINITY
    } else {
        cell as f64 * CELL_SIZE
    }
}

fn cell_end(cell: usize, cells: usize) -> f64 {
    if cell + 1 == cells {
        f64::INFINITY
    } else {
        (cell + 1) as f64 * CELL_SIZE
    }
}

/// How many columns and rows of cells [`ChangedBounds`] marks, each
/// [`CELL_SIZE`] across; the first and last reach on without end, as the
/// grid's do.
const CHANGED_CELLS: usize = 64;

/// The bounds that changed while a tree is replayed, with the cells of a
/// coarse grid each reaches into marked, so that an insert reaching into no
/// marked cell is known to meet none of them without comparing it with each.
///
/// Two bounds that intersect overlap along each axis, and so do the cells
/// they span, which is what a search checks. Bounds whose far edge is not
/// past their near one, or not a number, span no cells to mark or check;
/// once one has changed, or for such a search, every changed bounds is
/// compared.
#[derive(Debug)]
struct ChangedBounds<U>
where
    U: Clone + Debug + Default + PartialEq,
{
    bounds: Vec<Bounds<U>>,
    /// Row by row, a bit per column.
    rows: [u64; CHANGED_CELLS],
    /// Whether a changed bounds spans no cells, so that none can be ruled
    /// out by them.
    unmarked: bool,
}

impl<U> ChangedBounds<U>
where
    U: Clone
        + Debug
        + PartialEq
        + PartialOrd
        + Add<U, Output = U>
        + Sub<Output = U>
        + Half
        + Default
        + Into<f64>,
{
    fn clear(&mut self) {
        self.bounds.clear();
        self.rows = [0; CHANGED_CELLS];
        self.unmarked = false;
    }

    /// The first and last column, and the first and last row, of the cells
    /// `bounds` spans, if it spans any.
    fn cells(bounds: &Bounds<U>) -> Option<(usize, usize, usize, usize)> {
        let left: f64 = bounds.origin.x.clone().into();
        let top: f64 = bounds.origin.y.clone().into();
        let right: f64 = (bounds.origin.x.clone() + bounds.size.width.clone()).into();
        let bottom: f64 = (bounds.origin.y.clone() + bounds.size.height.clone()).into();
        // False for a NaN at either end.
        (right >= left && bottom >= top).then(|| {
            (
                cell_at(left, CHANGED_CELLS),
                cell_at(right, CHANGED_CELLS),
                cell_at(top, CHANGED_CELLS),
                cell_at(bottom, CHANGED_CELLS),
            )
        })
    }

    /// The bits of the columns `first..=last`.
    fn columns(first: usize, last: usize) -> u64 {
        (u64::MAX >> (CHANGED_CELLS - 1 - last)) & (u64::MAX << first)
    }

    fn push(&mut self, bounds: &Bounds<U>) {
        match Self::cells(bounds) {
            Some((left, right, top, bottom)) => {
                let columns = Self::columns(left, right);
                for row in &mut self.rows[top..=bottom] {
                    *row |= columns;
                }
            }
            None => self.unmarked = true,
        }
        self.bounds.push(bounds.clone());
    }

    /// Whether `bounds` might meet a changed bounds: false only when it
    /// cannot.
    fn might_meet(&self, bounds: &Bounds<U>) -> bool {
        if self.bounds.is_empty() {
            return false;
        }
        if self.unmarked {
            return true;
        }
        match Self::cells(bounds) {
            Some((left, right, top, bottom)) => {
                let columns = Self::columns(left, right);
                self.rows[top..=bottom].iter().any(|row| row & columns != 0)
            }
            None => true,
        }
    }
}

impl<U> Grid<U>
where
    U: Clone
        + Debug
        + PartialEq
        + PartialOrd
        + Add<U, Output = U>
        + Sub<Output = U>
        + Half
        + Default
        + Into<f64>,
{
    fn clear(&mut self) {
        self.cells.fill(Cell::EMPTY);
        self.entries.clear();
        self.degenerate.clear();
    }

    /// Whether `bounds` has a positive width and height, and an origin that
    /// is a number, which is what it takes to be kept in cells or searched
    /// for through them.
    #[allow(clippy::eq_op)]
    fn has_area(bounds: &Bounds<U>) -> bool {
        bounds.size.width > U::default()
            && bounds.size.height > U::default()
            && bounds.origin.x == bounds.origin.x
            && bounds.origin.y == bounds.origin.y
    }

    /// Where `bounds` lies along each axis.
    fn spans(&self, bounds: &Bounds<U>) -> (Span, Span) {
        let right = bounds.origin.x.clone() + bounds.size.width.clone();
        let bottom = bounds.origin.y.clone() + bounds.size.height.clone();
        (
            Span::new(bounds.origin.x.clone().into(), right.into(), self.columns),
            Span::new(bounds.origin.y.clone().into(), bottom.into(), self.rows),
        )
    }

    /// How many columns and rows a grid needs to hold `bounds` without
    /// keeping it in its last column or row, if more than it has.
    fn needs(&self, bounds: &Bounds<U>) -> Option<(usize, usize)> {
        let right: f64 = (bounds.origin.x.clone() + bounds.size.width.clone()).into();
        let bottom: f64 = (bounds.origin.y.clone() + bounds.size.height.clone()).into();
        if right <= self.columns as f64 * CELL_SIZE && bottom <= self.rows as f64 * CELL_SIZE {
            return None;
        }
        let needed = |end: f64| {
            ((end / CELL_SIZE).ceil() as isize).clamp(1, MAX_CELLS_PER_AXIS as isize) as usize
        };
        let (columns, rows) = (
            needed(right).max(self.columns),
            needed(bottom).max(self.rows),
        );
        (columns > self.columns || rows > self.rows).then_some((columns, rows))
    }

    /// Makes the grid `columns` by `rows` and empties it.
    fn resize(&mut self, columns: usize, rows: usize) {
        self.columns = columns;
        self.rows = rows;
        self.cells.clear();
        self.cells.resize(columns * rows, Cell::EMPTY);
        self.entries.clear();
        self.degenerate.clear();
    }

    fn add(&mut self, bounds: &Bounds<U>, order: u32) {
        if !Self::has_area(bounds) {
            self.degenerate.push((bounds.clone(), order));
            return;
        }
        let (x, y) = self.spans(bounds);
        for row in y.first_cell..=y.last_cell {
            let covers_row = y.covers(row, self.rows);
            for column in x.first_cell..=x.last_cell {
                let cell = &mut self.cells[row * self.columns + column];
                cell.max = cell.max.max(order);
                if covers_row && x.covers(column, self.columns) {
                    cell.cover = cell.cover.max(order);
                } else {
                    let rest_max = match self.entries.get(cell.head as usize) {
                        Some(next) => next.rest_max.max(order),
                        None => order,
                    };
                    let entry = self.entries.len() as u32;
                    self.entries.push(Entry {
                        bounds: bounds.clone(),
                        order,
                        rest_max,
                        next: cell.head,
                    });
                    cell.head = entry;
                }
            }
        }
    }

    /// The greatest ordering among the bounds that intersect `query`, which
    /// has a positive width and height, or 0.
    ///
    /// Two such bounds that intersect share a point inside both, and the
    /// cell holding that point lists one of them if it doesn't cover it, and
    /// the query reaches into its interior. A bounds that covers a cell whole
    /// meets every query that reaches into its interior, so the cell's cover
    /// counts there without looking at the bounds.
    fn max_intersecting(&self, query: &Bounds<U>) -> u32 {
        let mut max = self
            .degenerate
            .iter()
            .filter(|(bounds, _)| bounds.intersects(query))
            .map(|(_, order)| *order)
            .max()
            .unwrap_or(0);
        let (x, y) = self.spans(query);
        for row in y.first_cell..=y.last_cell {
            let enters_row = y.enters(row, self.rows);
            for column in x.first_cell..=x.last_cell {
                let cell = &self.cells[row * self.columns + column];
                if cell.max <= max {
                    continue;
                }
                if cell.cover > max && enters_row && x.enters(column, self.columns) {
                    max = cell.cover;
                }
                let mut entry_ix = cell.head;
                while let Some(entry) = self.entries.get(entry_ix as usize) {
                    if entry.rest_max <= max {
                        break;
                    }
                    if entry.order > max && entry.bounds.intersects(query) {
                        max = entry.order;
                    }
                    entry_ix = entry.next;
                }
            }
        }
        max
    }
}

impl<U> BoundsTree<U>
where
    U: Clone
        + Debug
        + PartialEq
        + PartialOrd
        + Add<U, Output = U>
        + Sub<Output = U>
        + Half
        + Default
        + Into<f64>,
{
    /// Clears all bounds from the tree.
    ///
    /// What was inserted since the last clear is kept aside: a frame usually
    /// inserts the same bounds in the same order as the one before it, and an
    /// ordering depends on nothing but the bounds inserted before it, so as
    /// long as that holds the orderings can be handed out again as they were.
    pub fn clear(&mut self) {
        self.grid.clear();
        self.max = None;
        std::mem::swap(&mut self.previous, &mut self.recorded);
        self.recorded.clear();
        self.replaying = true;
        self.changed.clear();
        self.replay_search_budget = REPLAY_SEARCH_BUDGET;
    }

    /// Clears the tree and forgets what was inserted before, so the next fill
    /// is ordered from scratch rather than replayed.
    #[cfg(test)]
    pub fn forget(&mut self) {
        self.clear();
        self.previous.clear();
        self.replaying = false;
    }

    /// Inserts bounds into the tree and returns its assigned ordering.
    ///
    /// The ordering is one greater than the maximum ordering of any
    /// existing bounds that intersect with the new bounds.
    pub fn insert(&mut self, new_bounds: Bounds<U>) -> u32 {
        if self.replaying {
            if let Some(ordering) = self.replay(&new_bounds) {
                self.recorded.push((new_bounds, ordering));
                return ordering;
            }
            self.replaying = false;
            self.build_from_recorded();
        }

        let ordering = self.find_max_ordering(&new_bounds) + 1;
        self.add(&new_bounds, ordering);
        self.recorded.push((new_bounds, ordering));
        ordering
    }

    /// The ordering `bounds` is given while the tree is being replayed, or
    /// `None` once finding it without the tree would cost more than building
    /// the tree.
    ///
    /// An ordering is one more than the greatest among the bounds inserted
    /// before it that it meets. If `bounds` is what was inserted at this
    /// position last time, and meets nothing that was, or is now, different
    /// from last time before it, then everything it meets and every ordering
    /// among them is as it was, and so is its own. Otherwise its ordering is
    /// worked out from what has been inserted so far, and if that differs
    /// from last time, the bounds join the ones that changed.
    fn replay(&mut self, bounds: &Bounds<U>) -> Option<u32> {
        let previous = self.previous.get(self.recorded.len());
        if let Some((previous_bounds, ordering)) = previous
            && previous_bounds == bounds
        {
            let meets_changed = self.changed.might_meet(bounds) && {
                self.replay_search_budget = self
                    .replay_search_budget
                    .checked_sub(self.changed.bounds.len())?;
                self.changed
                    .bounds
                    .iter()
                    .any(|changed| changed.intersects(bounds))
            };
            if !meets_changed {
                return Some(*ordering);
            }
        }

        self.replay_search_budget = self.replay_search_budget.checked_sub(self.recorded.len())?;
        let ordering = self
            .recorded
            .iter()
            .filter(|(other, _)| other.intersects(bounds))
            .map(|(_, ordering)| *ordering)
            .max()
            .unwrap_or(0)
            + 1;
        match previous {
            Some((previous_bounds, previous_ordering)) => {
                if previous_bounds != bounds {
                    self.changed.push(previous_bounds);
                    self.changed.push(bounds);
                } else if *previous_ordering != ordering {
                    self.changed.push(bounds);
                }
            }
            None => self.changed.push(bounds),
        }
        Some(ordering)
    }

    /// Adds `bounds` with `ordering` to the grid, growing it first if the
    /// bounds reach past it.
    fn add(&mut self, bounds: &Bounds<U>, ordering: u32) {
        if Grid::has_area(bounds)
            && let Some((columns, rows)) = self.grid.needs(bounds)
        {
            self.grid.resize(columns, rows);
            for (recorded, recorded_ordering) in &self.recorded {
                self.grid.add(recorded, *recorded_ordering);
            }
        }
        self.grid.add(bounds, ordering);
        if self.max.as_ref().is_none_or(|(_, max)| *max < ordering) {
            self.max = Some((bounds.clone(), ordering));
        }
    }

    /// Builds the grid from what has been inserted since it was cleared,
    /// whose orderings were handed out without it. Their orderings are
    /// known, so there is nothing to search for, only bounds to place.
    fn build_from_recorded(&mut self) {
        let mut size = (self.grid.columns, self.grid.rows);
        for (bounds, _) in &self.recorded {
            if Grid::has_area(bounds)
                && let Some((columns, rows)) = self.grid.needs(bounds)
            {
                size = (size.0.max(columns), size.1.max(rows));
            }
        }
        if size != (self.grid.columns, self.grid.rows) {
            self.grid.resize(size.0, size.1);
        }
        for (bounds, ordering) in &self.recorded {
            self.grid.add(bounds, *ordering);
            if self.max.as_ref().is_none_or(|(_, max)| max < ordering) {
                self.max = Some((bounds.clone(), *ordering));
            }
        }
    }

    /// Finds the maximum ordering among all bounds that intersect with the query.
    fn find_max_ordering(&self, query: &Bounds<U>) -> u32 {
        if let Some((max_bounds, max)) = &self.max
            && query.intersects(max_bounds)
        {
            return *max;
        }
        if Grid::has_area(query) {
            self.grid.max_intersecting(query)
        } else {
            // Without an area of its own the query may miss the interior of
            // every cell it touches, so the covers can't answer for it.
            self.recorded
                .iter()
                .filter(|(bounds, _)| bounds.intersects(query))
                .map(|(_, ordering)| *ordering)
                .max()
                .unwrap_or(0)
        }
    }
}

impl<U> Default for BoundsTree<U>
where
    U: Clone + Debug + Default + PartialEq,
{
    fn default() -> Self {
        BoundsTree {
            grid: Grid {
                columns: 1,
                rows: 1,
                cells: vec![Cell::EMPTY],
                entries: Vec::new(),
                degenerate: Vec::new(),
            },
            max: None,
            recorded: Vec::new(),
            previous: Vec::new(),
            replaying: false,
            changed: ChangedBounds {
                bounds: Vec::new(),
                rows: [0; CHANGED_CELLS],
                unmarked: false,
            },
            replay_search_budget: REPLAY_SEARCH_BUDGET,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{BoundsTree, CELL_SIZE, CHANGED_CELLS, MAX_CELLS_PER_AXIS};
    use crate::{Bounds, Point, Size};
    use rand::{Rng, SeedableRng};

    #[test]
    fn test_insert() {
        let mut tree = BoundsTree::<f32>::default();
        let bounds1 = Bounds {
            origin: Point { x: 0.0, y: 0.0 },
            size: Size {
                width: 10.0,
                height: 10.0,
            },
        };
        let bounds2 = Bounds {
            origin: Point { x: 5.0, y: 5.0 },
            size: Size {
                width: 10.0,
                height: 10.0,
            },
        };
        let bounds3 = Bounds {
            origin: Point { x: 10.0, y: 10.0 },
            size: Size {
                width: 10.0,
                height: 10.0,
            },
        };

        // Insert the bounds into the tree and verify the order is correct
        assert_eq!(tree.insert(bounds1), 1);
        assert_eq!(tree.insert(bounds2), 2);
        assert_eq!(tree.insert(bounds3), 3);

        // Insert non-overlapping bounds and verify they can reuse orders
        let bounds4 = Bounds {
            origin: Point { x: 20.0, y: 20.0 },
            size: Size {
                width: 10.0,
                height: 10.0,
            },
        };
        let bounds5 = Bounds {
            origin: Point { x: 40.0, y: 40.0 },
            size: Size {
                width: 10.0,
                height: 10.0,
            },
        };
        let bounds6 = Bounds {
            origin: Point { x: 25.0, y: 25.0 },
            size: Size {
                width: 10.0,
                height: 10.0,
            },
        };
        assert_eq!(tree.insert(bounds4), 1); // bounds4 does not overlap with bounds1, bounds2, or bounds3
        assert_eq!(tree.insert(bounds5), 1); // bounds5 does not overlap with any other bounds
        assert_eq!(tree.insert(bounds6), 2); // bounds6 overlaps with bounds4, so it should have a different order
    }

    #[test]
    fn test_random_iterations() {
        let max_bounds = 100;
        for seed in 1..=1000 {
            // let seed = 44;
            let mut tree = BoundsTree::default();
            let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64);
            let mut expected_quads: Vec<(Bounds<f32>, u32)> = Vec::new();

            // Insert a random number of random AABBs into the tree.
            let num_bounds = rng.random_range(1..=max_bounds);
            for _ in 0..num_bounds {
                let min_x: f32 = rng.random_range(-100.0..100.0);
                let min_y: f32 = rng.random_range(-100.0..100.0);
                let width: f32 = rng.random_range(0.0..50.0);
                let height: f32 = rng.random_range(0.0..50.0);
                let bounds = Bounds {
                    origin: Point { x: min_x, y: min_y },
                    size: Size { width, height },
                };

                let expected_ordering = expected_quads
                    .iter()
                    .filter_map(|quad| quad.0.intersects(&bounds).then_some(quad.1))
                    .max()
                    .unwrap_or(0)
                    + 1;
                expected_quads.push((bounds, expected_ordering));

                // Insert the AABB into the tree and collect intersections.
                let actual_ordering = tree.insert(bounds);
                assert_eq!(actual_ordering, expected_ordering);
            }
        }
    }

    fn random_bounds(rng: &mut rand::rngs::StdRng) -> Bounds<f32> {
        Bounds {
            origin: Point {
                x: rng.random_range(-100.0..100.0),
                y: rng.random_range(-100.0..100.0),
            },
            size: Size {
                width: rng.random_range(0.0..50.0),
                height: rng.random_range(0.0..50.0),
            },
        }
    }
    fn fill(tree: &mut BoundsTree<f32>, frame: &[Bounds<f32>]) {
        tree.clear();
        let mut inserted: Vec<(Bounds<f32>, u32)> = Vec::new();
        for bounds in frame {
            let expected = inserted
                .iter()
                .filter_map(|(other, order)| other.intersects(bounds).then_some(*order))
                .max()
                .unwrap_or(0)
                + 1;
            assert_eq!(tree.insert(*bounds), expected);
            inserted.push((*bounds, expected));
        }
    }

    /// A tree hands out last fill's orderings again while the bounds come in
    /// as they did then, and builds itself the moment they stop. Each frame
    /// here follows the one before for a while and then goes its own way, or
    /// repeats it, or differs from the start, and every ordering is checked
    /// against every bounds inserted before it in that frame.
    #[test]
    fn replaying_the_last_fill_gives_what_inserting_it_would() {
        for seed in 1..=300 {
            let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
            let mut tree = BoundsTree::default();
            let count = rng.random_range(1..=120);
            let first: Vec<_> = (0..count).map(|_| random_bounds(&mut rng)).collect();
            fill(&mut tree, &first);

            // Follows the last fill for a while, then diverges.
            let kept = rng.random_range(0..=count);
            let mut second: Vec<_> = first[..kept].to_vec();
            second.extend((0..rng.random_range(0..=60)).map(|_| random_bounds(&mut rng)));
            fill(&mut tree, &second);

            // Repeats it exactly.
            fill(&mut tree, &second);

            // Differs from the first bounds on.
            let third: Vec<_> = (0..count).map(|_| random_bounds(&mut rng)).collect();
            fill(&mut tree, &third);
        }
    }

    /// A frame that repeats the last one but for a few bounds scattered
    /// through it — a label grown by a digit, a row inserted or taken out —
    /// is replayed past each of them, and must still give every bounds the
    /// ordering inserting it afresh would. Frames with changes enough to
    /// exhaust what replaying may search are built as before, from wherever
    /// that happens.
    #[test]
    fn replaying_past_scattered_changes_gives_what_inserting_it_would() {
        for seed in 1..=300 {
            let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
            let mut tree = BoundsTree::default();
            let count = rng.random_range(1..=if seed % 10 == 0 { 800 } else { 150 });
            let mut frame: Vec<_> = (0..count).map(|_| random_bounds(&mut rng)).collect();
            fill(&mut tree, &frame);
            for _ in 0..6 {
                for _ in 0..rng.random_range(0..=count / 8 + 1) {
                    let at = rng.random_range(0..frame.len().max(1));
                    match rng.random_range(0..10) {
                        0 if !frame.is_empty() => {
                            frame.remove(at);
                        }
                        1 => frame.insert(at.min(frame.len()), random_bounds(&mut rng)),
                        _ if !frame.is_empty() => {
                            let grown = &mut frame[at];
                            grown.size.width += rng.random_range(-5.0..5.0);
                        }
                        _ => {}
                    }
                }
                fill(&mut tree, &frame);
            }
        }
    }

    /// The random cases above stay small enough that few nodes ever split
    /// more than once. These are large enough for splits to reach several
    /// levels up, and still checked against every bounds inserted before.
    #[test]
    fn test_random_iterations_deep_enough_to_split_every_level() {
        for seed in 1..=10 {
            let mut tree = BoundsTree::default();
            let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64);
            let mut expected_quads: Vec<(Bounds<f32>, u32)> = Vec::new();
            for _ in 0..2000 {
                let bounds = Bounds {
                    origin: Point {
                        x: rng.random_range(-1000.0..1000.0),
                        y: rng.random_range(-1000.0..1000.0),
                    },
                    size: Size {
                        width: rng.random_range(0.0..80.0),
                        height: rng.random_range(0.0..80.0),
                    },
                };
                let expected_ordering = expected_quads
                    .iter()
                    .filter_map(|quad| quad.0.intersects(&bounds).then_some(quad.1))
                    .max()
                    .unwrap_or(0)
                    + 1;
                expected_quads.push((bounds, expected_ordering));
                assert_eq!(tree.insert(bounds), expected_ordering);
            }
        }
    }

    /// A frame repeating the last one but for a few bounds, where bounds of
    /// every awkward kind come and go, and lie anywhere — past the cells
    /// changed bounds are marked in too — is still replayed only as far as
    /// inserting it afresh would give.
    #[test]
    fn replaying_past_awkward_changes_gives_what_inserting_it_would() {
        let edge = CELL_SIZE as f32;
        let coordinate = |rng: &mut rand::rngs::StdRng| match rng.random_range(0..14) {
            0 => f32::INFINITY,
            1 => f32::NEG_INFINITY,
            2 => f32::NAN,
            3 => rng.random_range(-4..(CHANGED_CELLS as i32 + 4)) as f32 * edge,
            4..8 => rng.random_range(-3..8) as f32 * edge,
            8 => rng.random_range(0.0..(CHANGED_CELLS as f32 + 8.) * edge),
            _ => rng.random_range(-2.0 * edge..6.0 * edge),
        };
        let length = |rng: &mut rand::rngs::StdRng| match rng.random_range(0..12) {
            0 => 0.,
            1 => -rng.random_range(0.0..edge),
            2 => f32::INFINITY,
            3 => f32::NAN,
            4..7 => rng.random_range(0..4) as f32 * edge,
            _ => rng.random_range(0.0..3.0 * edge),
        };
        let awkward = |rng: &mut rand::rngs::StdRng| Bounds {
            origin: Point {
                x: coordinate(rng),
                y: coordinate(rng),
            },
            size: Size {
                width: length(rng),
                height: length(rng),
            },
        };
        for seed in 1..=400 {
            let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
            let mut tree = BoundsTree::default();
            let mut frame: Vec<_> = (0..rng.random_range(1..200))
                .map(|_| awkward(&mut rng))
                .collect();
            fill(&mut tree, &frame);
            for _ in 0..4 {
                for _ in 0..rng.random_range(0..6) {
                    let at = rng.random_range(0..frame.len());
                    frame[at] = awkward(&mut rng);
                }
                fill(&mut tree, &frame);
            }
        }
    }

    /// Bounds the grid can't simply file under the cells they reach into:
    /// ones on cells' edges, covering cells whole or reaching past the grid,
    /// without a width or height, negative, infinite or not a number. Each
    /// still gets the ordering comparing it with every bounds before it gives.
    #[test]
    fn awkward_bounds_are_ordered_as_comparing_them_with_all_would() {
        let edge = CELL_SIZE as f32;
        let coordinate = |rng: &mut rand::rngs::StdRng| match rng.random_range(0..12) {
            0 => f32::INFINITY,
            1 => f32::NEG_INFINITY,
            2 => f32::NAN,
            3 => rng.random_range(-4..(MAX_CELLS_PER_AXIS as i32 + 4)) as f32 * edge,
            4..8 => rng.random_range(-3..8) as f32 * edge,
            _ => rng.random_range(-2.0 * edge..6.0 * edge),
        };
        let length = |rng: &mut rand::rngs::StdRng| match rng.random_range(0..10) {
            0 => 0.,
            1 => -rng.random_range(0.0..edge),
            2 => f32::INFINITY,
            3..6 => rng.random_range(0..4) as f32 * edge,
            _ => rng.random_range(0.0..3.0 * edge),
        };
        for seed in 1..=400 {
            let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
            let mut tree = BoundsTree::default();
            for _ in 0..3 {
                let frame: Vec<_> = (0..rng.random_range(1..200))
                    .map(|_| Bounds {
                        origin: Point {
                            x: coordinate(&mut rng),
                            y: coordinate(&mut rng),
                        },
                        size: Size {
                            width: length(&mut rng),
                            height: length(&mut rng),
                        },
                    })
                    .collect();
                tree.forget();
                let mut inserted: Vec<(Bounds<f32>, u32)> = Vec::new();
                for bounds in &frame {
                    let expected = inserted
                        .iter()
                        .filter_map(|(other, order)| other.intersects(bounds).then_some(*order))
                        .max()
                        .unwrap_or(0)
                        + 1;
                    assert_eq!(tree.insert(*bounds), expected, "seed {seed}: {bounds:?}");
                    inserted.push((*bounds, expected));
                }
            }
        }
    }
}