Skip to main content

blit/
node.rs

1//! stored nodes of the tree and the side tables they index
2
3use crate::*;
4
5/// identifies a node only during the current render
6///
7/// do not store this across renders
8#[repr(transparent)]
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
10pub struct NodeId(u32);
11
12impl NodeId {
13    #[inline]
14    pub(crate) fn new(index: usize) -> Self {
15        assert!(index < Slots::KEPT as usize, "too many frame nodes");
16        Self(index as u32)
17    }
18
19    #[inline]
20    pub(crate) fn index(self) -> usize {
21        self.0 as usize
22    }
23}
24
25#[derive(Clone, Copy)]
26pub enum FocusRequest {
27    Keep,
28    Clear,
29    Focus(Id),
30}
31
32// keep this under 64 bytes to fit in a cache line
33pub struct StoredNode {
34    pub id: Id,
35    pub parent: NodeId,
36    pub subtree_end: u32,
37    pub first_measure: StoredMeasureId,
38    pub last_paint: StoredPaintId,
39    pub layout: BumpId,
40    pub layout_kind: u16,
41    pub aux: AuxId,
42    pub place: PlaceId,
43    pub place_scope: NodeId,
44    pub item: BumpId,
45    pub target: NodeId,
46    pub interactive: bool,
47}
48
49// settings most nodes leave unset, kept apart so nodes stay small
50#[derive(Clone, Copy)]
51pub struct Aux<T> {
52    pub visual_parent: NodeId,
53    pub clip: Option<Corners<T>>,
54    pub limits: Constraints<T>,
55    pub padding: Sides<T>,
56    pub hit: Sides<T>,
57    pub motion: NodeMotionId,
58}
59
60// the parent a node stacks, clips and contains its size within
61pub fn visual_parent<T>(aux: &[Aux<T>], stored: &StoredNode) -> NodeId {
62    stored
63        .aux
64        .index()
65        .map_or(stored.parent, |index| aux[index].visual_parent)
66}
67
68#[derive(Clone, Copy)]
69pub struct NodeMotion {
70    pub node: NodeId,
71    pub motion: Motion,
72}
73
74#[derive(Clone, Copy)]
75pub struct ResolvedClip<T> {
76    pub parent: ResolvedClipId,
77    pub depth: u32,
78    pub area: Rect<T>,
79    pub radius: Corners<T>,
80    pub bounds: Rect<T>,
81}
82
83pub struct StoredMeasure<C: Context> {
84    pub run: fn(&BumpArena, BumpId, &mut C, Constraints<C::Scalar>) -> Fit<Size<C::Scalar>>,
85    pub bump_id: BumpId,
86    pub next: StoredMeasureId,
87}
88
89impl<C: Context> Clone for StoredMeasure<C> {
90    fn clone(&self) -> Self {
91        *self
92    }
93}
94
95impl<C: Context> Copy for StoredMeasure<C> {}
96
97pub struct StoredPaint<C: Context> {
98    pub run: fn(&BumpArena, BumpId, &mut C, Rect<C::Scalar>),
99    pub bump_id: BumpId,
100    pub next: StoredPaintId,
101}
102
103impl<C: Context> Clone for StoredPaint<C> {
104    fn clone(&self) -> Self {
105        *self
106    }
107}
108
109impl<C: Context> Copy for StoredPaint<C> {}
110
111pub struct StoredPlace<C: Context> {
112    pub bump_id: BumpId,
113    pub run: for<'a> fn(&mut PlaceCx<'a, C>, BumpId, Rect<C::Scalar>) -> Point<C::Scalar>,
114}
115
116impl<C: Context> Clone for StoredPlace<C> {
117    fn clone(&self) -> Self {
118        *self
119    }
120}
121
122impl<C: Context> Copy for StoredPlace<C> {}
123
124#[derive(Clone, Copy)]
125pub struct Index<T>(pub u32, PhantomData<fn() -> T>);
126
127impl<T> Index<T> {
128    pub const NONE: Self = Self(u32::MAX, PhantomData);
129
130    pub fn new(index: usize) -> Self {
131        Self(u32::try_from(index).expect("too many frame values"), PhantomData)
132    }
133
134    pub fn index(&self) -> Option<usize> {
135        (self.0 != u32::MAX).then_some(self.0 as usize)
136    }
137}
138
139pub type StoredMeasureId = Index<StoredMeasure<()>>;
140pub type StoredPaintId = Index<StoredPaint<()>>;
141pub type AuxId = Index<Aux<()>>;
142pub type PlaceId = Index<StoredPlace<()>>;
143pub type NodeMotionId = Index<NodeMotion>;
144pub type ResolvedClipId = Index<ResolvedClip<()>>;
145
146pub struct LayoutKind<C: Context> {
147    pub type_id: TypeId,
148    pub fit: for<'a> fn(&mut LayoutCx<'a, C>, BumpId, Axis) -> Fit<C::Scalar>,
149    pub distribute: for<'a> fn(&mut LayoutCx<'a, C>, BumpId, Axis, C::Scalar),
150    pub default_item: BumpId,
151}
152
153/// ids of the nodes in the current and previous build
154///
155/// a node inherits the id of the node it matches in the previous build, or takes a dead slot.
156/// a slot lives while the current or previous build used it, by building its node or by naming
157/// it before or without building it. once a whole build leaves it unused it is dead, and taking
158/// it again moves its generation on so ids kept elsewhere stop resolving.
159///
160/// slots remember the build that last used them, so a build clears and sweeps nothing
161#[derive(Default)]
162pub struct Slots {
163    slots: Vec<Slot>,
164    names: Names,
165    build: u32,
166    // where the search for a dead slot resumes in this build
167    sweep: u32,
168}
169
170#[derive(Clone, Copy)]
171struct Slot {
172    generation: NonZeroU32,
173    // the last build that used it
174    build: u32,
175    // its node in that build or KEPT
176    node: u32,
177    // its node in the build before or KEPT / NONE
178    old: u32,
179}
180
181impl Slots {
182    /// no node, as for a slot without one or a node new to this build
183    pub const NONE: u32 = u32::MAX;
184    // slot kept through the build without a node
185    const KEPT: u32 = u32::MAX - 1;
186
187    /// starts a build, so the current nodes become the previous build's
188    pub fn begin(&mut self) {
189        self.build = self.build.wrapping_add(1);
190        self.sweep = 0;
191        if self.slots.is_empty() {
192            self.alloc();
193        }
194    }
195
196    /// whether another node of this build already holds `id`
197    #[inline]
198    pub fn claimed(&self, id: Id) -> bool {
199        let slot = &self.slots[id.slot as usize];
200        slot.build == self.build && slot.node < Self::KEPT
201    }
202
203    /// assigns `id` to `node`
204    #[inline]
205    pub fn set(&mut self, id: Id, node: NodeId) {
206        self.touch(id.slot as usize).node = node.0;
207    }
208
209    /// keeps `id` through this build without a node
210    #[inline]
211    pub fn keep(&mut self, id: Id) {
212        if self.live(id) {
213            self.touch(id.slot as usize);
214        }
215    }
216
217    /// whether `id` is live and already used in this build
218    #[inline]
219    pub fn is_kept(&self, id: Id) -> bool {
220        self.live(id) && self.slots[id.slot as usize].build == self.build
221    }
222
223    pub fn alloc(&mut self) -> Id {
224        let build = self.build;
225        // slots before the sweep stay live through this build, as only a new build kills them
226        let mut index = self.sweep as usize;
227        while self
228            .slots
229            .get(index)
230            .is_some_and(|slot| build.wrapping_sub(slot.build) <= 1)
231        {
232            index += 1;
233        }
234        self.sweep = u32::try_from(index + 1).expect("too many ids");
235        let generation = self.slots.get(index).map_or(NonZeroU32::MIN, |slot| {
236            slot.generation.checked_add(1).unwrap_or(NonZeroU32::MIN)
237        });
238        let slot = Slot {
239            generation,
240            build,
241            node: Self::KEPT,
242            old: Self::NONE,
243        };
244        if index == self.slots.len() {
245            self.slots.push(slot);
246        } else {
247            self.slots[index] = slot;
248        }
249        Id {
250            slot: index as u32,
251            generation,
252        }
253    }
254
255    /// the node holding `id` in the current build
256    #[inline]
257    pub fn node(&self, id: Id) -> Option<NodeId> {
258        let slot = self.slots.get(id.slot as usize)?;
259        (slot.generation == id.generation && slot.build == self.build && slot.node < Self::KEPT)
260            .then_some(NodeId(slot.node))
261    }
262
263    /// the node holding `id` in the previous build
264    #[inline]
265    pub fn old(&self, id: Id) -> Option<usize> {
266        let slot = self.slots.get(id.slot as usize).filter(|_| self.live(id))?;
267        // a slot this build has not used yet still holds its node from the previous one
268        let old = if slot.build == self.build { slot.old } else { slot.node };
269        (old < Self::KEPT).then_some(old as usize)
270    }
271
272    /// the id keyed `key` in `scope`, taking a slot when nothing holds the name yet
273    pub fn name(&mut self, scope: Id, key: u64) -> Id {
274        let mut bucket = 0;
275        if !self.names.table.is_empty() {
276            bucket = self.names.probe(scope, key);
277            let index = self.names.table[bucket];
278            if index != Names::EMPTY {
279                let id = self.names.entries[index as usize].id;
280                if self.live(id) {
281                    return id;
282                }
283                // a dead entry for the name takes the new id
284                let id = self.alloc();
285                self.names.entries[index as usize].id = id;
286                return id;
287            }
288        }
289        let id = self.alloc();
290        if self.names.entries.len() + 1 > self.names.table.len() / 2 {
291            // dead names go once the table fills, so it grows only for live ones
292            let mut entries = core::mem::take(&mut self.names.entries);
293            entries.retain(|name| self.live(name.id));
294            entries.push(Name { scope, key, id });
295            self.names.entries = entries;
296            self.names.rebuild();
297        } else {
298            let index = u32::try_from(self.names.entries.len()).expect("too many names");
299            self.names.entries.push(Name { scope, key, id });
300            self.names.table[bucket] = index;
301        }
302        id
303    }
304
305    /// the id keyed `key` in `scope`, if anything holds the name
306    pub fn find(&self, scope: Id, key: u64) -> Option<Id> {
307        // entries of dead slots stay until the table fills
308        let index = (!self.names.table.is_empty()).then(|| self.names.table[self.names.probe(scope, key)])?;
309        let id = self.names.entries.get(index as usize)?.id;
310        self.live(id).then_some(id)
311    }
312
313    #[inline]
314    fn live(&self, id: Id) -> bool {
315        self.slots
316            .get(id.slot as usize)
317            .is_some_and(|slot| slot.generation == id.generation && self.build.wrapping_sub(slot.build) <= 1)
318    }
319
320    // marks a live slot used in this build, so its node so far is the previous build's
321    #[inline]
322    fn touch(&mut self, index: usize) -> &mut Slot {
323        let build = self.build;
324        let slot = &mut self.slots[index];
325        if slot.build != build {
326            slot.old = slot.node;
327            slot.node = Self::KEPT;
328            slot.build = build;
329        }
330        slot
331    }
332}
333
334/// a node's place in the previous build and its child there to try first
335#[derive(Clone, Copy)]
336pub struct Cursor {
337    pub old: u32,
338    pub next: u32,
339}
340
341/// children built from one call site under an open node
342#[derive(Clone, Copy)]
343pub struct Site {
344    pub location: &'static Location<'static>,
345    /// the ordinal of its latest child
346    pub ordinal: u32,
347    /// whether its next child may still be among the previous children
348    ///
349    /// a site numbers its children from zero without gaps in every build, so once one of them
350    /// matches nothing the later ones cannot match either, and skipping their search keeps a
351    /// site that replaces another linear
352    pub scan: bool,
353}
354
355/// how a node is told apart from its siblings
356#[derive(Clone, Copy)]
357pub enum Mark {
358    /// built from a call site, repeats told apart by their order
359    Site(&'static Location<'static>, u32),
360    /// keyed in a scope already used in this build
361    Key(u32, u64),
362    /// repeating a key or keyed in an unused scope, found by name alone
363    Named,
364}
365
366impl Mark {
367    #[inline]
368    pub fn is_site(self, location: &Location<'_>, ordinal: u32) -> bool {
369        matches!(self, Self::Site(other, other_ordinal) if other_ordinal == ordinal && same_place(other, location))
370    }
371}
372
373/// whether two locations are one call site, as copies of one may not share an address
374#[inline]
375pub fn same_place(site: &Location<'_>, other: &Location<'_>) -> bool {
376    // out of line so other sites are told apart by line and column without a call
377    #[cold]
378    fn same_file(site: &Location<'_>, other: &Location<'_>) -> bool {
379        site.file() == other.file()
380    }
381    core::ptr::eq(site, other)
382        || (site.line() == other.line() && site.column() == other.column() && same_file(site, other))
383}
384
385/// ids of keyed nodes by scope and key, open addressed
386///
387/// buckets come from mixing the scope and key, entries compare exactly
388#[derive(Default)]
389struct Names {
390    entries: Vec<Name>,
391    // entry indices, at most half full
392    table: Vec<u32>,
393}
394
395// a key in a scope and the id it names
396#[derive(Clone, Copy)]
397struct Name {
398    scope: Id,
399    key: u64,
400    id: Id,
401}
402
403impl Names {
404    const EMPTY: u32 = u32::MAX;
405
406    fn rebuild(&mut self) {
407        self.table.clear();
408        if self.entries.is_empty() {
409            return;
410        }
411        self.table
412            // a quarter full so as many names again fit before the next compaction
413            .resize((self.entries.len() * 4).next_power_of_two(), Self::EMPTY);
414        for index in 0..self.entries.len() {
415            let Name { scope, key, .. } = self.entries[index];
416            let bucket = self.probe(scope, key);
417            self.table[bucket] = index as u32;
418        }
419    }
420
421    // the bucket holding the name, or the empty one where it would go
422    fn probe(&self, scope: Id, key: u64) -> usize {
423        let mask = self.table.len() - 1;
424        let mixed = (key ^ u64::from(scope.slot).rotate_left(32)).wrapping_mul(0x9e37_79b9_7f4a_7c15);
425        let mut bucket = (mixed >> (64 - self.table.len().trailing_zeros())) as usize;
426        loop {
427            let index = self.table[bucket];
428            if index == Self::EMPTY {
429                return bucket;
430            }
431            let name = self.entries[index as usize];
432            if name.scope == scope && name.key == key {
433                return bucket;
434            }
435            bucket = (bucket + 1) & mask;
436        }
437    }
438}
439
440/// a scope made at a call site on a node
441#[derive(Clone, Copy)]
442pub struct CallScope {
443    pub call: Call,
444    pub id: Id,
445}
446
447/// a call site on a node, the key of its animations and timers
448#[derive(Clone, Copy, PartialEq, Eq)]
449pub struct Call {
450    pub owner: Id,
451    // compared by content as copies of one call site may not share an address
452    pub location: &'static Location<'static>,
453    // calls from one site repeat within a frame, so their order tells them apart
454    pub repeat: u32,
455}
456
457impl Call {
458    pub fn new(owner: Id, location: &'static Location<'static>) -> Self {
459        Self {
460            owner,
461            location,
462            repeat: 0,
463        }
464    }
465}
466
467impl Ord for Call {
468    #[inline]
469    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
470        let (location, other_location) = (self.location, other.location);
471        // the file last and only between copies of a call site, as it compares as a string
472        self.owner
473            .cmp(&other.owner)
474            .then_with(|| location.line().cmp(&other_location.line()))
475            .then_with(|| location.column().cmp(&other_location.column()))
476            .then_with(|| self.repeat.cmp(&other.repeat))
477            .then_with(|| match core::ptr::eq(location, other_location) {
478                true => core::cmp::Ordering::Equal,
479                false => location.file().cmp(other_location.file()),
480            })
481    }
482}
483
484impl PartialOrd for Call {
485    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
486        Some(self.cmp(other))
487    }
488}