Skip to main content

cranpose_render_pixels/
lib.rs

1#![deny(missing_docs)]
2#![doc = include_str!("../README.md")]
3
4mod damage;
5mod draw;
6mod frame;
7mod growth_trim;
8mod pipeline;
9mod pixel;
10mod rewrite;
11/// The retained scene and hit regions of the pixel renderer.
12pub mod scene;
13mod scene_item;
14mod shift;
15pub mod sprites;
16mod style;
17mod surface;
18#[cfg(test)]
19#[path = "tests/text_draws.rs"]
20mod text_draws;
21
22pub use cranpose_render_common::rgb565::Rgb565Order;
23use cranpose_render_common::{
24    Renderer, SceneUpdates,
25    rgb565::{Rgb565Be, Rgb565Le},
26    scene_store::{RecordEvents, SceneVersion},
27    text_fonts::TextFonts,
28};
29use cranpose_ui_graphics::{MemoryHeadroom, Size};
30pub use draw::draw_scene;
31use pixel::Pixel;
32pub use scene::{HitRegion, Scene};
33
34/// A rectangle of device pixels: columns `x..x + width` of rows
35/// `y..y + height`.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct PixelRect {
38    /// The first column.
39    pub x: u32,
40    /// The first row.
41    pub y: u32,
42    /// The number of columns.
43    pub width: u32,
44    /// The number of rows.
45    pub height: u32,
46}
47
48fn pixel_rect(bounds: draw::ClipBounds) -> PixelRect {
49    PixelRect {
50        x: bounds.min_x.max(0) as u32,
51        y: bounds.min_y.max(0) as u32,
52        width: (bounds.max_x - bounds.min_x).max(0) as u32,
53        height: (bounds.max_y - bounds.min_y).max(0) as u32,
54    }
55}
56
57/// The picture a host drew last. [`PixelsRenderer::update_picture`] moves it
58/// to the current scene and finds the pixels that change, and
59/// [`PixelsRenderer::draw_picture_area`] draws any part of it.
60#[derive(Default)]
61pub struct Picture {
62    raster: Option<scene::RasterScene>,
63    /// What an update in place pushes each changed layer again with.
64    rewrite: Option<Box<rewrite::Rewrite>>,
65    width: u32,
66    height: u32,
67    scale: f32,
68    changed: Vec<draw::ClipBounds>,
69    // Where each item of `raster` can draw in the frame, in its order: each
70    // strip a host draws passes over the items that miss it.
71    reach: Vec<Option<draw::ClipBounds>>,
72    // The version of the store the scene was brought up to.
73    synced: Option<SceneVersion>,
74    // The subtrees an update in place pushes again, kept for its room.
75    roots: Vec<pipeline::PushRoot>,
76}
77
78fn valid_scale(scale: f32) -> f32 {
79    if scale.is_finite() && scale > 0.0 {
80        scale
81    } else {
82        1.0
83    }
84}
85
86/// A renderer that draws the scene into a caller-owned RGBA pixel buffer on the CPU.
87pub struct PixelsRenderer {
88    scene: Scene,
89    text: draw::TextRaster,
90    /// The app context this renderer gave its text measurer.
91    app_context: Option<std::rc::Weak<cranpose_ui::AppContext>>,
92}
93
94impl Default for PixelsRenderer {
95    fn default() -> Self {
96        Self::new()
97    }
98}
99
100impl PixelsRenderer {
101    /// Creates a renderer that draws text in the embedded default font when the
102    /// `embedded-default-font` feature is on, and draws no text otherwise.
103    pub fn new() -> Self {
104        Self::with_fonts(&[])
105    }
106
107    /// A renderer that draws text in `fonts`. With none that parses, it uses
108    /// the embedded default font when the `embedded-default-font` feature is
109    /// on, and draws no text otherwise.
110    pub fn with_fonts(fonts: &[&'static [u8]]) -> Self {
111        let mut scene = Scene::new();
112        scene.follow(RecordEvents::STAMPS);
113        Self {
114            scene,
115            text: draw::TextRaster::new(TextFonts::from_fonts_or_default(fonts)),
116            app_context: None,
117        }
118    }
119
120    /// Draws the scene into `frame`, an RGBA8 buffer of `width` by `height` pixels, at one device
121    /// pixel per logical pixel.
122    pub fn draw(&self, frame: &mut [u8], width: u32, height: u32) {
123        draw::draw_scene_scaled(frame, width, height, &self.scene, &self.text, 1.0);
124    }
125
126    /// Rasterizes logical scene coordinates at `scale` device pixels per point.
127    /// Hit regions stay in logical coordinates. Invalid scales use 1.0.
128    pub fn draw_scaled(&self, frame: &mut [u8], width: u32, height: u32, scale: f32) {
129        draw::draw_scene_scaled(
130            frame,
131            width,
132            height,
133            &self.scene,
134            &self.text,
135            valid_scale(scale),
136        );
137    }
138
139    /// Fills `raster` with the scene at `scale`, keeping its storage, and
140    /// copying from `previous`, the frame before's, what did not change.
141    fn fill_raster_scene(
142        &self,
143        raster: &mut scene::RasterScene,
144        scale: f32,
145        previous: Option<&scene::RasterScene>,
146    ) {
147        if self.scene.root_layer().is_some() {
148            pipeline::fill_raster_scene(
149                raster,
150                self.scene.store(),
151                self.scene.diagnostics(),
152                scale,
153                previous,
154                &self.text,
155            );
156        } else {
157            raster.clear();
158        }
159    }
160
161    /// Moves `picture` to the current scene, drawn `width` by `height` device
162    /// pixels at `scale` device pixels per point, and puts into `changed` the
163    /// areas whose pixels differ from the picture it held: the whole frame the
164    /// first time and after a change of size or scale. Invalid scales use 1.0.
165    pub fn update_picture(
166        &self,
167        picture: &mut Picture,
168        width: u32,
169        height: u32,
170        scale: f32,
171        changed: &mut Vec<PixelRect>,
172    ) {
173        let scale = valid_scale(scale);
174        let store = self.scene.store();
175        let now = Some(store.version());
176        if let Some(reach) = self.update_picture_in_place(picture, width, height, scale) {
177            picture.synced = now;
178            changed.clear();
179            changed.extend(picture.changed.iter().copied().map(pixel_rect));
180            match reach {
181                pipeline::UpdatedReach::Held => {}
182                pipeline::UpdatedReach::Lost => picture.measure_reach(),
183            }
184            // With little memory left, the spill an update took for a
185            // subtree that pushed other items than before goes, and so does
186            // the room the scene's lists grew past their items.
187            if cranpose_ui::current_memory_headroom() == MemoryHeadroom::Tight {
188                if let Some(rewrite) = picture.rewrite.as_mut() {
189                    rewrite.release_spill();
190                }
191                growth_trim::trim(picture);
192            }
193            return;
194        }
195        self.redraw_picture(picture, width, height, scale, changed);
196        picture.synced = now;
197    }
198
199    // Builds `picture`'s scene again and puts into `changed` the areas that
200    // differ from the scene before. Out of line: most frames update the
201    // scene in place.
202    #[inline(never)]
203    fn redraw_picture(
204        &self,
205        picture: &mut Picture,
206        width: u32,
207        height: u32,
208        scale: f32,
209        changed: &mut Vec<PixelRect>,
210    ) {
211        // An update in place that gave up after it changed part of the scene
212        // left the areas it changed: the scene holds those changes already.
213        let updated = (!picture.changed.is_empty()).then(|| std::mem::take(&mut picture.changed));
214        let mut raster = picture
215            .rewrite
216            .as_mut()
217            .map_or_default(|rewrite| rewrite.take_storage());
218        self.fill_raster_scene(&mut raster, scale, picture.raster.as_ref());
219        changed.clear();
220        match picture.raster.as_ref() {
221            Some(old)
222                if (picture.width, picture.height, picture.scale) == (width, height, scale) =>
223            {
224                damage::changed_areas(
225                    old,
226                    &picture.reach,
227                    &raster,
228                    picture.frame(),
229                    &mut picture.changed,
230                );
231                if let Some(mut updated) = updated {
232                    picture.changed.append(&mut updated);
233                    damage::merge_areas(&mut picture.changed);
234                }
235                changed.extend(picture.changed.iter().copied().map(pixel_rect));
236            }
237            _ if width > 0 && height > 0 => changed.push(PixelRect {
238                x: 0,
239                y: 0,
240                width,
241                height,
242            }),
243            _ => {}
244        }
245        picture.raster = Some(raster);
246        picture.width = width;
247        picture.height = height;
248        picture.scale = scale;
249        picture.measure_reach();
250        if cranpose_ui::current_memory_headroom() == MemoryHeadroom::Tight {
251            growth_trim::trim(picture);
252        }
253    }
254
255    // Brings `picture`'s scene up to the current scene in place, and puts
256    // the areas the changed layers changed into `picture.changed`. `None`
257    // when the scene must be built again: the first time, after a change of
258    // size, scale or light, or of the root layer, when the picture holds
259    // another scene than the one before the store's last update, or when a
260    // layer's records no longer lie in one run, with the areas the update
261    // changed before it stopped in `picture.changed`.
262    fn update_picture_in_place(
263        &self,
264        picture: &mut Picture,
265        width: u32,
266        height: u32,
267        scale: f32,
268    ) -> Option<pipeline::UpdatedReach> {
269        picture.changed.clear();
270        let (Some(raster), Some(_)) = (picture.raster.as_mut(), self.scene.root_layer()) else {
271            return None;
272        };
273        if (picture.width, picture.height, picture.scale) != (width, height, scale) {
274            return None;
275        }
276        let store = self.scene.store();
277        let synced = picture.synced?;
278        let changed = pipeline::Changed {
279            store,
280            records: store.stamps_since(Some(synced))?,
281            updates: store.update().since(synced.update()),
282        };
283        let window = draw::ClipBounds {
284            min_x: 0,
285            min_y: 0,
286            max_x: i32::try_from(width).unwrap_or(i32::MAX),
287            max_y: i32::try_from(height).unwrap_or(i32::MAX),
288        };
289        pipeline::InPlaceUpdate {
290            scene: raster,
291            reach: &mut picture.reach,
292            rewrite: &mut picture.rewrite,
293            roots: &mut picture.roots,
294        }
295        .run(
296            changed,
297            self.scene.diagnostics(),
298            scale,
299            &self.text,
300            window,
301            &mut picture.changed,
302        )
303    }
304
305    /// Rasterizes the glyphs of the text in `area` of `picture` into the
306    /// renderer's glyph cache, so that drawing the area later takes them from
307    /// it. A host calls it while it waits anyway, such as for a display that
308    /// is still starting up.
309    pub fn prepare_picture_area(&self, picture: &Picture, area: PixelRect) {
310        let Some(raster) = picture.raster.as_ref() else {
311            return;
312        };
313        let window = draw::ClipBounds {
314            min_x: i32::try_from(area.x).unwrap_or(i32::MAX),
315            min_y: i32::try_from(area.y).unwrap_or(i32::MAX),
316            max_x: i32::try_from(area.x.saturating_add(area.width)).unwrap_or(i32::MAX),
317            max_y: i32::try_from(area.y.saturating_add(area.height)).unwrap_or(i32::MAX),
318        };
319        draw::prepare_raster_window(raster, window, &self.text);
320    }
321
322    /// Draws `area` of `picture` into `pixels` as straight-alpha RGBA8 rows of
323    /// `area.width` pixels, `area.height` of them. Draws nothing before the
324    /// first [`Self::update_picture`] or when `pixels` is shorter than the area.
325    pub fn draw_picture_area(&self, picture: &Picture, area: PixelRect, pixels: &mut [u8]) {
326        self.draw_picture_area_as(picture, area, pixels.as_chunks_mut::<4>().0);
327    }
328
329    /// Draws `area` of `picture` into `pixels` as rows of 16-bit pixels, 5
330    /// bits of red, 6 of green and 5 of blue, stored in `order`, as a display
331    /// takes them: `area.width` pixels a row, `area.height` rows. Each pixel
332    /// keeps the high bits of the bytes [`Self::draw_picture_area`] draws,
333    /// except where a drawing blends over another, which blends over the
334    /// 16-bit pixel.
335    pub fn draw_picture_area_rgb565(
336        &self,
337        picture: &Picture,
338        area: PixelRect,
339        pixels: &mut [u16],
340        order: Rgb565Order,
341    ) {
342        match order {
343            Rgb565Order::LittleEndian => self.draw_picture_area_as::<Rgb565Le>(
344                picture,
345                area,
346                bytemuck::cast_slice_mut(pixels),
347            ),
348            Rgb565Order::BigEndian => self.draw_picture_area_as::<Rgb565Be>(
349                picture,
350                area,
351                bytemuck::cast_slice_mut(pixels),
352            ),
353        }
354    }
355
356    // Out of line, one function a format: a display takes one byte order, and
357    // a build that keeps its drawing in fast memory keeps only that one.
358    #[inline(never)]
359    fn draw_picture_area_as<P: Pixel>(&self, picture: &Picture, area: PixelRect, pixels: &mut [P]) {
360        let Some(raster) = picture.raster.as_ref() else {
361            return;
362        };
363        let len = area.width as usize * area.height as usize;
364        let Some(pixels) = pixels.get_mut(..len) else {
365            return;
366        };
367        let mut target = draw::Target {
368            pixels,
369            left: i32::try_from(area.x).unwrap_or(i32::MAX),
370            top: i32::try_from(area.y).unwrap_or(i32::MAX),
371            width: area.width,
372            height: area.height,
373        };
374        draw::draw_raster_window(
375            &mut target,
376            raster,
377            &picture.reach,
378            self.scene.diagnostics(),
379            &self.text,
380        );
381    }
382
383    /// The scene at `scale` device pixels per point as sprites for a GPU
384    /// compositor, into `frame`, which keeps its textures from the frames
385    /// before. Invalid scales use 1.0.
386    pub fn compose_sprites(
387        &self,
388        frame: &mut sprites::SpriteFrame,
389        width: u32,
390        height: u32,
391        scale: f32,
392    ) {
393        let mut scene = std::mem::take(&mut frame.scene);
394        self.fill_raster_scene(&mut scene, valid_scale(scale), None);
395        frame.compose(&scene, width, height, self.scene.diagnostics(), &self.text);
396        frame.scene = scene;
397    }
398}
399
400impl Picture {
401    fn frame(&self) -> draw::ClipBounds {
402        draw::ClipBounds {
403            min_x: 0,
404            min_y: 0,
405            max_x: i32::try_from(self.width).unwrap_or(i32::MAX),
406            max_y: i32::try_from(self.height).unwrap_or(i32::MAX),
407        }
408    }
409
410    fn measure_reach(&mut self) {
411        let frame = self.frame();
412        match self.raster.as_ref() {
413            Some(raster) => raster.reach_into(frame, &mut self.reach),
414            None => self.reach.clear(),
415        }
416    }
417}
418
419impl Renderer for PixelsRenderer {
420    type Scene = Scene;
421    type Error = std::convert::Infallible;
422
423    fn attach_app_context_services(&mut self, app_context: &cranpose_ui::AppContext) {
424        app_context.set_text_fonts(self.text.fonts.resolver());
425        self.app_context = Some(app_context.downgrade());
426    }
427
428    #[cfg(feature = "installed-fonts")]
429    fn apply_installed_fonts(&mut self, app_context: &cranpose_ui::AppContext) {
430        let Some(fonts) = self.text.fonts.with_installed_faces() else {
431            return;
432        };
433        self.text = draw::TextRaster::new(fonts);
434        let attached = self
435            .app_context
436            .as_ref()
437            .and_then(std::rc::Weak::upgrade)
438            .is_some_and(|attached| std::ptr::eq(&*attached, app_context));
439        if attached {
440            self.attach_app_context_services(app_context);
441        }
442    }
443
444    fn scene(&self) -> &Self::Scene {
445        &self.scene
446    }
447
448    fn scene_mut(&mut self) -> &mut Self::Scene {
449        &mut self.scene
450    }
451
452    fn rebuild_scene_from_applier(
453        &mut self,
454        applier: &mut cranpose_core::MemoryApplier,
455        root: cranpose_core::NodeId,
456        _viewport: Size,
457    ) -> Result<(), Self::Error> {
458        self.scene.rebuild_from_applier(applier, root);
459        Ok(())
460    }
461
462    fn update_scene_from_applier(
463        &mut self,
464        applier: &mut cranpose_core::MemoryApplier,
465        root: cranpose_core::NodeId,
466        _viewport: Size,
467        updates: SceneUpdates<'_>,
468    ) -> Result<(), Self::Error> {
469        self.scene.update_from_applier(applier, root, updates);
470        Ok(())
471    }
472}