Skip to main content

mln_engine/layer/
layer_drawing.rs

1//! What the engine keeps of a layer's tiles between frames: its value of
2//! each tile it draws, a value of the layer's type, in a [`TileMap`], which
3//! also says what the tile's value was made from and what of that bucket's
4//! vertex data changed since, and the tile's previous value, which the next
5//! value the layer makes of the tile may take from. The frame and every
6//! drape the layer draws in draw the same values.
7
8use std::ops::BitOrAssign;
9
10use mln_style::hash::HashMap;
11
12use crate::draw::identity::SimpleIdentity;
13use crate::tile::OverscaledTileID;
14/// What of a bucket's vertex data changed since a tile's draws copied it.
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16pub struct BucketChanges {
17    /// The values of the paint properties that read feature state.
18    pub paint: bool,
19    /// The opacities that placement sets.
20    pub opacity: bool,
21    /// The positions that placement moves, such as of labels along lines or
22    /// at variable anchors.
23    pub dynamic: bool,
24    /// The order of the bucket's triangles.
25    pub sort: bool,
26}
27
28impl BucketChanges {
29    /// Everything changed.
30    pub const ALL: BucketChanges = BucketChanges { paint: true, opacity: true, dynamic: true, sort: true };
31
32    /// Whether anything changed.
33    #[must_use]
34    pub fn any(self) -> bool {
35        self != BucketChanges::default()
36    }
37}
38
39impl BitOrAssign for BucketChanges {
40    fn bitor_assign(&mut self, other: BucketChanges) {
41        self.paint |= other.paint;
42        self.opacity |= other.opacity;
43        self.dynamic |= other.dynamic;
44        self.sort |= other.sort;
45    }
46}
47
48/// The buckets whose vertex data changed, by bucket id, with what changed.
49#[derive(Default)]
50pub struct ChangedBuckets(HashMap<SimpleIdentity, BucketChanges>);
51
52impl ChangedBuckets {
53    /// Records that `changes` of the bucket `bucket` changed.
54    pub fn mark(&mut self, bucket: SimpleIdentity, changes: BucketChanges) {
55        if changes.any() {
56            *self.0.entry(bucket).or_default() |= changes;
57        }
58    }
59
60    #[must_use]
61    pub(crate) fn is_empty(&self) -> bool {
62        self.0.is_empty()
63    }
64
65    /// Whether the bucket `bucket` changed.
66    #[must_use]
67    pub(crate) fn contains(&self, bucket: SimpleIdentity) -> bool {
68        self.0.contains_key(&bucket)
69    }
70
71    fn get(&self, bucket: SimpleIdentity) -> Option<BucketChanges> {
72        self.0.get(&bucket).copied()
73    }
74}
75
76/// What the tile showed a layer that its value was made from: the
77/// identity of its bucket, or of its raster or raster-dem contents, with the
78/// generations of their mask or mesh and of their DEM's border.
79pub(crate) type MadeFrom = (SimpleIdentity, [u64; 2]);
80
81/// What the engine keeps of a tile a layer draws, whatever the layer's type.
82#[derive(Default)]
83struct TileState {
84    /// What the tile's value was made from, `None` until the engine first
85    /// sees the tile show the layer something.
86    made_from: Option<MadeFrom>,
87    /// What of the bucket's vertex data changed since the draws copied it.
88    changes: BucketChanges,
89}
90
91/// The frame's tiles a layer draws, in id order, each with its
92/// [`TileState`]: the part of a [`TileMap`] that doesn't depend on what the
93/// layer keeps of a tile.
94#[derive(Default)]
95struct TileSet {
96    /// The tiles' ids, in order.
97    ids: Vec<OverscaledTileID>,
98    /// Each tile's state, at the tile's index.
99    states: Vec<TileState>,
100    /// How the tiles' indexes last changed.
101    moves: TileMoves,
102    /// The ids that `set_tiles` makes the set's; after it, the ids the set
103    /// had, whose memory the next change reuses.
104    incoming: Vec<OverscaledTileID>,
105    /// The index after the tile that [`find`](Self::find) last found,
106    /// where it looks first.
107    next: usize,
108}
109
110/// How the indexes of a set's tiles change, as swaps of the values at them
111/// that move the values of the tiles that stay to their new indexes.
112#[derive(Default)]
113struct TileMoves {
114    /// The swaps: `swaps[..split]` before the values beyond `kept` drop, and
115    /// the others after the new tiles' values fill the indexes up to `len`.
116    swaps: Vec<(usize, usize)>,
117    split: usize,
118    kept: usize,
119    len: usize,
120}
121
122impl TileMoves {
123    /// Moves `values`, one at each index of the set's tiles before the
124    /// change, to their tiles' indexes after it, drops those of the tiles
125    /// that left, and gives the new tiles `fill()`.
126    fn apply<V>(&self, values: &mut Vec<V>, fill: impl FnMut() -> V) {
127        let (before, after) = self.swaps.split_at(self.split);
128        for &(a, b) in before {
129            values.swap(a, b);
130        }
131        values.truncate(self.kept);
132        values.resize_with(self.len, fill);
133        for &(a, b) in after {
134            values.swap(a, b);
135        }
136    }
137}
138
139impl TileSet {
140    /// Makes `incoming` the set's tiles: keeps the states of those it has,
141    /// and drops the others. Returns whether that changed any tile's index,
142    /// which `moves` then says.
143    fn set_tiles(&mut self) -> bool {
144        // The stable sort, which the renderer's other sorts of tile ids
145        // share, allocates nothing for a frame's tens of tiles.
146        self.incoming.sort();
147        self.incoming.dedup();
148        if self.ids == self.incoming {
149            return false;
150        }
151        let (ids, incoming, moves) = (&self.ids, &self.incoming, &mut self.moves);
152        moves.swaps.clear();
153        // The tiles that stay move to the front, in order, ahead of those
154        // that leave...
155        let mut kept = 0;
156        for (old, _) in kept_tiles(ids, incoming) {
157            if kept != old {
158                moves.swaps.push((kept, old));
159            }
160            kept += 1;
161        }
162        moves.split = moves.swaps.len();
163        moves.kept = kept;
164        moves.len = incoming.len();
165        // ...and then, from the last to the first, to their new indexes,
166        // whose values are the new tiles' until then.
167        for (rank, (_, new)) in kept_tiles(ids, incoming).enumerate() {
168            if rank != new {
169                moves.swaps.push((new, rank));
170            }
171        }
172        moves.swaps[moves.split..].reverse();
173        moves.apply(&mut self.states, TileState::default);
174        std::mem::swap(&mut self.ids, &mut self.incoming);
175        true
176    }
177
178    /// Moves the tiles' states to the tiles `wrap_delta` world copies east
179    /// of theirs. Returns whether that changed their order, which `moves`
180    /// then says; only a wrap that overflows does.
181    fn shift_wraps(&mut self, wrap_delta: i16) -> bool {
182        for id in &mut self.ids {
183            *id = id.unwrap_to(id.wrap.wrapping_add(wrap_delta));
184        }
185        if self.ids.is_sorted() {
186            return false;
187        }
188        // The shifted ids, in their old order.
189        self.incoming.clone_from(&self.ids);
190        self.ids.sort();
191        // For each tile's old index, its new one. A wrap overflows rarely
192        // enough that this allocates.
193        let mut new_index: Vec<usize> =
194            self.incoming.iter().map(|id| self.ids.binary_search(id).unwrap_or_default()).collect();
195        let moves = &mut self.moves;
196        moves.swaps.clear();
197        for old in 0..new_index.len() {
198            while new_index[old] != old {
199                let new = new_index[old];
200                moves.swaps.push((old, new));
201                new_index.swap(old, new);
202            }
203        }
204        moves.split = moves.swaps.len();
205        moves.kept = self.ids.len();
206        moves.len = self.ids.len();
207        moves.apply(&mut self.states, TileState::default);
208        true
209    }
210
211    /// The index of `tile_id`, if it is one of the set's.
212    fn index_of(&self, tile_id: &OverscaledTileID) -> Option<usize> {
213        self.ids.binary_search(tile_id).ok()
214    }
215
216    /// [`index_of`](Self::index_of), looking first at the index after the
217    /// tile it last found: the engine readies a layer's tile values and the
218    /// layer then makes its draws of them in the same order, the tiles' id
219    /// order for most layer types.
220    fn find(&mut self, tile_id: &OverscaledTileID) -> Option<usize> {
221        let index = match self.ids.get(self.next) {
222            Some(id) if id == tile_id => self.next,
223            _ => self.index_of(tile_id)?,
224        };
225        self.next = index + 1;
226        Some(index)
227    }
228
229    fn clear(&mut self) {
230        self.ids.clear();
231        self.states.clear();
232    }
233
234    fn mark_changed(&mut self, changed: &ChangedBuckets) {
235        for state in &mut self.states {
236            if let Some(changes) = state.made_from.and_then(|(bucket, _)| changed.get(bucket)) {
237                state.changes |= changes;
238            }
239        }
240    }
241}
242
243/// The tiles of both `old` and `new`, sorted ids, each with its index in
244/// `old` and in `new`, in order.
245fn kept_tiles<'a>(
246    old: &'a [OverscaledTileID],
247    new: &'a [OverscaledTileID],
248) -> impl Iterator<Item = (usize, usize)> + 'a {
249    let mut old_index = 0;
250    new.iter().enumerate().filter_map(move |(new_index, id)| {
251        while old.get(old_index).is_some_and(|old_id| old_id < id) {
252            old_index += 1;
253        }
254        (old.get(old_index) == Some(id)).then_some((old_index, new_index))
255    })
256}
257
258/// A layer's values of the frame's tiles, which the engine keeps, by tile id:
259/// what each tile's value was made from and what of its bucket changed
260/// since, and the value, a `T` of the layer's type, from when the layer
261/// makes one ([`TypedLayer::tile`]). A value that the map retires, rather
262/// than drops, stays as the tile's previous value until the layer makes the
263/// tile's next one, which takes it, or the tile leaves.
264///
265/// [`TypedLayer::tile`]: crate::layer::render_layer::TypedLayer::tile
266pub struct TileMap<T> {
267    set: TileSet,
268    /// Each tile's values, at the tile's index in the set.
269    values: Vec<Slot<T>>,
270}
271
272/// A tile's value in a [`TileMap`], and its previous one.
273struct Slot<T> {
274    value: Option<T>,
275    previous: Option<T>,
276}
277
278impl<T> Default for Slot<T> {
279    fn default() -> Self {
280        Slot { value: None, previous: None }
281    }
282}
283
284impl<T> Slot<T> {
285    /// Makes the value, if there is one, the previous one.
286    fn retire(&mut self) {
287        if let Some(value) = self.value.take() {
288            self.previous = Some(value);
289        }
290    }
291}
292
293impl<T> Default for TileMap<T> {
294    fn default() -> Self {
295        TileMap { set: TileSet::default(), values: Vec::new() }
296    }
297}
298
299impl<T> TileMap<T> {
300    /// Makes `tiles`, the frame's tiles of the layer in any order, those the
301    /// map has entries for: it keeps the entries of those it had, and drops
302    /// the others.
303    pub(crate) fn set_tiles(&mut self, tiles: impl IntoIterator<Item = OverscaledTileID>) {
304        self.set.incoming.clear();
305        self.set.incoming.extend(tiles);
306        if self.set.set_tiles() {
307            self.set.moves.apply(&mut self.values, Slot::default);
308        }
309    }
310
311    /// Whether the map has no tiles.
312    #[must_use]
313    pub(crate) fn is_empty(&self) -> bool {
314        self.set.ids.is_empty()
315    }
316
317    /// Drops the entries of the tiles.
318    pub(crate) fn clear_tiles(&mut self) {
319        self.set.clear();
320        self.values.clear();
321    }
322
323    /// Moves the tiles' entries to the tiles `wrap_delta` world copies east
324    /// of theirs.
325    pub(crate) fn shift_wraps(&mut self, wrap_delta: i16) {
326        if self.set.shift_wraps(wrap_delta) {
327            self.set.moves.apply(&mut self.values, Slot::default);
328        }
329    }
330
331    /// Adds `changed` to the changes of the tiles whose values were made from
332    /// a bucket in it.
333    pub(crate) fn mark_changed(&mut self, changed: &ChangedBuckets) {
334        self.set.mark_changed(changed);
335    }
336
337    /// Drops the tiles' values and their previous ones. The tiles' entries
338    /// stay.
339    pub fn clear(&mut self) {
340        self.values.fill_with(Slot::default);
341    }
342
343    /// Makes the tiles' values their previous ones. The tiles' entries stay.
344    pub(crate) fn retire(&mut self) {
345        self.values.iter_mut().for_each(Slot::retire);
346    }
347
348    /// Whether `tile_id` is one of the frame's tiles of the layer.
349    #[cfg(test)]
350    #[must_use]
351    pub(crate) fn has_tile(&self, tile_id: &OverscaledTileID) -> bool {
352        self.set.index_of(tile_id).is_some()
353    }
354
355    /// What the layer keeps of `tile_id`, if the tile is one of the frame's
356    /// and the layer keeps anything of it.
357    #[cfg(test)]
358    #[must_use]
359    pub(crate) fn get(&self, tile_id: &OverscaledTileID) -> Option<&T> {
360        self.values.get(self.set.index_of(tile_id)?)?.value.as_ref()
361    }
362
363    /// What the layer keeps of `tile_id`, if the tile is one of the frame's
364    /// and the layer keeps anything of it.
365    pub fn get_mut(&mut self, tile_id: &OverscaledTileID) -> Option<&mut T> {
366        self.values.get_mut(self.set.find(tile_id)?)?.value.as_mut()
367    }
368
369    /// Drops what the layer keeps of `tile_id`, its previous value too.
370    pub fn drop_value(&mut self, tile_id: &OverscaledTileID) {
371        if let Some(slot) = self.set.find(tile_id).and_then(|index| self.values.get_mut(index)) {
372            *slot = Slot::default();
373        }
374    }
375
376    /// The tiles, in order, each with its entry.
377    pub(crate) fn entries(&mut self) -> impl Iterator<Item = (OverscaledTileID, TileEntry<'_, T>)> {
378        let TileSet { ids, states, .. } = &mut self.set;
379        ids.iter().zip(states).zip(&mut self.values).map(|((&id, state), slot)| (id, TileEntry::new(state, slot)))
380    }
381
382    /// The entry of `tile_id`, if the tile is one of the frame's.
383    pub fn entry(&mut self, tile_id: &OverscaledTileID) -> Option<TileEntry<'_, T>> {
384        let index = self.set.find(tile_id)?;
385        Some(TileEntry::new(self.set.states.get_mut(index)?, self.values.get_mut(index)?))
386    }
387}
388
389/// The entry of a tile in a [`TileMap`].
390pub struct TileEntry<'a, T> {
391    state: &'a mut TileState,
392    /// What the layer keeps of the tile, if anything.
393    pub value: &'a mut Option<T>,
394    /// The tile's previous value, which the map retired.
395    previous: &'a mut Option<T>,
396}
397
398impl<'a, T> TileEntry<'a, T> {
399    fn new(state: &'a mut TileState, Slot { value, previous }: &'a mut Slot<T>) -> Self {
400        TileEntry { state, value, previous }
401    }
402
403    /// Makes the tile's value, if it has one, its previous one.
404    pub(crate) fn retire(&mut self) {
405        if let Some(value) = self.value.take() {
406            *self.previous = Some(value);
407        }
408    }
409
410    /// Takes the tile's previous value, for the layer's next value of the
411    /// tile.
412    pub(crate) fn take_previous(&mut self) -> Option<T> {
413        self.previous.take()
414    }
415
416    /// What the tile's value was made from, if the engine saw it show the
417    /// layer something.
418    #[cfg(test)]
419    #[must_use]
420    pub(crate) fn made_from(&self) -> Option<MadeFrom> {
421        self.state.made_from
422    }
423
424    /// Records what the tile shows the layer: `made_from`, or `None` for
425    /// nothing. The tile's value drops for nothing, with its previous one,
426    /// and retires where it was made from something else, which drops the
427    /// changes of what it was made from too.
428    pub(crate) fn show(&mut self, made_from: Option<MadeFrom>) {
429        match made_from {
430            None => {
431                *self.value = None;
432                *self.previous = None;
433            }
434            Some(made_from) if self.state.made_from != Some(made_from) => {
435                if self.state.made_from.is_some() {
436                    self.retire();
437                }
438                self.state.made_from = Some(made_from);
439                self.state.changes = BucketChanges::default();
440            }
441            Some(_) => {}
442        }
443    }
444
445    /// What of the tile's bucket changed since its value last copied it,
446    /// which the layer is about to copy again.
447    pub fn take_changes(&mut self) -> BucketChanges {
448        std::mem::take(&mut self.state.changes)
449    }
450}
451
452#[cfg(test)]
453mod tests {
454    use super::{BucketChanges, ChangedBuckets, TileMap};
455    use crate::draw::identity::SimpleIdentity;
456    use crate::tile::OverscaledTileID;
457
458    /// Sets what `tiles` keeps of `tile_id` to `value`, if the tile is one
459    /// of the map's; returns whether it is.
460    fn set<T>(tiles: &mut TileMap<T>, tile_id: &OverscaledTileID, value: T) -> bool {
461        tiles.entry(tile_id).map(|entry| *entry.value = Some(value)).is_some()
462    }
463
464    /// The bucket that the value of `tile_id` in `tiles` was made from.
465    fn bucket_of<T>(tiles: &mut TileMap<T>, tile_id: &OverscaledTileID) -> Option<SimpleIdentity> {
466        Some(tiles.entry(tile_id)?.made_from()?.0)
467    }
468
469    /// Records that `tile_id` shows `bucket` in `tiles`; returns whether the
470    /// tile is one of the map's.
471    fn show<T>(tiles: &mut TileMap<T>, tile_id: &OverscaledTileID, bucket: SimpleIdentity) -> bool {
472        tiles.entry(tile_id).map(|mut entry| entry.show(Some((bucket, [0, 0])))).is_some()
473    }
474
475    /// A tile's changes are those of the bucket its draws were built from,
476    /// until the draws take them; a tile that leaves the frame
477    /// takes its entry with it.
478    #[test]
479    fn changes_follow_the_tiles_bucket() {
480        let (tile, other) = (OverscaledTileID::with_zxy(1, 0, 1, 1, 0), OverscaledTileID::with_zxy(1, 0, 1, 0, 0));
481        let (bucket, other_bucket) = (SimpleIdentity::new(), SimpleIdentity::new());
482        let mut tiles = TileMap::<()>::default();
483        tiles.set_tiles([tile, other]);
484        assert!(show(&mut tiles, &tile, bucket));
485        assert!(show(&mut tiles, &tile, bucket));
486        assert!(show(&mut tiles, &other, other_bucket));
487
488        let mut changed = ChangedBuckets::default();
489        changed.mark(bucket, BucketChanges { paint: true, ..BucketChanges::default() });
490        changed.mark(bucket, BucketChanges { sort: true, ..BucketChanges::default() });
491        tiles.mark_changed(&changed);
492
493        let mut take = |tile_id| tiles.entry(tile_id).map(|mut entry| entry.take_changes());
494        assert_eq!(Some(BucketChanges { paint: true, sort: true, ..BucketChanges::default() }), take(&tile));
495        assert_eq!(Some(BucketChanges::default()), take(&tile));
496        assert_eq!(Some(BucketChanges::default()), take(&other));
497
498        tiles.set_tiles([other]);
499        assert!(!tiles.has_tile(&tile));
500        assert_eq!(Some(other_bucket), bucket_of(&mut tiles, &other));
501        tiles.shift_wraps(1);
502        assert_eq!(Some(other_bucket), bucket_of(&mut tiles, &other.unwrap_to(1)));
503    }
504
505    /// A tile that shows another bucket, or bucket of another generation,
506    /// retires its value and drops the changes of the bucket before; one
507    /// that shows nothing drops its value and its previous one.
508    #[test]
509    fn another_bucket_retires_the_value() {
510        let tile = OverscaledTileID::with_zxy(1, 0, 1, 1, 0);
511        let (bucket, other_bucket) = (SimpleIdentity::new(), SimpleIdentity::new());
512        let mut tiles = TileMap::<u32>::default();
513        tiles.set_tiles([tile]);
514        assert!(set(&mut tiles, &tile, 1));
515        assert!(show(&mut tiles, &tile, bucket));
516        assert_eq!(Some(&1), tiles.get(&tile));
517        let mut changed = ChangedBuckets::default();
518        changed.mark(bucket, BucketChanges { paint: true, ..BucketChanges::default() });
519        tiles.mark_changed(&changed);
520        assert!(show(&mut tiles, &tile, other_bucket));
521        assert!(tiles.get(&tile).is_none());
522        assert_eq!(Some(BucketChanges::default()), tiles.entry(&tile).map(|mut entry| entry.take_changes()));
523        assert_eq!(Some(1), tiles.entry(&tile).unwrap().take_previous());
524        assert_eq!(None, tiles.entry(&tile).unwrap().take_previous());
525
526        assert!(set(&mut tiles, &tile, 2));
527        tiles.entry(&tile).unwrap().show(Some((other_bucket, [1, 0])));
528        assert!(tiles.get(&tile).is_none());
529        assert!(set(&mut tiles, &tile, 3));
530        tiles.entry(&tile).unwrap().show(None);
531        assert!(tiles.get(&tile).is_none());
532        assert_eq!(None, tiles.entry(&tile).unwrap().take_previous());
533
534        assert!(set(&mut tiles, &tile, 4));
535        tiles.retire();
536        assert!(tiles.get(&tile).is_none());
537        assert_eq!(Some(4), tiles.entry(&tile).unwrap().take_previous());
538    }
539
540    /// Each tile keeps its value and bucket as tiles before and after it
541    /// come and go, and in whatever order the frame gives the tiles.
542    #[test]
543    fn values_stay_with_their_tiles() {
544        let ids: Vec<OverscaledTileID> = (0..6).map(|x| OverscaledTileID::with_zxy(3, 0, 3, x, 2)).collect();
545        let mut tiles = TileMap::<u32>::default();
546        tiles.set_tiles([ids[4], ids[1], ids[2]]);
547        for &i in &[1, 2, 4] {
548            assert!(set(&mut tiles, &ids[i], i as u32));
549        }
550        let bucket = SimpleIdentity::new();
551        assert!(show(&mut tiles, &ids[2], bucket));
552        tiles.set_tiles([ids[5], ids[2], ids[0], ids[4], ids[3]]);
553        let values: Vec<Option<u32>> = ids.iter().map(|id| tiles.get(id).copied()).collect();
554        assert_eq!(vec![None, None, Some(2), None, Some(4), None], values);
555        assert_eq!(Some(bucket), bucket_of(&mut tiles, &ids[2]));
556        assert!(set(&mut tiles, &ids[0], 0));
557        tiles.set_tiles([ids[4], ids[0], ids[4]]);
558        let values: Vec<Option<u32>> = ids.iter().map(|id| tiles.get(id).copied()).collect();
559        assert_eq!(vec![Some(0), None, None, None, Some(4), None], values);
560        assert!(!tiles.has_tile(&ids[2]));
561    }
562
563    /// Each tile keeps its value and bucket from any set of tiles to any
564    /// other.
565    #[test]
566    fn values_stay_through_every_change() {
567        let ids: Vec<OverscaledTileID> = (0..5).map(|x| OverscaledTileID::with_zxy(3, 0, 3, x, 2)).collect();
568        let buckets: Vec<SimpleIdentity> = ids.iter().map(|_| SimpleIdentity::new()).collect();
569        let subsets = |mask: u32| ids.iter().enumerate().filter(move |(i, _)| mask & (1 << i) != 0).map(|(_, id)| *id);
570        let mut tiles = TileMap::<usize>::default();
571        for from in 0..32 {
572            for to in 0..32 {
573                tiles.clear_tiles();
574                tiles.set_tiles(subsets(from));
575                for (i, id) in ids.iter().enumerate() {
576                    show(&mut tiles, id, buckets[i]);
577                    set(&mut tiles, id, i);
578                }
579                tiles.set_tiles(subsets(to).rev());
580                let values: Vec<Option<usize>> = ids.iter().map(|id| tiles.get(id).copied()).collect();
581                let expected: Vec<Option<usize>> =
582                    (0..ids.len()).map(|i| (from & to & (1 << i) != 0).then_some(i)).collect();
583                assert_eq!(expected, values, "from {from:05b} to {to:05b}");
584                let kept_buckets: Vec<Option<SimpleIdentity>> =
585                    ids.iter().map(|id| bucket_of(&mut tiles, id)).collect();
586                let expected: Vec<Option<SimpleIdentity>> =
587                    (0..ids.len()).map(|i| (from & to & (1 << i) != 0).then_some(buckets[i])).collect();
588                assert_eq!(expected, kept_buckets, "from {from:05b} to {to:05b}");
589            }
590        }
591    }
592
593    /// What the layer keeps of a tile moves with the tile across a wrap jump,
594    /// even one that changes the tiles' order, and as other tiles come and
595    /// go, and goes when the tile leaves the frame or the map is cleared.
596    #[test]
597    fn caches_follow_their_tiles() {
598        let (tile, other) = (OverscaledTileID::with_zxy(1, 0, 1, 1, 0), OverscaledTileID::with_zxy(1, 0, 1, 0, 0));
599        let mut tiles = TileMap::<u32>::default();
600        tiles.set_tiles([tile, other]);
601        assert!(set(&mut tiles, &tile, 1));
602        assert!(set(&mut tiles, &other, 2));
603        assert!(!set(&mut tiles, &OverscaledTileID::with_zxy(1, 0, 1, 1, 1), 3));
604
605        tiles.shift_wraps(1);
606        let moved = tile.unwrap_to(1);
607        assert_eq!(Some(&mut 1), tiles.get_mut(&moved));
608        tiles.set_tiles([moved]);
609        assert!(tiles.get_mut(&other.unwrap_to(1)).is_none());
610        tiles.set_tiles([other, moved]);
611        assert!(tiles.get_mut(&other).is_none());
612        assert_eq!(Some(&1), tiles.get(&moved));
613        tiles.set_tiles([moved]);
614        assert_eq!(Some(&1), tiles.get(&moved));
615
616        let (high, low) = (tile.unwrap_to(i16::MAX), other.unwrap_to(i16::MAX - 1));
617        tiles.set_tiles([high, low, tile]);
618        assert!(set(&mut tiles, &high, 3));
619        assert!(set(&mut tiles, &low, 4));
620        assert!(set(&mut tiles, &tile, 5));
621        tiles.shift_wraps(1);
622        assert_eq!(Some(&3), tiles.get(&tile.unwrap_to(i16::MIN)));
623        assert_eq!(Some(&4), tiles.get(&other.unwrap_to(i16::MAX)));
624        assert_eq!(Some(&5), tiles.get(&tile.unwrap_to(1)));
625
626        tiles.clear();
627        assert!(tiles.has_tile(&other.unwrap_to(i16::MAX)));
628        assert!(tiles.get(&other.unwrap_to(i16::MAX)).is_none());
629    }
630}