finished moving out render_state

This commit is contained in:
2026-01-19 18:00:24 -05:00
parent 79813db3ba
commit 06dd015092
26 changed files with 497 additions and 221 deletions

View File

@@ -13,6 +13,6 @@ pub struct EventIdCtx<'a, Rsc: HasEvents, Data, W: ?Sized> {
impl<Rsc: HasEvents, Data, W: Widget> EventIdCtx<'_, Rsc, Data, W> {
pub fn widget<'a>(&self, rsc: &'a mut Rsc) -> &'a mut W {
&mut rsc.widgets_mut()[self.widget]
&mut rsc.ui_mut().widgets[self.widget]
}
}

View File

@@ -1,6 +1,6 @@
use crate::{
ActiveData, Event, EventCtx, EventFn, EventIdCtx, EventLike, HasEvents, IdLike, LayerId,
Widget, WidgetEventFn, WidgetId, WeakWidget,
WeakWidget, Widget, WidgetEventFn, WidgetId,
util::{HashMap, HashSet, TypeMap},
};
use std::{any::TypeId, rc::Rc};
@@ -28,7 +28,7 @@ impl<Rsc: HasEvents + 'static> EventManager<Rsc> {
&mut self,
id: WeakWidget<W>,
event: E,
f: impl WidgetEventFn<Rsc, <E::Event as Event>::Data, W>,
f: impl for<'a> WidgetEventFn<Rsc, <E::Event as Event>::Data<'a>, W>,
) {
self.get_type::<E>().register(id, event, f);
self.widget_to_types
@@ -74,7 +74,7 @@ pub trait EventManagerLike<State> {
fn undraw(&mut self, data: &ActiveData);
}
type EventData<Rsc, E> = (E, Rc<dyn EventFn<Rsc, <E as Event>::Data>>);
type EventData<Rsc, E> = (E, Rc<dyn for<'a> EventFn<Rsc, <E as Event>::Data<'a>>>);
pub struct TypeEventManager<Rsc: HasEvents, E: Event> {
// TODO: reduce visiblity!!
pub active: HashMap<LayerId, HashMap<WidgetId, E::State>>,
@@ -116,7 +116,7 @@ impl<Rsc: HasEvents + 'static, E: Event> TypeEventManager<Rsc, E> {
&mut self,
widget: WeakWidget<W>,
event: impl EventLike<Event = E>,
f: impl WidgetEventFn<Rsc, E::Data, W>,
f: impl for<'a> WidgetEventFn<Rsc, E::Data<'a>, W>,
) {
let event = event.into_event();
self.map.entry(widget.id()).or_default().push((
@@ -137,7 +137,7 @@ impl<Rsc: HasEvents + 'static, E: Event> TypeEventManager<Rsc, E> {
pub fn run_fn<'a>(
&mut self,
id: impl IdLike,
) -> impl FnOnce(EventCtx<'_, Rsc, E::Data>, &mut Rsc) + 'a {
) -> impl for<'b> FnOnce(EventCtx<'_, Rsc, E::Data<'b>>, &mut Rsc) + 'a {
let fs = self.map.get(&id.id()).cloned().unwrap_or_default();
move |ctx, rsc| {
for (e, f) in fs {

View File

@@ -7,10 +7,10 @@ pub use manager::*;
pub use rsc::*;
pub trait Event: Sized + 'static + Clone {
type Data: Clone = ();
type Data<'a>: Clone = ();
type State: Default = ();
#[allow(unused_variables)]
fn should_run(&self, data: &Self::Data) -> Option<Self::Data> {
fn should_run<'a>(&self, data: &Self::Data<'a>) -> Option<Self::Data<'a>> {
Some(data.clone())
}
}

View File

@@ -1,5 +1,5 @@
use crate::{
Event, EventCtx, EventLike, EventManager, IdLike, UiRsc, Widget, WidgetEventFn, WeakWidget,
Event, EventCtx, EventLike, EventManager, IdLike, UiRsc, WeakWidget, Widget, WidgetEventFn,
};
pub trait HasState: 'static {
@@ -14,7 +14,7 @@ pub trait HasEvents: Sized + UiRsc + HasState {
&mut self,
id: WeakWidget<W>,
event: E,
f: impl WidgetEventFn<Self, <E::Event as Event>::Data, W>,
f: impl for<'a> WidgetEventFn<Self, <E::Event as Event>::Data<'a>, W>,
) {
self.events_mut().register(id, event, f);
}
@@ -24,7 +24,7 @@ pub trait RunEvents: HasEvents {
fn run_event<E: EventLike>(
&mut self,
id: impl IdLike,
data: <E::Event as Event>::Data,
data: <E::Event as Event>::Data<'_>,
state: &mut Self::State,
) {
let f = self.events_mut().get_type::<E>().run_fn(id);

View File

@@ -7,12 +7,3 @@ pub use color::*;
pub use layer::*;
pub use text::*;
pub use texture::*;
use crate::{Mask, util::TrackedArena};
#[derive(Default)]
pub struct PainterData {
pub textures: Textures,
pub text: TextData,
pub masks: TrackedArena<Mask, u32>,
}

View File

@@ -1,7 +1,7 @@
use std::num::NonZero;
use crate::{
Textures, UiRenderState,
UiData, UiRenderState,
render::{data::PrimitiveInstance, texture::GpuTextures, util::ArrBuf},
util::HashMap,
};
@@ -63,14 +63,14 @@ impl UiRenderNode {
&mut self,
device: &Device,
queue: &Queue,
ui: &mut UiRenderState,
textures: &mut Textures,
ui: &mut UiData,
ui_render: &mut UiRenderState,
) {
self.active.clear();
for (i, primitives) in ui.layers.iter_mut() {
for (i, primitives) in ui_render.layers.iter_mut() {
self.active.push(i);
for change in primitives.apply_free() {
if let Some(inst) = ui.active.get_mut(&change.id) {
if let Some(inst) = ui_render.active.get_mut(&change.id) {
for h in &mut inst.primitives {
if h.layer == i && h.inst_idx == change.old {
h.inst_idx = change.new;
@@ -107,7 +107,7 @@ impl UiRenderNode {
}
}
let mut changed = false;
changed |= self.textures.update(textures);
changed |= self.textures.update(&mut ui.textures);
if ui.masks.changed {
ui.masks.changed = false;
self.masks.update(device, queue, &ui.masks[..]);

View File

@@ -1,6 +1,6 @@
use crate::{
ActiveData, Axis, EventsLike, Painter, PainterData, SizeCtx, StrongWidget, UiRegion,
UiRenderState, UiVec2, WidgetId, Widgets,
ActiveData, Axis, EventsLike, Painter, SizeCtx, StrongWidget, UiRegion, UiRenderState, UiVec2,
WidgetId, Widgets,
render::MaskIdx,
util::{HashSet, forget_ref},
};
@@ -16,30 +16,6 @@ pub struct Drawer<'a> {
}
impl<'a> Drawer<'a> {
pub fn new(
widgets: &'a mut Widgets,
data: &'a mut PainterData,
render: &'a mut UiRenderState,
events: &'a mut dyn EventsLike,
root: Option<&'a StrongWidget>,
) -> Self {
Self {
widgets,
data,
events,
render,
root,
draw_started: Default::default(),
}
}
pub fn redraw_updates(&mut self) {
while let Some(&id) = self.widgets.needs_redraw.iter().next() {
self.redraw(id);
}
self.ui.free(self.events);
}
/// redraws a widget that's currently active (drawn)
pub fn redraw(&mut self, id: WidgetId) {
self.widgets.needs_redraw.remove(&id);
@@ -94,21 +70,6 @@ impl<'a> Drawer<'a> {
}
}
pub fn redraw_all(&mut self) {
// free all resources & cache
for (_, active) in self.render.active.drain() {
self.events.undraw(&active);
}
self.render.cache.clear();
self.ui.free(self.events);
self.render.layers.clear();
self.widgets.needs_redraw.clear();
if let Some(id) = self.root {
self.draw_inner(0, id.id(), UiRegion::FULL, None, MaskIdx::NONE, None);
}
}
pub(super) fn draw_inner(
&mut self,
layer: usize,

View File

@@ -1,8 +1,8 @@
use crate::{WeakWidget, Widget, Widgets};
use crate::{Mask, TextData, Textures, WeakWidget, WidgetId, Widgets, util::TrackedArena};
mod active;
mod cache;
mod draw_state;
// mod draw_state;
mod painter;
mod render_state;
mod size;
@@ -13,10 +13,37 @@ pub use painter::Painter;
pub use render_state::*;
pub use size::*;
pub struct Ui {}
pub trait UiRsc: Sized {
fn add_widget<W: Widget>(&mut self, widget: W) -> WeakWidget<W>;
fn widgets(&self) -> &Widgets;
fn widgets_mut(&mut self) -> &mut Widgets;
#[derive(Default)]
pub struct UiData {
pub widgets: Widgets,
pub textures: Textures,
pub text: TextData,
pub masks: TrackedArena<Mask, u32>,
}
pub trait UiRsc {
fn ui(&self) -> &UiData;
fn ui_mut(&mut self) -> &mut UiData;
#[allow(unused_variables)]
fn on_add(&mut self, id: WeakWidget) {}
#[allow(unused_variables)]
fn on_remove(&mut self, id: WidgetId) {}
#[allow(unused_variables)]
fn on_draw(&mut self, active: &ActiveData) {}
#[allow(unused_variables)]
fn on_undraw(&mut self, active: &ActiveData) {}
fn widgets(&self) -> &Widgets {
&self.ui().widgets
}
fn widgets_mut(&mut self) -> &mut Widgets {
&mut self.ui_mut().widgets
}
fn free(&mut self) {
while let Some(id) = self.widgets_mut().free_next() {
self.on_remove(id);
}
self.ui_mut().textures.free();
}
}

View File

@@ -1,14 +1,14 @@
use crate::{
Axis, Len, RenderedText, Size, SizeCtx, StrongWidget, TextAttrs, TextBuffer, TextData,
TextureHandle, UiRegion, Widget, WidgetId,
TextureHandle, UiRegion, UiRenderState, UiRsc, Widget, WidgetId,
render::{Mask, MaskIdx, Primitive, PrimitiveHandle, PrimitiveInst},
ui::draw_state::Drawer,
util::Vec2,
};
/// makes your surfaces look pretty
pub struct Painter<'a, 'b> {
pub(super) drawer: &'a mut Drawer<'b>,
pub struct Painter<'a> {
pub(super) state: &'a mut UiRenderState,
pub(super) rsc: &'a mut dyn UiRsc,
pub(super) region: UiRegion,
pub(super) mask: MaskIdx,
@@ -19,9 +19,9 @@ pub struct Painter<'a, 'b> {
pub(super) id: WidgetId,
}
impl<'a, 'c> Painter<'a, 'c> {
impl<'a> Painter<'a> {
fn primitive_at<P: Primitive>(&mut self, primitive: P, region: UiRegion) {
let h = self.drawer.layers.write(
let h = self.state.layers.write(
self.layer,
PrimitiveInst {
id: self.id,
@@ -32,7 +32,7 @@ impl<'a, 'c> Painter<'a, 'c> {
);
if self.mask != MaskIdx::NONE {
// TODO: I have no clue if this works at all :joy:
self.drawer.masks.push_ref(self.mask);
self.rsc.ui_mut().masks.push_ref(self.mask);
}
self.primitives.push(h);
}
@@ -48,7 +48,7 @@ impl<'a, 'c> Painter<'a, 'c> {
pub fn set_mask(&mut self, region: UiRegion) {
assert!(self.mask == MaskIdx::NONE);
self.mask = self.drawer.masks.push(Mask { region });
self.mask = self.rsc.ui_mut().masks.push(Mask { region });
}
/// Draws a widget within this widget's region.
@@ -64,8 +64,15 @@ impl<'a, 'c> Painter<'a, 'c> {
fn widget_at<W: ?Sized>(&mut self, id: &StrongWidget<W>, region: UiRegion) {
self.children.push(id.id());
self.drawer
.draw_inner(self.layer, id.id(), region, Some(self.id), self.mask, None);
self.state.draw_inner(
self.layer,
id.id(),
region,
Some(self.id),
self.mask,
None,
self.rsc,
);
}
pub fn texture_within(&mut self, handle: &TextureHandle, region: UiRegion) {
@@ -85,10 +92,8 @@ impl<'a, 'c> Painter<'a, 'c> {
/// returns (handle, offset from top left)
pub fn render_text(&mut self, buffer: &mut TextBuffer, attrs: &TextAttrs) -> RenderedText {
self.drawer
.ui
.text
.draw(buffer, attrs, &mut self.drawer.ui.textures)
let ui = self.rsc.ui_mut();
ui.text.draw(buffer, attrs, &mut ui.textures)
}
pub fn region(&self) -> UiRegion {
@@ -107,27 +112,27 @@ impl<'a, 'c> Painter<'a, 'c> {
}
pub fn output_size(&self) -> Vec2 {
self.drawer.output_size
self.state.output_size
}
pub fn px_size(&mut self) -> Vec2 {
self.region.size().to_abs(self.drawer.output_size)
self.region.size().to_abs(self.state.output_size)
}
pub fn text_data(&mut self) -> &mut TextData {
&mut self.drawer.text
&mut self.rsc.ui_mut().text
}
pub fn child_layer(&mut self) {
self.layer = self.drawer.layers.child(self.layer);
self.layer = self.state.layers.child(self.layer);
}
pub fn next_layer(&mut self) {
self.layer = self.drawer.layers.next(self.layer);
self.layer = self.state.layers.next(self.layer);
}
pub fn label(&self) -> &str {
&self.drawer.widgets.data(self.id).unwrap().label
&self.rsc.widgets().data(self.id).unwrap().label
}
pub fn id(&self) -> &WidgetId {
@@ -135,6 +140,6 @@ impl<'a, 'c> Painter<'a, 'c> {
}
pub fn size_ctx(&mut self) -> SizeCtx<'_> {
self.drawer.size_ctx(self.id, self.region.size())
self.state.size_ctx(self.id, self.region.size(), self.rsc)
}
}

View File

@@ -1,7 +1,8 @@
use crate::{
ActiveData, EventsLike, IdLike, PixelRegion, PrimitiveLayers, StrongWidget, WidgetId, Widgets,
ui::{cache::Cache, draw_state::Drawer},
util::{HashMap, Vec2},
ActiveData, Axis, IdLike, MaskIdx, Painter, PixelRegion, PrimitiveLayers, SizeCtx,
StrongWidget, UiRegion, UiRsc, UiVec2, WidgetId, Widgets,
ui::cache::Cache,
util::{HashMap, HashSet, Vec2, forget_ref},
};
pub struct UiRenderState {
@@ -12,6 +13,7 @@ pub struct UiRenderState {
old_root: Option<WidgetId>,
resized: bool,
draw_started: HashSet<WidgetId>,
}
impl UiRenderState {
@@ -23,6 +25,7 @@ impl UiRenderState {
output_size: Vec2::ZERO,
old_root: None,
resized: false,
draw_started: Default::default(),
}
}
@@ -31,15 +34,11 @@ impl UiRenderState {
self.resized = true;
}
pub fn update<'a>(
&mut self,
root: impl Into<Option<&'a StrongWidget>>,
widgets: &mut Widgets,
events: &mut dyn EventsLike,
) {
pub fn update<'a>(&mut self, root: impl Into<Option<&'a StrongWidget>>, rsc: &mut dyn UiRsc) {
// safety mechanism for memory leaks; might wanna return a result instead so user can
// decide whether to panic or not
if !widgets.waiting.is_empty() {
if !rsc.widgets().waiting.is_empty() {
let widgets = rsc.widgets();
let len = widgets.waiting.len();
let all: Vec<_> = widgets
.waiting
@@ -52,18 +51,169 @@ impl UiRenderState {
weak widgets: {all:#?}"
);
}
if self.root_changed(root) {
Drawer::new(self, events).redraw_all();
self.old_root = root.into().map(|r| r.id());
} else if widgets.has_updates() {
Drawer::new(self, events).redraw_updates();
}
if self.resized {
let root = root.into();
if self.root_changed(root) || self.resized {
self.redraw_all(root, rsc);
self.old_root = root.map(|r| r.id());
self.resized = false;
Drawer::new(self, events).redraw_all();
} else if rsc.widgets().has_updates() {
self.redraw_updates(rsc);
}
}
fn redraw_all(&mut self, root: Option<&StrongWidget>, rsc: &mut dyn UiRsc) {
self.clear(rsc);
// free all resources & cache
if let Some(id) = root {
self.draw_inner(0, id.id(), UiRegion::FULL, None, MaskIdx::NONE, None, rsc);
}
}
// TODO: should prolly make a DrawInfo struct or smth for everything other than rsc
#[allow(clippy::too_many_arguments)]
pub(super) fn draw_inner(
&mut self,
layer: usize,
id: WidgetId,
region: UiRegion,
parent: Option<WidgetId>,
mask: MaskIdx,
old_children: Option<Vec<WidgetId>>,
rsc: &mut dyn UiRsc,
) {
let mut old_children = old_children.unwrap_or_default();
if let Some(active) = self.active.get_mut(&id)
&& !rsc.widgets().needs_redraw.contains(&id)
{
// check to see if we can skip drawing first
if active.region == region {
return;
} else if active.region.size() == region.size() {
// TODO: epsilon?
let from = active.region;
self.mov(id, from, region);
return;
}
// if not, then maintain resize and track old children to remove unneeded
let active = self.remove(id, false, rsc).unwrap();
old_children = active.children;
}
// draw widget
self.draw_started.insert(id);
let mut painter = Painter {
state: self,
region,
mask,
layer,
id,
textures: Vec::new(),
primitives: Vec::new(),
children: Vec::new(),
rsc,
};
let mut widget = painter.rsc.widgets().get_dyn_dynamic(id);
widget.draw(&mut painter);
drop(widget);
let Painter {
state: _,
rsc: _,
region,
mask,
textures,
primitives,
children,
layer,
id,
} = painter;
// add to active
let active = ActiveData {
id,
region,
parent,
textures,
primitives,
children,
mask,
layer,
};
// remove old children that weren't kept
for c in &old_children {
if !active.children.contains(c) {
self.remove_rec(*c, rsc);
}
}
rsc.on_draw(&active);
self.active.insert(id, active);
}
fn mov(&mut self, id: WidgetId, from: UiRegion, to: UiRegion) {
let active = self.active.get_mut(&id).unwrap();
for h in &active.primitives {
let region = self.layers[h.layer].region_mut(h);
*region = region.outside(&from).within(&to);
}
active.region = active.region.outside(&from).within(&to);
// SAFETY: children cannot be recursive
let children = unsafe { forget_ref(&active.children) };
for child in children {
self.mov(*child, from, to);
}
}
/// NOTE: instance textures are cleared and self.textures freed
fn remove(&mut self, id: WidgetId, undraw: bool, rsc: &mut dyn UiRsc) -> Option<ActiveData> {
let mut active = self.active.remove(&id);
if let Some(active) = &mut active {
for h in &active.primitives {
let mask = self.layers.free(h);
if mask != MaskIdx::NONE {
rsc.ui_mut().masks.remove(mask);
}
}
active.textures.clear();
rsc.ui_mut().textures.free();
if undraw {
rsc.on_undraw(active);
}
}
active
}
fn remove_rec(&mut self, id: WidgetId, rsc: &mut dyn UiRsc) -> Option<ActiveData> {
self.cache.remove(id);
let inst = self.remove(id, true, rsc);
if let Some(inst) = &inst {
for c in &inst.children {
self.remove_rec(*c, rsc);
}
}
inst
}
fn clear(&mut self, rsc: &mut dyn UiRsc) {
for (_, active) in self.active.drain() {
rsc.on_undraw(&active);
}
self.cache.clear();
self.layers.clear();
rsc.widgets_mut().needs_redraw.clear();
rsc.free();
}
pub fn redraw_updates(&mut self, rsc: &mut dyn UiRsc) {
while let Some(&id) = rsc.widgets().needs_redraw.iter().next() {
self.redraw(id, rsc);
}
rsc.free();
}
pub fn root_changed<'a>(&self, root: impl Into<Option<&'a StrongWidget>>) -> bool {
root.into().map(|r| r.id()) != self.old_root
}
@@ -103,10 +253,63 @@ impl UiRenderState {
let region = self.active.get(&id.id())?.region;
Some(region.to_px(self.output_size))
}
}
pub trait HasRoot {
fn set_root(&mut self, root: StrongWidget);
/// redraws a widget that's currently active (drawn)
pub fn redraw(&mut self, id: WidgetId, rsc: &mut dyn UiRsc) {
rsc.widgets_mut().needs_redraw.remove(&id);
self.draw_started.remove(&id);
// check if parent depends on the desired size of this, if so then redraw it first
for axis in [Axis::X, Axis::Y] {
if let Some(&(outer, old)) = self.cache.size.axis_dyn(axis).get(&id)
&& let Some(current) = self.active.get(&id)
&& let Some(pid) = current.parent
{
self.cache.size.axis_dyn(axis).remove(&id);
let new = self.size_ctx(id, outer, rsc).len_axis(id, axis);
self.cache.size.axis_dyn(axis).insert(id, (outer, new));
if new != old {
self.redraw(pid, rsc);
}
}
}
if self.draw_started.contains(&id) {
return;
}
let Some(active) = self.remove(id, false, rsc) else {
return;
};
self.draw_inner(
active.layer,
id,
active.region,
active.parent,
active.mask,
Some(active.children),
rsc,
);
}
pub(super) fn size_ctx<'b>(
&'b mut self,
source: WidgetId,
outer: UiVec2,
rsc: &'b mut dyn UiRsc,
) -> SizeCtx<'b> {
let ui = rsc.ui_mut();
SizeCtx {
source,
cache: &mut self.cache,
text: &mut ui.text,
textures: &mut ui.textures,
widgets: &ui.widgets,
outer,
output_size: self.output_size,
id: source,
}
}
}
impl Default for UiRenderState {

View File

@@ -1,4 +1,4 @@
use crate::{HasRoot, UiRsc};
use crate::UiRsc;
use super::*;
use std::marker::Unsize;
@@ -22,15 +22,16 @@ pub trait WidgetLike<Rsc: UiRsc, Tag>: Sized {
}
}
fn set_root(self, rsc: &mut Rsc)
where
Rsc: HasRoot,
{
fn set_root(self, rsc: &mut Rsc, root: &mut impl HasRoot) {
let id = self.add_strong(rsc);
rsc.set_root(id);
root.set_root(id);
}
}
pub trait HasRoot {
fn set_root(&mut self, root: StrongWidget);
}
pub trait WidgetArrLike<Rsc, const LEN: usize, Tag> {
#[track_caller]
fn add(self, state: &mut Rsc) -> WidgetArr<LEN>;

View File

@@ -6,7 +6,9 @@ pub struct WidgetTag;
impl<Rsc: UiRsc, W: Widget> WidgetLike<Rsc, WidgetTag> for W {
type Widget = W;
fn add(self, rsc: &mut Rsc) -> WeakWidget<W> {
rsc.add_widget(self)
let w = rsc.ui_mut().widgets.add_weak(self);
rsc.on_add(w);
w
}
}

View File

@@ -104,10 +104,10 @@ impl Widgets {
self.vec.get_mut(id.id())
}
pub fn free(&mut self) {
for id in self.recv.try_iter() {
self.vec.free(id.id());
}
pub fn free_next(&mut self) -> Option<WidgetId> {
let next = self.recv.try_recv().ok()?;
self.vec.free(next);
Some(next)
}
#[allow(clippy::len_without_is_empty)]