use std::{
rc::Rc,
sync::atomic::{AtomicU16, Ordering},
};
use cranpose_core::{NodeId, RecordId, RecordRef, SceneUpdate, StoreId};
use cranpose_ui::{GraphicsLayer, Rect};
use cranpose_ui_graphics::CommandRecording;
use super::{
ChildOrder, Facts, GeoRecord, HashCache, Item, ItemKind, ItemLists, Journal, JournalEntry,
JournalRead, LayerProps, LayerRef, NodeRecords, Reach, RecordEvent, RecordEvents, RecordFlags,
RecordKind, RecordNode, ShapeChunks, ShapeRun, Slab, Span, SpanPool, TreeRecord, WarmRecord,
recordings::Recordings,
};
#[cfg(feature = "window-damage")]
use super::{ReachState, own_marks};
#[cfg(feature = "layer-tree")]
use crate::graph::LayerNode;
use crate::graph::{
DrawCommandId, DrawPrimitiveNode, DrawRunNode, ProjectiveTransform, TextPrimitiveNode,
};
pub struct SceneStore {
id: StoreId,
pub(super) tree: Vec<TreeRecord>,
pub(super) geo: Vec<GeoRecord>,
pub(super) warm: Vec<WarmRecord>,
pub(super) generations: Vec<u32>,
pub(super) generation_floor: u32,
pub(super) free_rows: Vec<u32>,
pub(super) items: SpanPool<Item>,
#[cfg(feature = "window-damage")]
pub(super) marks: own_marks::Marks,
pub(super) props: Slab<LayerProps>,
pub(super) graphics_layers: Slab<GraphicsLayer>,
pub(super) transforms: Slab<ProjectiveTransform>,
pub(super) draws: Slab<DrawPrimitiveNode>,
pub(super) texts: Slab<TextPrimitiveNode>,
pub(super) runs: Slab<DrawRunNode>,
pub(super) shape_runs: Slab<ShapeRun>,
pub(super) shape_chunks: ShapeChunks,
pub(super) hashes: HashCache,
pub(super) facts: Facts,
pub(super) node_records: NodeRecords,
pub(crate) lists: ItemLists,
root: Option<RecordId>,
update: SceneUpdate,
pub(super) journal: Journal,
pub(super) order: ChildOrder,
pub(crate) recordings: Recordings,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SceneVersion {
store: StoreId,
update: SceneUpdate,
}
impl SceneVersion {
pub fn update(self) -> SceneUpdate {
self.update
}
}
#[derive(Clone, Copy, Debug)]
pub struct RecordSeed {
pub kind: RecordKind,
pub node: Option<NodeId>,
pub parent: Option<RecordId>,
}
fn next_store_id() -> StoreId {
static NEXT: AtomicU16 = AtomicU16::new(1);
loop {
if let Some(id) = StoreId::new(NEXT.fetch_add(1, Ordering::Relaxed)) {
return id;
}
}
}
impl Default for SceneStore {
fn default() -> Self {
Self::new()
}
}
impl SceneStore {
pub fn new() -> Self {
Self {
id: next_store_id(),
tree: Vec::new(),
geo: Vec::new(),
warm: Vec::new(),
generations: Vec::new(),
generation_floor: 0,
free_rows: Vec::new(),
items: SpanPool::default(),
#[cfg(feature = "window-damage")]
marks: own_marks::Marks::default(),
props: Slab::default(),
graphics_layers: Slab::default(),
transforms: Slab::default(),
draws: Slab::default(),
texts: Slab::default(),
runs: Slab::default(),
shape_runs: Slab::default(),
shape_chunks: ShapeChunks::default(),
hashes: HashCache::default(),
facts: Facts::default(),
node_records: NodeRecords::default(),
lists: ItemLists::default(),
root: None,
update: SceneUpdate::default(),
journal: Journal::default(),
order: ChildOrder::default(),
recordings: Recordings::default(),
}
}
#[inline]
pub fn id(&self) -> StoreId {
self.id
}
pub fn version(&self) -> SceneVersion {
SceneVersion {
store: self.id,
update: self.update,
}
}
pub fn root(&self) -> Option<RecordId> {
self.root
}
pub fn update(&self) -> SceneUpdate {
self.update
}
pub fn begin_update(&mut self) -> SceneUpdate {
self.recordings.begin_update();
self.update = self.update.next();
self.journal.begin(self.update, self.tree.len());
self.update
}
#[inline]
pub fn changed_within(&self, id: RecordId, updates: u32) -> bool {
let row = &self.tree[id.index()];
self.update.since(row.content_rev) < updates || self.update.since(row.place_rev) < updates
}
#[inline]
fn touch(&mut self, index: usize) {
let tree = &self.tree[index];
if self.journal.follows_stamps()
&& tree.content_rev != self.update
&& tree.place_rev != self.update
{
self.journal.stamp(RecordRef {
id: RecordId::from_index(index).expect("a row is a record"),
generation: self.generations[index],
});
}
}
pub fn follow(&mut self, events: RecordEvents) {
if self.journal.followed() != events {
self.journal.follow(events);
self.mark_for_redraws();
}
}
#[cfg(feature = "window-damage")]
#[inline]
pub(super) fn follows_redrawn_reach(&self) -> bool {
self.journal.wants_redrawn_reach(self.update)
}
#[cfg(feature = "window-damage")]
fn mark_for_redraws(&mut self) {
if self.follows_redrawn_reach() {
own_marks::refresh_lost(self);
}
}
#[cfg(not(feature = "window-damage"))]
#[inline]
fn mark_for_redraws(&mut self) {}
pub fn changes_since(&self, read: Option<SceneVersion>) -> JournalRead<'_> {
match read {
Some(read) if read.store == self.id => self.journal.since(read.update, self.update),
_ => JournalRead::Lost,
}
}
pub fn stamps_since(&self, read: Option<SceneVersion>) -> Option<&[RecordRef]> {
let read = read.filter(|read| read.store == self.id)?;
self.journal.stamps_since(read.update, self.update)
}
pub fn changed_since(&self, read: Option<SceneVersion>) -> bool {
match read {
Some(read) if read.store == self.id => self.journal.changed_since(read.update),
_ => true,
}
}
#[inline]
pub(super) fn log(&mut self, event: RecordEvent, id: RecordId) {
self.journal.note_change(self.update);
if self.journal.wants(event, self.update) {
self.log_entry(event, id);
}
}
fn log_entry(&mut self, event: RecordEvent, id: RecordId) {
let index = id.index();
self.journal.log(JournalEntry {
update: self.update,
event,
record: RecordRef {
id,
generation: self.generations[index],
},
parent: self.tree[index].parent.map(|parent| RecordRef {
id: parent,
generation: self.generations[parent.index()],
}),
node: self.warm[index].node.map(RecordNode::id),
});
}
pub fn finish_update(&mut self) {
super::child_order::settle(self);
#[cfg(feature = "window-damage")]
own_marks::settle(self);
}
pub fn trim(&mut self) -> bool {
super::growth_slack::trim(self)
}
#[expect(
clippy::inline_always,
reason = "the collect walk and the update call it for every record; out of line the gauntlet frame took 2% more instructions"
)]
#[inline(always)]
#[cfg(feature = "window-damage")]
pub(super) fn redraw_pending(&mut self, index: usize) {
if !self.follows_redrawn_reach() {
own_marks::lose(self, index);
return;
}
let flags = &mut self.tree[index].flags;
if !flags.contains(RecordFlags::REDRAW_PENDING) {
*flags = flags.with(RecordFlags::REDRAW_PENDING);
self.marks.redrawn.push(RecordRef {
id: RecordId::from_index(index).expect("a row is a record"),
generation: self.generations[index],
});
}
}
#[cfg(not(feature = "window-damage"))]
#[inline]
pub(super) fn redraw_pending(&mut self, index: usize) {
self.log(
RecordEvent::Redrawn(Reach::Unknown),
RecordId::from_index(index).expect("a row is a record"),
);
}
#[cfg(feature = "window-damage")]
pub(super) fn reach(&self, index: usize) -> Reach {
match self.tree[index].reach_state {
ReachState::Empty => Reach::Empty,
ReachState::Finite => Reach::Finite(self.geo[index].reach),
ReachState::Unknown => Reach::Unknown,
}
}
#[cfg(feature = "window-damage")]
pub(super) fn set_reach(&mut self, index: usize, reach: Reach) {
let (state, rect) = match reach {
Reach::Empty => (ReachState::Empty, Rect::default()),
Reach::Finite(rect) => (ReachState::Finite, rect),
Reach::Unknown => (ReachState::Unknown, Rect::default()),
};
self.tree[index].reach_state = state;
self.geo[index].reach = rect;
}
#[cfg(feature = "window-damage")]
#[inline]
pub(super) fn stale(&mut self, index: usize) {
if !self.tree[index].flags.contains(RecordFlags::REACH_STALE)
|| super::facts::keeps_contained(self, index)
{
self.stale_climb(index);
}
}
#[cfg(not(feature = "window-damage"))]
#[inline]
pub(super) fn stale(&mut self, _index: usize) {}
#[cfg(feature = "window-damage")]
#[inline(never)]
fn stale_climb(&mut self, index: usize) {
super::facts::forget_contained(self, index);
self.reach_stale(index);
}
#[cfg(feature = "window-damage")]
fn reach_stale(&mut self, index: usize) {
let mut current = Some(index);
while let Some(index) = current {
let flags = &mut self.tree[index].flags;
if flags.contains(RecordFlags::REACH_STALE) {
break;
}
*flags = flags.with(RecordFlags::REACH_STALE);
current = self.tree[index].parent.map(RecordId::index);
}
}
#[cfg(feature = "window-damage")]
pub fn refresh_reach(&mut self) {
own_marks::refresh_lost(self);
if let Some(root) = self.root {
super::reach::refresh(self, root);
}
}
#[inline]
pub(super) fn stale_with_parent(&mut self, index: usize) {
self.stale(index);
if let Some(parent) = self.tree[index].parent {
self.stale(parent.index());
}
}
#[cfg(feature = "layer-tree")]
pub fn from_layer(root: &LayerNode) -> Self {
let mut store = Self::new();
store.describe(root);
store
}
#[cfg(feature = "layer-tree")]
pub fn describe(&mut self, root: &LayerNode) {
self.begin_update();
super::spec::write_root(self, root);
self.finish_update();
}
#[inline]
pub fn layer(&self, id: RecordId) -> LayerRef<'_> {
LayerRef::new(self, id)
}
pub fn root_layer(&self) -> Option<LayerRef<'_>> {
self.root.map(|root| self.layer(root))
}
pub fn heap_bytes(&self) -> usize {
super::heap_bytes::store_heap_bytes(self)
}
pub fn node_count(&self) -> usize {
self.record_count()
+ self.draws.values().count()
+ self.texts.values().count()
+ self.runs.values().map(DrawRunNode::len).sum::<usize>()
+ self.shape_item_count()
}
pub fn record_count(&self) -> usize {
self.tree.len() - self.free_rows.len()
}
pub fn clear(&mut self) {
self.tree.clear();
self.geo.clear();
self.warm.clear();
if let Some(&last) = self.generations.iter().max() {
self.generation_floor = self.generation_floor.max(last.wrapping_add(1));
}
self.generations.clear();
self.free_rows = Vec::new();
self.items.clear();
#[cfg(feature = "window-damage")]
self.marks.clear();
self.props.clear();
self.graphics_layers.clear();
self.transforms.clear();
self.draws.clear();
self.texts.clear();
self.runs.clear();
self.clear_shapes();
self.hashes.clear();
self.facts.clear();
self.node_records.clear();
self.root = None;
self.update = self.update.next();
self.journal.clear(self.update);
}
pub(crate) fn reserve_records(&mut self, records: usize) {
let more = records.saturating_sub(self.free_rows.len());
self.tree.reserve_exact(more);
self.geo.reserve_exact(more);
self.warm.reserve_exact(more);
self.generations.reserve_exact(more);
self.facts.reserve_rows(self.tree.len() + more);
self.node_records.reserve(more);
}
pub fn insert(&mut self, seed: RecordSeed) -> RecordId {
let update = self.update;
let tree = TreeRecord {
parent: seed.parent,
items: Span::default(),
kind: seed.kind,
#[cfg(feature = "window-damage")]
reach_state: ReachState::Empty,
flags: RecordFlags::default(),
content_rev: update,
place_rev: update,
subtree_rev: update,
transform: None,
};
let warm = WarmRecord {
node: seed.node.map(RecordNode::of),
props: None,
graphics_layer: None,
content_offset: [0.0; 2],
#[cfg(feature = "window-damage")]
own_marks: Span::default(),
};
let id = match self.free_rows.pop() {
Some(row) => {
let index = row as usize;
self.tree[index] = tree;
self.geo[index] = GeoRecord::default();
self.warm[index] = warm;
RecordId::from_index(index).expect("a freed row was a record")
}
None => {
self.tree.push(tree);
self.geo.push(GeoRecord::default());
self.warm.push(warm);
self.generations.push(self.generation_floor);
RecordId::from_index(self.tree.len() - 1).expect("fewer than 2^32 records")
}
};
self.facts.open_row(id.index());
self.node_records.claim(id, seed.kind, seed.node);
match seed.parent {
Some(parent) => self.note_subtree_change(Some(parent)),
None => self.root = Some(id),
}
self.stale_with_parent(id.index());
#[cfg(feature = "window-damage")]
own_marks::pend_inserted(self, id.index());
self.log(RecordEvent::Inserted, id);
if self.journal.follows_stamps() {
self.journal.stamp(self.record_ref(id));
}
id
}
#[inline(never)]
pub fn remove_subtree(&mut self, id: RecordId) {
self.log(RecordEvent::Removed, id);
let index = id.index();
self.node_records
.release(id, self.tree[index].kind, self.node(id));
if let Some(parent) = self.tree[index].parent {
self.stale(parent.index());
}
let span = self.tree[index].items;
for position in 0..span.len() {
let item = self.items.span(span)[position];
self.remove_item(item);
}
self.items.free_span(span);
self.tree[index].items = Span::default();
#[cfg(feature = "window-damage")]
self.marks
.pool
.free_span(std::mem::take(&mut self.warm[index].own_marks));
self.hashes.remove(index);
self.drop_props(index);
if let Some(transform) = self.tree[index].transform.take() {
self.transforms.remove(transform.index());
}
self.generations[index] = self.generations[index].wrapping_add(1);
self.free_rows
.push(u32::try_from(index).expect("fewer than 2^32 records"));
if self.root == Some(id) {
self.root = None;
}
}
pub fn remove_item(&mut self, item: Item) {
match item.kind() {
ItemKind::Child => {
if let Some(child) = item.as_child() {
self.remove_subtree(child);
}
}
ItemKind::Draw => {
self.draws.remove(item.index());
}
ItemKind::Text => {
self.texts.remove(item.index());
}
ItemKind::Run => {
if let Some(run) = self.runs.take(item.index()) {
self.keep_released(run.command, &run.recording);
}
}
ItemKind::Shape => self.remove_shapes(item.index()),
}
}
#[inline]
pub fn record_ref(&self, id: RecordId) -> RecordRef {
RecordRef {
id,
generation: self.generations[id.index()],
}
}
#[inline]
pub fn resolve(&self, held: RecordRef) -> Option<RecordId> {
(self.generations.get(held.id.index()) == Some(&held.generation)).then_some(held.id)
}
#[inline]
pub fn items(&self, id: RecordId) -> &[Item] {
self.items.span(self.tree[id.index()].items)
}
pub(crate) fn write_items(&mut self, id: RecordId, items: &[Item]) {
self.replace_items(id, items);
self.stale(id.index());
}
pub(super) fn replace_items(&mut self, id: RecordId, items: &[Item]) -> bool {
let index = id.index();
let old = self.items.span(self.tree[index].items);
if old == items {
return false;
}
if !super::facts::same_children(old, items) {
super::facts::forget_children(self, index);
}
super::facts::forget_own(self, index);
let noted = self.journal.follows(RecordEvent::Changed);
if noted {
let record = self.record_ref(id);
self.order.note(record, old);
}
self.tree[index].items = self.items.write(self.tree[index].items, items);
self.touch(index);
if !noted {
self.journal.note_change(self.update);
}
true
}
pub fn add_draw(&mut self, draw: DrawPrimitiveNode) -> Item {
Item::new(ItemKind::Draw, self.draws.insert(draw))
}
pub fn add_text(&mut self, text: TextPrimitiveNode) -> Item {
Item::new(ItemKind::Text, self.texts.insert(text))
}
pub fn add_run(&mut self, run: DrawRunNode) -> Item {
Item::new(ItemKind::Run, self.runs.insert(run))
}
#[inline]
pub fn draw(&self, item: Item) -> &DrawPrimitiveNode {
&self.draws[item.index()]
}
#[inline]
pub fn text(&self, item: Item) -> &TextPrimitiveNode {
&self.texts[item.index()]
}
pub(crate) fn text_mut(&mut self, item: Item) -> &mut TextPrimitiveNode {
&mut self.texts[item.index()]
}
#[inline]
pub fn run(&self, item: Item) -> &DrawRunNode {
&self.runs[item.index()]
}
#[inline]
pub(crate) fn run_mut(&mut self, item: Item) -> &mut DrawRunNode {
&mut self.runs[item.index()]
}
pub(crate) fn swap_run_recording(&mut self, item: Item, recording: Rc<CommandRecording>) {
let run = &mut self.runs[item.index()];
if Rc::ptr_eq(&run.recording, &recording) {
return;
}
let command = run.command;
let old = std::mem::replace(&mut run.recording, recording);
self.keep_released(command, &old);
}
fn keep_released(&mut self, command: Option<DrawCommandId>, recording: &Rc<CommandRecording>) {
if let Some(id) = command {
self.recordings.keep(id, recording);
}
}
#[inline]
pub fn kind(&self, id: RecordId) -> RecordKind {
self.tree[id.index()].kind
}
#[inline]
pub fn node(&self, id: RecordId) -> Option<NodeId> {
self.warm[id.index()].node.map(RecordNode::id)
}
#[inline]
pub fn parent(&self, id: RecordId) -> Option<RecordId> {
self.tree[id.index()].parent
}
pub(crate) fn record_of(&self, node: NodeId) -> Option<RecordId> {
self.node_records.get(node)
}
pub(crate) fn drawn_parent(&self, node: NodeId) -> Option<NodeId> {
let mut record = self.record_of(node)?;
loop {
record = self.parent(record)?;
if let Some(parent) = self.node(record)
&& parent != node
{
return Some(parent);
}
}
}
#[inline]
pub fn flags(&self, id: RecordId) -> RecordFlags {
self.tree[id.index()].flags
}
pub(crate) fn write_flags(&mut self, id: RecordId, flags: RecordFlags) -> bool {
let changed = self.write_flag_row(id.index(), flags);
if changed {
self.stale_with_parent(id.index());
}
changed
}
#[inline]
pub fn node_rect(&self, id: RecordId) -> Rect {
self.geo[id.index()].node_rect()
}
#[inline]
pub(crate) fn write_size(&mut self, id: RecordId, width: f32, height: f32) -> bool {
let index = id.index();
let size = [width, height];
if super::records::same_pair(self.geo[index].size, size) {
return false;
}
self.geo[index].size = size;
self.stale_with_parent(index);
true
}
#[inline]
pub fn set_kind(&mut self, id: RecordId, kind: RecordKind, node: Option<NodeId>) -> bool {
let index = id.index();
let changed =
self.tree[index].kind != kind || self.warm[index].node != node.map(RecordNode::of);
if changed {
self.change_kind(id, kind, node);
}
changed
}
#[inline(never)]
fn change_kind(&mut self, id: RecordId, kind: RecordKind, node: Option<NodeId>) {
let index = id.index();
self.log(RecordEvent::Released, id);
self.node_records
.release(id, self.tree[index].kind, self.node(id));
self.node_records.claim(id, kind, node);
self.tree[index].kind = kind;
self.warm[index].node = node.map(RecordNode::of);
self.stale_with_parent(index);
self.log(RecordEvent::Claimed, id);
self.touch(index);
}
pub(crate) fn drop_items(&mut self, id: RecordId) {
let index = id.index();
let span = self.tree[index].items;
if !super::facts::same_children(self.items.span(span), &[]) {
super::facts::forget_children(self, index);
}
for position in 0..span.len() {
let item = self.items.span(span)[position];
self.remove_item(item);
}
self.items.free_span(span);
self.tree[index].items = Span::default();
super::facts::forget_own(self, index);
self.stale(index);
if span.len() != 0 {
self.touch(index);
}
}
pub fn note_content_change(&mut self, id: RecordId) {
let update = self.update;
let index = id.index();
self.redraw_pending(index);
self.stale(index);
super::facts::forget_own(self, index);
self.touch(index);
let tree = &mut self.tree[index];
tree.content_rev = update;
let raise = tree.subtree_rev != update;
self.note_content_run(index);
if raise {
self.raise_subtree_revs(id);
}
}
pub fn note_property_change(&mut self, id: RecordId) {
let update = self.update;
let index = id.index();
if self.tree[index].content_rev != update {
self.log(RecordEvent::Changed, id);
}
self.touch(index);
let tree = &mut self.tree[index];
tree.content_rev = update;
tree.subtree_rev = update;
let parent = tree.parent;
self.note_subtree_change(parent);
}
#[inline]
pub(super) fn moved(&mut self, index: usize) {
if self.tree[index].place_rev != self.update {
self.touch(index);
self.tree[index].place_rev = self.update;
self.log(
RecordEvent::Moved,
RecordId::from_index(index).expect("a row is a record"),
);
self.note_subtree_change(self.tree[index].parent);
}
}
#[inline]
pub(super) fn note_subtree_change(&mut self, from: Option<RecordId>) {
if let Some(record) = from
&& self.tree[record.index()].subtree_rev != self.update
{
self.raise_subtree_revs(record);
}
}
#[inline(never)]
fn raise_subtree_revs(&mut self, from: RecordId) {
let update = self.update;
let mut current = Some(from);
while let Some(record) = current {
let index = record.index();
let tree = &mut self.tree[index];
if tree.subtree_rev == update {
break;
}
tree.subtree_rev = update;
current = tree.parent;
self.note_content_run(index);
}
}
#[cfg(feature = "window-damage")]
#[inline]
fn note_content_run(&mut self, index: usize) {
if self.tree[index].flags.contains(RecordFlags::HAS_PROPS)
&& let Some(props) = self.warm[index].props
{
self.props[props.index()].content_run.note(self.update);
}
}
#[cfg(not(feature = "window-damage"))]
#[inline]
fn note_content_run(&mut self, _index: usize) {}
pub fn content_rev(&self, id: RecordId) -> SceneUpdate {
self.tree[id.index()].content_rev
}
}