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(|rewrite| rewrite.take_storage())
218            .unwrap_or_default();
219        self.fill_raster_scene(&mut raster, scale, picture.raster.as_ref());
220        changed.clear();
221        match picture.raster.as_ref() {
222            Some(old)
223                if (picture.width, picture.height, picture.scale) == (width, height, scale) =>
224            {
225                damage::changed_areas(
226                    old,
227                    &picture.reach,
228                    &raster,
229                    picture.frame(),
230                    &mut picture.changed,
231                );
232                if let Some(mut updated) = updated {
233                    picture.changed.append(&mut updated);
234                    damage::merge_areas(&mut picture.changed);
235                }
236                changed.extend(picture.changed.iter().copied().map(pixel_rect));
237            }
238            _ if width > 0 && height > 0 => changed.push(PixelRect {
239                x: 0,
240                y: 0,
241                width,
242                height,
243            }),
244            _ => {}
245        }
246        picture.raster = Some(raster);
247        picture.width = width;
248        picture.height = height;
249        picture.scale = scale;
250        picture.measure_reach();
251        if cranpose_ui::current_memory_headroom() == MemoryHeadroom::Tight {
252            growth_trim::trim(picture);
253        }
254    }
255
256    // Brings `picture`'s scene up to the current scene in place, and puts
257    // the areas the changed layers changed into `picture.changed`. `None`
258    // when the scene must be built again: the first time, after a change of
259    // size, scale or light, or of the root layer, when the picture holds
260    // another scene than the one before the store's last update, or when a
261    // layer's records no longer lie in one run, with the areas the update
262    // changed before it stopped in `picture.changed`.
263    fn update_picture_in_place(
264        &self,
265        picture: &mut Picture,
266        width: u32,
267        height: u32,
268        scale: f32,
269    ) -> Option<pipeline::UpdatedReach> {
270        picture.changed.clear();
271        let (Some(raster), Some(_)) = (picture.raster.as_mut(), self.scene.root_layer()) else {
272            return None;
273        };
274        if (picture.width, picture.height, picture.scale) != (width, height, scale) {
275            return None;
276        }
277        let store = self.scene.store();
278        let synced = picture.synced?;
279        let changed = pipeline::Changed {
280            store,
281            records: store.stamps_since(Some(synced))?,
282            updates: store.update().since(synced.update()),
283        };
284        let window = draw::ClipBounds {
285            min_x: 0,
286            min_y: 0,
287            max_x: i32::try_from(width).unwrap_or(i32::MAX),
288            max_y: i32::try_from(height).unwrap_or(i32::MAX),
289        };
290        pipeline::InPlaceUpdate {
291            scene: raster,
292            reach: &mut picture.reach,
293            rewrite: &mut picture.rewrite,
294            roots: &mut picture.roots,
295        }
296        .run(
297            changed,
298            self.scene.diagnostics(),
299            scale,
300            &self.text,
301            window,
302            &mut picture.changed,
303        )
304    }
305
306    /// Rasterizes the glyphs of the text in `area` of `picture` into the
307    /// renderer's glyph cache, so that drawing the area later takes them from
308    /// it. A host calls it while it waits anyway, such as for a display that
309    /// is still starting up.
310    pub fn prepare_picture_area(&self, picture: &Picture, area: PixelRect) {
311        let Some(raster) = picture.raster.as_ref() else {
312            return;
313        };
314        let window = draw::ClipBounds {
315            min_x: i32::try_from(area.x).unwrap_or(i32::MAX),
316            min_y: i32::try_from(area.y).unwrap_or(i32::MAX),
317            max_x: i32::try_from(area.x.saturating_add(area.width)).unwrap_or(i32::MAX),
318            max_y: i32::try_from(area.y.saturating_add(area.height)).unwrap_or(i32::MAX),
319        };
320        draw::prepare_raster_window(raster, window, &self.text);
321    }
322
323    /// Draws `area` of `picture` into `pixels` as straight-alpha RGBA8 rows of
324    /// `area.width` pixels, `area.height` of them. Draws nothing before the
325    /// first [`Self::update_picture`] or when `pixels` is shorter than the area.
326    pub fn draw_picture_area(&self, picture: &Picture, area: PixelRect, pixels: &mut [u8]) {
327        self.draw_picture_area_as(picture, area, pixels.as_chunks_mut::<4>().0);
328    }
329
330    /// Draws `area` of `picture` into `pixels` as rows of 16-bit pixels, 5
331    /// bits of red, 6 of green and 5 of blue, stored in `order`, as a display
332    /// takes them: `area.width` pixels a row, `area.height` rows. Each pixel
333    /// keeps the high bits of the bytes [`Self::draw_picture_area`] draws,
334    /// except where a drawing blends over another, which blends over the
335    /// 16-bit pixel.
336    pub fn draw_picture_area_rgb565(
337        &self,
338        picture: &Picture,
339        area: PixelRect,
340        pixels: &mut [u16],
341        order: Rgb565Order,
342    ) {
343        match order {
344            Rgb565Order::LittleEndian => self.draw_picture_area_as::<Rgb565Le>(
345                picture,
346                area,
347                bytemuck::cast_slice_mut(pixels),
348            ),
349            Rgb565Order::BigEndian => self.draw_picture_area_as::<Rgb565Be>(
350                picture,
351                area,
352                bytemuck::cast_slice_mut(pixels),
353            ),
354        }
355    }
356
357    // Out of line, one function a format: a display takes one byte order, and
358    // a build that keeps its drawing in fast memory keeps only that one.
359    #[inline(never)]
360    fn draw_picture_area_as<P: Pixel>(&self, picture: &Picture, area: PixelRect, pixels: &mut [P]) {
361        let Some(raster) = picture.raster.as_ref() else {
362            return;
363        };
364        let len = area.width as usize * area.height as usize;
365        let Some(pixels) = pixels.get_mut(..len) else {
366            return;
367        };
368        let mut target = draw::Target {
369            pixels,
370            left: i32::try_from(area.x).unwrap_or(i32::MAX),
371            top: i32::try_from(area.y).unwrap_or(i32::MAX),
372            width: area.width,
373            height: area.height,
374        };
375        draw::draw_raster_window(
376            &mut target,
377            raster,
378            &picture.reach,
379            self.scene.diagnostics(),
380            &self.text,
381        );
382    }
383
384    /// The scene at `scale` device pixels per point as sprites for a GPU
385    /// compositor, into `frame`, which keeps its textures from the frames
386    /// before. Invalid scales use 1.0.
387    pub fn compose_sprites(
388        &self,
389        frame: &mut sprites::SpriteFrame,
390        width: u32,
391        height: u32,
392        scale: f32,
393    ) {
394        let mut scene = std::mem::take(&mut frame.scene);
395        self.fill_raster_scene(&mut scene, valid_scale(scale), None);
396        frame.compose(&scene, width, height, self.scene.diagnostics(), &self.text);
397        frame.scene = scene;
398    }
399}
400
401impl Picture {
402    fn frame(&self) -> draw::ClipBounds {
403        draw::ClipBounds {
404            min_x: 0,
405            min_y: 0,
406            max_x: i32::try_from(self.width).unwrap_or(i32::MAX),
407            max_y: i32::try_from(self.height).unwrap_or(i32::MAX),
408        }
409    }
410
411    fn measure_reach(&mut self) {
412        let frame = self.frame();
413        match self.raster.as_ref() {
414            Some(raster) => raster.reach_into(frame, &mut self.reach),
415            None => self.reach.clear(),
416        }
417    }
418}
419
420impl Renderer for PixelsRenderer {
421    type Scene = Scene;
422    type Error = std::convert::Infallible;
423
424    fn attach_app_context_services(&mut self, app_context: &cranpose_ui::AppContext) {
425        app_context.set_text_fonts(self.text.fonts.resolver());
426        self.app_context = Some(app_context.downgrade());
427    }
428
429    #[cfg(feature = "installed-fonts")]
430    fn apply_installed_fonts(&mut self, app_context: &cranpose_ui::AppContext) {
431        let Some(fonts) = self.text.fonts.with_installed_faces() else {
432            return;
433        };
434        self.text = draw::TextRaster::new(fonts);
435        let attached = self
436            .app_context
437            .as_ref()
438            .and_then(std::rc::Weak::upgrade)
439            .is_some_and(|attached| std::ptr::eq(&*attached, app_context));
440        if attached {
441            self.attach_app_context_services(app_context);
442        }
443    }
444
445    fn scene(&self) -> &Self::Scene {
446        &self.scene
447    }
448
449    fn scene_mut(&mut self) -> &mut Self::Scene {
450        &mut self.scene
451    }
452
453    fn rebuild_scene_from_applier(
454        &mut self,
455        applier: &mut cranpose_core::MemoryApplier,
456        root: cranpose_core::NodeId,
457        _viewport: Size,
458    ) -> Result<(), Self::Error> {
459        self.scene.rebuild_from_applier(applier, root);
460        Ok(())
461    }
462
463    fn update_scene_from_applier(
464        &mut self,
465        applier: &mut cranpose_core::MemoryApplier,
466        root: cranpose_core::NodeId,
467        _viewport: Size,
468        updates: SceneUpdates<'_>,
469    ) -> Result<(), Self::Error> {
470        self.scene.update_from_applier(applier, root, updates);
471        Ok(())
472    }
473}