use cranpose_core::{RecordId, RecordRef};
use cranpose_render_common::{
graph::ProjectiveTransform, graph_scene::RenderDiagnostics, scene_store::SceneStore,
};
use super::{ContentStyle, LightSource, RasterTraversalContext, populate_draws_from_graph};
use crate::{
damage::merge_areas,
draw::{ClipBounds, TextRaster},
rewrite::Rewrite,
scene::{PassedDown, RasterScene, Subtree},
};
mod frame_shift;
struct Repush<'a> {
scene: &'a mut RasterScene,
rewrite: &'a mut Option<Box<Rewrite>>,
diagnostics: &'a RenderDiagnostics,
light: LightSource,
scale: f32,
text: &'a TextRaster,
}
struct Rebuild;
#[derive(Clone, Copy, PartialEq, Eq)]
enum RootKind {
Push,
Shift,
}
#[derive(Clone, Copy)]
pub(crate) struct PushRoot {
place: usize,
end: usize,
parent: Option<usize>,
record: RecordId,
kind: RootKind,
}
#[derive(Clone, Copy)]
pub(crate) struct Changed<'a> {
pub store: &'a SceneStore,
pub records: &'a [RecordRef],
pub updates: u32,
}
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum UpdatedReach {
Held,
#[default]
Lost,
}
pub(crate) struct InPlaceUpdate<'a> {
pub scene: &'a mut RasterScene,
pub reach: &'a mut Vec<Option<ClipBounds>>,
pub rewrite: &'a mut Option<Box<Rewrite>>,
pub roots: &'a mut Vec<PushRoot>,
}
impl InPlaceUpdate<'_> {
pub(crate) fn run(
self,
changed: Changed<'_>,
diagnostics: &RenderDiagnostics,
scale: f32,
text: &TextRaster,
window: ClipBounds,
areas: &mut Vec<ClipBounds>,
) -> Option<UpdatedReach> {
let InPlaceUpdate {
scene,
reach,
rewrite,
roots,
} = self;
areas.clear();
let store = changed.store;
let light = LightSource::of(store, scale);
if scene.start != Some(light) {
return None;
}
store.root_layer()?;
scene.refresh_routes();
roots.clear();
for &record in changed.records {
let Some(id) = store.resolve(record) else {
continue;
};
if store
.parent(id)
.is_some_and(|parent| store.changed_within(parent, changed.updates))
{
continue;
}
match push_root(scene, store, id, (roots, changed.records)) {
Ok(Some(root)) => add_root(roots, root),
Ok(None) => {}
Err(Rebuild) => return None,
}
}
let held = if reach.len() == scene.order.len() {
UpdatedReach::Held
} else {
UpdatedReach::Lost
};
if roots.is_empty() {
return Some(held);
}
rewrite
.get_or_insert_default()
.begin_update(window, reach, held);
let mut repush = Repush {
scene,
rewrite,
diagnostics,
light,
scale,
text,
};
let pushed = roots
.iter()
.try_for_each(|root| repush.push_root(store, root));
let held = session(repush.rewrite).end_update(reach, areas);
merge_areas(areas);
pushed.ok()?;
Some(held)
}
}
#[inline]
fn pushed_by(found: &[PushRoot], place: usize) -> bool {
match found.last() {
None => false,
Some(last) if last.place <= place => place < last.end,
Some(_) => pushed_by_earlier(found, place),
}
}
#[cold]
#[inline(never)]
fn pushed_by_earlier(found: &[PushRoot], place: usize) -> bool {
let after = found.partition_point(|root| root.place <= place);
after
.checked_sub(1)
.and_then(|before| found.get(before))
.is_some_and(|root| place < root.end)
}
#[inline]
fn add_root(found: &mut Vec<PushRoot>, root: PushRoot) {
if found.last().is_none_or(|last| last.end <= root.place) {
found.push(root);
} else {
add_root_between(found, root);
}
}
#[cold]
#[inline(never)]
fn add_root_between(found: &mut Vec<PushRoot>, root: PushRoot) {
let at = found.partition_point(|other| other.place < root.place);
let beneath = found
.iter()
.skip(at)
.take_while(|other| other.place < root.end)
.count();
found.drain(at..at + beneath);
found.insert(at, root);
}
fn push_root(
scene: &RasterScene,
store: &SceneStore,
record: RecordId,
(found, stamps): (&[PushRoot], &[RecordRef]),
) -> Result<Option<PushRoot>, Rebuild> {
let mut id = record;
let mut asked = false;
loop {
let parent = store.parent(id);
let Some(place) = scene.route(store.record_ref(id)) else {
id = parent.ok_or(Rebuild)?;
asked = true;
continue;
};
if let Some(frame) = frame_shift::frame_above(scene, store, place) {
id = frame;
asked = true;
continue;
}
if pushed_by(found, place) {
return Ok(None);
}
let old = &scene.subtrees[place];
let subtree = Subtree::of_record(store.layer(id));
if old.identity != subtree.identity() {
id = parent.ok_or(Rebuild)?;
asked = true;
continue;
}
let now = subtree.changes();
let moved = !old.changes.same_place(now);
let pushes = asked
|| moved
|| match subtree {
Subtree::Inline(_) => true,
Subtree::Layer(_) => {
!old.changes.same_own(now) || old.end == place + 1 || old.passed_down.is_none()
}
};
if !pushes {
return Ok(None);
}
let passed = match passed_down_above(scene, store, parent) {
Ok(passed) => passed,
Err(parent) => {
id = parent;
asked = true;
continue;
}
};
let shifts = !asked
&& moved
&& matches!(subtree, Subtree::Layer(_))
&& frame_shift::can_shift(scene, store, (old, id), stamps);
return Ok(Some(PushRoot {
place,
end: old.end,
parent: passed,
record: id,
kind: if shifts {
RootKind::Shift
} else {
RootKind::Push
},
}));
}
}
fn passed_down_above(
scene: &RasterScene,
store: &SceneStore,
parent: Option<RecordId>,
) -> Result<Option<usize>, RecordId> {
let Some(parent) = parent else {
return Ok(None);
};
passed_down_by(scene, store, parent).map(Some).ok_or(parent)
}
fn passed_down_by(scene: &RasterScene, store: &SceneStore, parent: RecordId) -> Option<usize> {
scene
.route(store.record_ref(parent))
.and_then(|at| scene.subtrees[at].passed_down)
}
fn session(slot: &mut Option<Box<Rewrite>>) -> &mut Rewrite {
slot.as_deref_mut()
.expect("the update holds its rewrite between pushes")
}
impl<'a> Repush<'a> {
#[inline(never)]
fn push_root(&mut self, store: &SceneStore, root: &PushRoot) -> Result<(), Rebuild> {
let record = root.record;
let (place, parent) = if session(self.rewrite).shifted() {
self.find_again(store, record)?
} else {
(root.place, root.parent)
};
if root.kind == RootKind::Shift && self.shift_frame(store, record, place, parent) {
return Ok(());
}
if !self.scene.frames.is_empty() {
self.forget_frames_within(place);
}
self.push_again(Subtree::of_record(store.layer(record)), place, parent)
}
#[cold]
#[inline(never)]
fn find_again(
&mut self,
store: &SceneStore,
record: RecordId,
) -> Result<(usize, Option<usize>), Rebuild> {
self.scene.refresh_routes();
let place = self.scene.route(store.record_ref(record)).ok_or(Rebuild)?;
let parent = match store.parent(record) {
Some(parent) => Some(passed_down_by(self.scene, store, parent).ok_or(Rebuild)?),
None => None,
};
Ok((place, parent))
}
#[expect(
clippy::inline_always,
reason = "the push and the frame step call it: out of line, the dashboard update took more instructions"
)]
#[inline(always)]
fn inherited(&self, passed: Option<&PassedDown>) -> (ProjectiveTransform, ContentStyle) {
let transform = passed.map_or_else(
|| ProjectiveTransform::uniform_scale(self.scale),
|passed| passed.transform,
);
let style = passed.map_or(ContentStyle::PLAIN, |passed| ContentStyle {
alpha: passed.alpha,
color_filter: passed.color_filter.clone(),
});
(transform, style)
}
#[expect(
clippy::inline_always,
reason = "the push and the frame step call it: out of line, the dashboard update took more instructions"
)]
#[inline(always)]
fn context<'c>(
&self,
passed: Option<&PassedDown>,
inherited: &'c (ProjectiveTransform, ContentStyle),
) -> RasterTraversalContext<'c>
where
'a: 'c,
{
RasterTraversalContext {
parent_transform: &inherited.0,
parent_content_style: &inherited.1,
parent_visual_clip: passed.and_then(|passed| passed.clip),
inherited_translated_snap_anchor: passed.and_then(|passed| passed.snap_anchor),
inherited_translated_content_context: passed.is_some_and(|passed| passed.translated),
diagnostics: self.diagnostics,
light: self.light,
same_as_before: false,
text: self.text,
surface_root: false,
in_space: false,
}
}
fn push_again(
&mut self,
subtree: Subtree<'_>,
record: usize,
parent: Option<usize>,
) -> Result<(), Rebuild> {
let passed = parent.and_then(|at| self.scene.passed_down.get(at));
let inherited = self.inherited(passed);
let context = self.context(passed, &inherited);
let mut rewrite = self.rewrite.take().expect("the update holds its rewrite");
if !rewrite.start(self.scene, record) {
*self.rewrite = Some(rewrite);
return Err(Rebuild);
}
self.scene.rewrite = Some(rewrite);
populate_draws_from_graph(subtree, self.scene, &context, &mut None);
let mut rewrite = self
.scene
.rewrite
.take()
.expect("the rewrite started above");
rewrite.finish(self.scene, record);
if rewrite.rerouted() && !self.scene.routes_stale {
let end = self.scene.subtrees.get(record).map_or(record, |at| at.end);
self.scene.route_records(record..end);
}
*self.rewrite = Some(rewrite);
Ok(())
}
}