1use 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#[derive(Clone, PartialEq, Debug)]
17pub(super) enum What {
18 Chunk(Order),
20 Run(RunId),
22}
23
24#[derive(Clone, PartialEq)]
26pub(super) struct Entry {
27 pub(super) what: What,
29 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
40pub(super) struct Found<'a> {
43 pub(super) order: &'a Order,
45 pub(super) at: Vec2,
47 pub(super) cut: Option<KRect>,
50}
51
52#[derive(Default)]
55pub(super) struct Extent {
56 x0: BTreeMap<i64, usize>,
58 y0: BTreeMap<i64, usize>,
60 x1: BTreeMap<i64, usize>,
62 y1: BTreeMap<i64, usize>,
64}
65
66pub(super) fn key(v: f64) -> i64 {
68 (v * 1e6).round() as i64
69}
70
71impl Extent {
72 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 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 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
116pub struct List {
120 pub trees: Trees,
122 pub(super) chunks: BTreeMap<Order, Chunk>,
124 pub(super) root: SpaceIndex,
126 pub(super) runs: Vec<Option<Run>>,
128 pub(super) free_runs: Vec<RunId>,
130 pub(super) stale: std::collections::BTreeSet<(RunId, crate::tree::OrderKey)>,
132 pub root_transform: Id,
134 pub root_clip: Id,
136 pub area: Frame,
138}
139
140impl Default for List {
141 fn default() -> Self {
142 List::new()
143 }
144}
145
146impl List {
147 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 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 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 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 pub fn covered(&self) -> Option<KRect> {
227 self.root.covers.rect()
228 }
229
230 pub fn chunk(&self, order: &Order) -> Option<&Chunk> {
232 self.chunks.get(order)
233 }
234
235 pub fn chunks(&self) -> impl Iterator<Item = (&Order, &Chunk)> {
237 self.chunks.iter()
238 }
239
240 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 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 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 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 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 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 pub fn run(&self, id: RunId) -> &Run {
323 self.runs[id as usize].as_ref().expect("a live run")
324 }
325
326 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
580pub(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;