Skip to main content

devpage_design/display/
list.rs

1//! The list: every chunk by paint order and the top-level R-tree over them
2//! in the design's coordinates — what touches a rectangle, in log time —
3//! with the extent that keeps the drawing's area without a walk.
4
5use std::collections::{BTreeMap, HashMap};
6
7use kurbo::{BezPath, Rect as KRect, Shape, Vec2};
8use rstar::{AABB, RTree, RTreeObject};
9
10use super::{Draw, Frame};
11
12use super::*;
13
14/// What an entry of a space's index is: a chunk, by its order, or a run
15/// whose children are spaces of their own.
16#[derive(Clone, PartialEq, Debug)]
17pub(super) enum What {
18    /// A chunk, by its paint order.
19    Chunk(Order),
20    /// A run, whose children's spaces are searched in turn.
21    Run(RunId),
22}
23
24/// An entry in a space's index.
25#[derive(Clone, PartialEq)]
26pub(super) struct Entry {
27    /// The chunk or run it stands for.
28    pub(super) what: What,
29    /// What it reaches, in its space's coordinates.
30    pub(super) bounds: KRect,
31}
32
33impl RTreeObject for Entry {
34    type Envelope = AABB<[f64; 2]>;
35    fn envelope(&self) -> Self::Envelope {
36        aabb(self.bounds)
37    }
38}
39
40/// A chunk a query found: its order, where its space's origin is in the
41/// design's coordinates, and what cuts it from outside its space.
42pub(super) struct Found<'a> {
43    /// The chunk's paint order: its node's order keys from the root.
44    pub(super) order: &'a Order,
45    /// Where the chunk's space's origin is, in the design's coordinates.
46    pub(super) at: Vec2,
47    /// What cuts the chunk from outside its space, in the design's
48    /// coordinates; `None` when nothing does.
49    pub(super) cut: Option<KRect>,
50}
51
52/// A multiset of edges that knows its least and greatest in log time: the
53/// drawing's area kept from its chunks' covers as they come and go.
54#[derive(Default)]
55pub(super) struct Extent {
56    /// How many rectangles have each left edge.
57    x0: BTreeMap<i64, usize>,
58    /// How many rectangles have each top edge.
59    y0: BTreeMap<i64, usize>,
60    /// How many rectangles have each right edge.
61    x1: BTreeMap<i64, usize>,
62    /// How many rectangles have each bottom edge.
63    y1: BTreeMap<i64, usize>,
64}
65
66/// An edge as a key: to a millionth of a pixel, exactly ordered.
67pub(super) fn key(v: f64) -> i64 {
68    (v * 1e6).round() as i64
69}
70
71impl Extent {
72    /// Counts `r`'s edges in.
73    pub(super) fn add(&mut self, r: KRect) {
74        for (m, v) in [
75            (&mut self.x0, r.x0),
76            (&mut self.y0, r.y0),
77            (&mut self.x1, r.x1),
78            (&mut self.y1, r.y1),
79        ] {
80            *m.entry(key(v)).or_default() += 1;
81        }
82    }
83
84    /// Counts `r`'s edges out; an edge never counted in is left alone.
85    pub(super) fn remove(&mut self, r: KRect) {
86        for (m, v) in [
87            (&mut self.x0, r.x0),
88            (&mut self.y0, r.y0),
89            (&mut self.x1, r.x1),
90            (&mut self.y1, r.y1),
91        ] {
92            let k = key(v);
93            if let Some(n) = m.get_mut(&k) {
94                *n -= 1;
95                if *n == 0 {
96                    m.remove(&k);
97                }
98            }
99        }
100    }
101
102    /// The least rectangle holding every one counted in; `None` when there is
103    /// none.
104    pub(super) fn rect(&self) -> Option<KRect> {
105        let low = |m: &BTreeMap<i64, usize>| m.keys().next().map(|k| *k as f64 / 1e6);
106        let high = |m: &BTreeMap<i64, usize>| m.keys().next_back().map(|k| *k as f64 / 1e6);
107        Some(KRect::new(
108            low(&self.x0)?,
109            low(&self.y0)?,
110            high(&self.x1)?,
111            high(&self.y1)?,
112        ))
113    }
114}
115
116/// The display list: chunks by paint order, the property trees, and the
117/// index over the chunks — the design's own space, and a space for each
118/// child of each run.
119pub struct List {
120    /// The transform, clip and effect trees its chunks are drawn under.
121    pub trees: Trees,
122    /// Every chunk, by its paint order.
123    pub(super) chunks: BTreeMap<Order, Chunk>,
124    /// The index of the design's own space.
125    pub(super) root: SpaceIndex,
126    /// Every run, by its slot; `None` for a slot freed and not yet reused.
127    pub(super) runs: Vec<Option<Run>>,
128    /// The slots of `runs` free to reuse.
129    pub(super) free_runs: Vec<RunId>,
130    /// Children whose spaces changed since their runs last summed them.
131    pub(super) stale: std::collections::BTreeSet<(RunId, crate::tree::OrderKey)>,
132    /// The root of the transform tree: the design's own coordinates.
133    pub root_transform: Id,
134    /// The root of the clip tree: the drawing's own area.
135    pub root_clip: Id,
136    /// The drawing's area.
137    pub area: Frame,
138}
139
140impl Default for List {
141    fn default() -> Self {
142        List::new()
143    }
144}
145
146impl List {
147    /// An empty list: the root transform, and the root clip — to an empty
148    /// area until [`List::set_area`].
149    pub fn new() -> List {
150        let mut trees = Trees::default();
151        let root_transform = trees.transforms.add(Transform {
152            parent: None,
153            offset: Vec2::ZERO,
154            item: None,
155        });
156        let root_clip = trees.clips.add(Clip {
157            parent: None,
158            transform: root_transform,
159            path: BezPath::new(),
160        });
161        List {
162            trees,
163            chunks: BTreeMap::new(),
164            root: SpaceIndex::default(),
165            runs: Vec::new(),
166            free_runs: Vec::new(),
167            stale: Default::default(),
168            root_transform,
169            root_clip,
170            area: Frame {
171                x: 0.0,
172                y: 0.0,
173                width: 0.0,
174                height: 0.0,
175            },
176        }
177    }
178
179    /// A list of one chunk at the origin, `area` its drawing, built by
180    /// `build`: for painting a few commands by themselves.
181    pub fn of(area: Frame, build: impl FnOnce(&mut Builder)) -> List {
182        let mut list = List::new();
183        list.set_area(area);
184        let (t, c) = (list.root_transform, list.root_clip);
185        let mut b = Builder::new(&mut list.trees, t, c, None);
186        build(&mut b);
187        let made = b.finish();
188        list.put(
189            Vec::new(),
190            Chunk::new(t, Space::Root, Vec2::ZERO, made, Vec::new(), None, None),
191        );
192        list
193    }
194
195    /// Puts the chunks made for a new scene in, those in the design's own
196    /// space bulk-loaded into its index with what is in it already.
197    pub fn load(&mut self, chunks: Vec<(Order, Chunk)>) {
198        let mut entries: Vec<Entry> = std::mem::take(&mut self.root.index).into_iter().collect();
199        for (order, chunk) in chunks {
200            if chunk.space != Space::Root {
201                self.put(order, chunk);
202                continue;
203            }
204            if let Some(r) = chunk.cover() {
205                self.root.covers.add(r);
206            }
207            if let Some(bounds) = chunk.reach() {
208                entries.push(Entry {
209                    what: What::Chunk(order.clone()),
210                    bounds,
211                });
212            }
213            self.chunks.insert(order, chunk);
214        }
215        self.root.index = RTree::bulk_load(entries);
216        self.flush();
217    }
218
219    /// The drawing's area becomes `area`, and the root clip with it.
220    pub fn set_area(&mut self, area: Frame) {
221        self.area = area;
222        self.trees.clips.get_mut(self.root_clip).path = frame_rect(area).to_path(0.1);
223    }
224
225    /// What the chunks cover together, before rounding.
226    pub fn covered(&self) -> Option<KRect> {
227        self.root.covers.rect()
228    }
229
230    /// The chunk at `order`, if there is one.
231    pub fn chunk(&self, order: &Order) -> Option<&Chunk> {
232        self.chunks.get(order)
233    }
234
235    /// Every chunk, in paint order.
236    pub fn chunks(&self) -> impl Iterator<Item = (&Order, &Chunk)> {
237        self.chunks.iter()
238    }
239
240    /// The index of a space.
241    fn local(&mut self, space: &Space) -> &mut SpaceIndex {
242        match space {
243            Space::Root => &mut self.root,
244            Space::Item(r, k) => self.runs[*r as usize]
245                .as_mut()
246                .expect("a live run")
247                .spaces
248                .entry(k.clone())
249                .or_default(),
250        }
251    }
252
253    /// Takes the chunk at `order` out of the list and its space's index.
254    pub fn take(&mut self, order: &Order) -> Option<Chunk> {
255        let chunk = self.chunks.remove(order)?;
256        let (reach, cover, space) = (chunk.reach(), chunk.cover(), chunk.space.clone());
257        if self.space_lives(&space) {
258            let local = self.local(&space);
259            if let Some(bounds) = reach {
260                local.index.remove(&Entry {
261                    what: What::Chunk(order.clone()),
262                    bounds,
263                });
264            }
265            if let Some(r) = cover {
266                local.covers.remove(r);
267            }
268            self.touch(&space);
269        }
270        Some(chunk)
271    }
272
273    /// Puts a chunk in the list and its space's index.
274    pub fn put(&mut self, order: Order, chunk: Chunk) {
275        let (reach, cover, space) = (chunk.reach(), chunk.cover(), chunk.space.clone());
276        let local = self.local(&space);
277        if let Some(bounds) = reach {
278            local.index.insert(Entry {
279                what: What::Chunk(order.clone()),
280                bounds,
281            });
282        }
283        if let Some(r) = cover {
284            local.covers.add(r);
285        }
286        self.touch(&space);
287        self.chunks.insert(order, chunk);
288    }
289
290    /// Whether `space` is still there: the design's own, or a child's of a run
291    /// not removed.
292    fn space_lives(&self, space: &Space) -> bool {
293        match space {
294            Space::Root => true,
295            Space::Item(r, _) => self.runs.get(*r as usize).is_some_and(|r| r.is_some()),
296        }
297    }
298
299    /// Marks a space's run child as needing its run to sum it again.
300    fn touch(&mut self, space: &Space) {
301        if let Space::Item(r, k) = space {
302            self.stale.insert((*r, k.clone()));
303        }
304    }
305
306    /// A new run, in `space`, with no children yet.
307    pub fn add_run(&mut self, space: Space) -> RunId {
308        let run = Run::new(space);
309        match self.free_runs.pop() {
310            Some(id) => {
311                self.runs[id as usize] = Some(run);
312                id
313            }
314            None => {
315                self.runs.push(Some(run));
316                (self.runs.len() - 1) as RunId
317            }
318        }
319    }
320
321    /// The run `id`; it must be live.
322    pub fn run(&self, id: RunId) -> &Run {
323        self.runs[id as usize].as_ref().expect("a live run")
324    }
325
326    /// The run `id`, to change; it must be live.
327    pub fn run_mut(&mut self, id: RunId) -> &mut Run {
328        self.runs[id as usize].as_mut().expect("a live run")
329    }
330
331    /// Takes a run out, its entry and cover with it; its children's chunks
332    /// must be gone already.
333    pub fn remove_run(&mut self, id: RunId) {
334        self.place_run(id, None, None);
335        let space = self.run(id).space.clone();
336        self.runs[id as usize] = None;
337        self.free_runs.push(id);
338        self.stale.retain(|(r, _)| *r != id);
339        self.touch(&space);
340    }
341
342    /// Puts a run's child in its sums, as `placed` — or, with `None`, takes
343    /// it out, its space with it.
344    pub fn place_child(&mut self, id: RunId, key: crate::tree::OrderKey, placed: Option<Placed>) {
345        let run = self.run_mut(id);
346        match placed {
347            Some(p) => run.set(key.clone(), p),
348            None => {
349                run.unset(&key);
350                run.spaces.remove(&key);
351            }
352        }
353        self.stale.remove(&(id, key));
354        self.resum(id);
355    }
356
357    /// The run's entry and cover in its space made again from its sums —
358    /// after where it places its children changed.
359    pub fn resum(&mut self, id: RunId) {
360        let (reach, cover) = self.run(id).extents();
361        self.place_run(id, reach, cover);
362    }
363
364    /// Puts run `id`'s entry and cover in its space's index as `reach` and
365    /// `cover`, in place of what it had there.
366    fn place_run(&mut self, id: RunId, reach: Option<KRect>, cover: Option<KRect>) {
367        let (space, old_reach, old_cover) = {
368            let run = self.run(id);
369            (run.space.clone(), run.entry, run.cover)
370        };
371        if old_reach == reach && old_cover == cover {
372            return;
373        }
374        let local = self.local(&space);
375        if let Some(bounds) = old_reach {
376            local.index.remove(&Entry {
377                what: What::Run(id),
378                bounds,
379            });
380        }
381        if let Some(r) = old_cover {
382            local.covers.remove(r);
383        }
384        if let Some(bounds) = reach {
385            local.index.insert(Entry {
386                what: What::Run(id),
387                bounds,
388            });
389        }
390        if let Some(r) = cover {
391            local.covers.add(r);
392        }
393        let run = self.run_mut(id);
394        run.entry = reach;
395        run.cover = cover;
396        self.touch(&space);
397    }
398
399    /// Sums again every run child whose space changed, and every run around
400    /// it, out to the design's own space.
401    pub fn flush(&mut self) {
402        while let Some((r, k)) = self.stale.pop_last() {
403            if !self.space_lives(&Space::Item(r, k.clone())) {
404                continue;
405            }
406            let run = self.run_mut(r);
407            if let Some(p) = run.items.get(&k).cloned() {
408                run.set(k, p);
409            }
410            self.resum(r);
411        }
412    }
413
414    /// Frees the property-tree nodes a chunk's own layers made.
415    pub fn free(&mut self, made: &Made) {
416        for &c in &made.clips {
417            self.trees.clips.remove(c);
418        }
419        for &e in &made.effects {
420            self.trees.effects.remove(e);
421        }
422    }
423
424    /// The chunks whose entries touch `rect`, in paint order — those smaller
425    /// than `pixel` both ways skipped — through every run's children that
426    /// can touch it.
427    pub(super) fn found(&self, rect: KRect, pixel: f64) -> Vec<Found<'_>> {
428        let mut out = Vec::new();
429        self.found_in(&self.root, Vec2::ZERO, None, rect, pixel, &mut out);
430        out.sort_by(|a, b| a.order.cmp(b.order));
431        out
432    }
433
434    /// The chunks [`found`](Self::found) reaches from `local`, a space whose
435    /// origin is at `at` and which `cut` cuts from outside, added to `out`.
436    fn found_in<'a>(
437        &'a self,
438        local: &'a SpaceIndex,
439        at: Vec2,
440        cut: Option<KRect>,
441        rect: KRect,
442        pixel: f64,
443        out: &mut Vec<Found<'a>>,
444    ) {
445        let inside = rect - at;
446        for e in local.index.locate_in_envelope_intersecting(&aabb(inside)) {
447            if e.bounds.width() < pixel && e.bounds.height() < pixel {
448                continue;
449            }
450            match &e.what {
451                What::Chunk(order) => out.push(Found { order, at, cut }),
452                What::Run(id) => {
453                    let run = self.run(*id);
454                    let outer = run.cut.map(|c| c + at);
455                    let cut = match (cut, outer) {
456                        (Some(a), Some(b)) => Some(a.intersect(b)),
457                        (a, b) => a.or(b),
458                    };
459                    let rect = match outer {
460                        Some(c) => rect.intersect(c),
461                        None => rect,
462                    };
463                    if rect.width() < 0.0 || rect.height() < 0.0 {
464                        continue;
465                    }
466                    for (k, child) in run.touching(rect - at) {
467                        if let Some(space) = run.spaces.get(k) {
468                            self.found_in(space, at + child, cut, rect, pixel, out);
469                        }
470                    }
471                }
472            }
473        }
474    }
475
476    /// The run children that touch `rect` — in the design's coordinates —
477    /// and no longer round as their spaces were made: what is rounded anew
478    /// before `rect` is painted, hit or read. Only what touches `rect` is
479    /// looked at.
480    pub fn unrounded(&self, rect: KRect) -> Vec<(RunId, crate::tree::OrderKey)> {
481        let mut out = Vec::new();
482        self.unrounded_in(&self.root, Vec2::ZERO, rect, &mut out);
483        out
484    }
485
486    /// The run children [`unrounded`](Self::unrounded) finds from `local`, a
487    /// space whose origin is at `at`, added to `out`.
488    fn unrounded_in(
489        &self,
490        local: &SpaceIndex,
491        at: Vec2,
492        rect: KRect,
493        out: &mut Vec<(RunId, crate::tree::OrderKey)>,
494    ) {
495        for e in local
496            .index
497            .locate_in_envelope_intersecting(&aabb(rect - at))
498        {
499            let What::Run(id) = &e.what else { continue };
500            let run = self.run(*id);
501            let rect = match run.cut {
502                Some(c) => rect.intersect(c + at),
503                None => rect,
504            };
505            if rect.width() < 0.0 || rect.height() < 0.0 {
506                continue;
507            }
508            for (k, child, fresh) in run.touching_rounded(rect - at) {
509                if !fresh {
510                    out.push((*id, k.clone()));
511                } else if let Some(space) = run.spaces.get(k) {
512                    self.unrounded_in(space, at + child, rect, out);
513                }
514            }
515        }
516    }
517
518    /// The commands that touch `rect`, in the design's coordinates, in paint
519    /// order — a chunk smaller than `pixel` both ways skipped — each with its
520    /// chunk and where the chunk's origin is in the design's coordinates.
521    pub fn query(&self, rect: KRect, pixel: f64) -> Vec<(Vec2, &Chunk, &Command)> {
522        let mut out = Vec::new();
523        for f in self.found(rect, pixel) {
524            let chunk = &self.chunks[f.order];
525            let origin = f.at + chunk.origin;
526            let local = rect - origin;
527            let mut at: Vec<usize> = chunk
528                .index
529                .locate_in_envelope_intersecting(&aabb(local))
530                .map(|l| l.at)
531                .collect();
532            at.sort_unstable();
533            out.extend(at.into_iter().map(|i| (origin, chunk, &chunk.commands[i])));
534        }
535        out
536    }
537
538    /// Where a space's origin is in the design's coordinates.
539    pub fn space_at(&self, space: &Space) -> Vec2 {
540        match space {
541            Space::Root => Vec2::ZERO,
542            Space::Item(r, k) => {
543                let run = self.run(*r);
544                self.space_at(&run.space) + run.child_at(k).unwrap_or(Vec2::ZERO)
545            }
546        }
547    }
548
549    /// Where `transform`'s origin is in the design's coordinates.
550    pub(super) fn world(&self, mut transform: Id) -> Vec2 {
551        let mut at = Vec2::ZERO;
552        loop {
553            let t = self.trees.transforms.get(transform);
554            at += t.offset;
555            if let Some((r, k)) = &t.item {
556                return at + self.space_at(&Space::Item(*r, k.clone()));
557            }
558            match t.parent {
559                Some(p) => transform = p,
560                None => return at,
561            }
562        }
563    }
564
565    /// Every image the list paints swapped for the blob `last_of` names for
566    /// it, where it names one.
567    pub fn swap_images(&mut self, last_of: &HashMap<u64, peniko::ImageData>) {
568        for chunk in self.chunks.values_mut() {
569            for c in &mut chunk.commands {
570                if let Draw::Fill(_, super::Paint::Image(data, _)) = &mut c.draw
571                    && let Some(old) = last_of.get(&data.data.id())
572                {
573                    *data = old.clone();
574                }
575            }
576        }
577    }
578}
579
580/// `f` as a rectangle.
581pub(super) fn frame_rect(f: Frame) -> KRect {
582    KRect::new(
583        f.x as f64,
584        f.y as f64,
585        (f.x + f.width) as f64,
586        (f.y + f.height) as f64,
587    )
588}
589
590#[cfg(test)]
591mod tests;