Skip to main content

dream_soft_render/renderer/
frame.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3use super::{
4    MeshRasterContext, SOLID_FAN_POLYGON_SCRATCH_CAPACITY, SoftwareRenderer,
5    rasterize_mesh_contents,
6};
7use crate::geometry::RasterMesh;
8use crate::raster::ClipBounds;
9use crate::surface::SoftwareSurface;
10use crate::texture::{EMPTY_TEXTURE, TextureId, TextureKey};
11use crate::{ClipRect, Color, Error, Rect, Vertex};
12
13/// Triangles to draw with [`Frame::mesh`].
14///
15/// Every three `indices` name one triangle's vertices. The rasterizer reads the slices where they
16/// lie for the duration of the call: nothing is copied, and nothing is kept afterwards.
17#[derive(Clone, Copy, Debug)]
18pub struct Mesh<'a> {
19    /// The vertices.
20    pub vertices: &'a [Vertex],
21    /// Vertex indices, three per triangle.
22    pub indices: &'a [u32],
23    /// The texture sampled at each vertex's `uv`, or `None` to use the vertex colors alone.
24    pub texture: Option<TextureId>,
25}
26
27impl SoftwareRenderer {
28    /// Stores a texture from premultiplied RGBA8 `pixels`, `width * height * 4` bytes, top
29    /// row first.
30    ///
31    /// # Errors
32    ///
33    /// [`Error::TextureSize`] for a zero or overflowing size or a side longer than 65536
34    /// texels, [`Error::PixelDataLength`] if `pixels` is the wrong length,
35    /// [`Error::TextureBudget`] if the renderer's texture storage would exceed
36    /// [`MAX_TEXTURE_BYTES`](crate::MAX_TEXTURE_BYTES), and [`Error::TextureIdsExhausted`] once
37    /// the process has issued every possible handle.
38    pub fn create_texture(
39        &mut self,
40        width: usize,
41        height: usize,
42        pixels: &[u8],
43    ) -> Result<TextureId, Error> {
44        let id = TextureId::issue().ok_or(Error::TextureIdsExhausted)?;
45        self.textures.insert_native(id, width, height, pixels)?;
46        self.forget_last_egui_frame();
47        Ok(id)
48    }
49
50    /// Replaces the `width`x`height` region of `texture` whose top-left texel is (`x`, `y`)
51    /// with premultiplied RGBA8 `pixels`, top row first.
52    ///
53    /// # Errors
54    ///
55    /// [`Error::UnknownTexture`] for a freed or foreign handle, [`Error::PixelDataLength`] if
56    /// `pixels` is the wrong length, and [`Error::TextureUpdateOutOfBounds`] if the region does
57    /// not fit inside the texture.
58    pub fn update_texture(
59        &mut self,
60        texture: TextureId,
61        x: usize,
62        y: usize,
63        width: usize,
64        height: usize,
65        pixels: &[u8],
66    ) -> Result<(), Error> {
67        self.textures
68            .update_native(texture, [x, y], [width, height], pixels)?;
69        self.forget_last_egui_frame();
70        Ok(())
71    }
72
73    /// Releases a texture's storage. The handle is invalid afterwards.
74    ///
75    /// # Errors
76    ///
77    /// [`Error::UnknownTexture`] if the handle was already freed or never belonged to this
78    /// renderer.
79    pub fn free_texture(&mut self, texture: TextureId) -> Result<(), Error> {
80        self.textures.free_native(texture)?;
81        self.forget_last_egui_frame();
82        Ok(())
83    }
84
85    /// Starts drawing into a `width`x`height` surface.
86    ///
87    /// Nothing is cleared implicitly: the surface keeps the previous frame's pixels, unless its
88    /// size changed, in which case it starts transparent black. Call [`Frame::clear`] to set a
89    /// background.
90    ///
91    /// # Errors
92    ///
93    /// [`Error::SurfaceSize`] if the pixel count overflows or exceeds
94    /// [`MAX_SURFACE_PIXELS`](crate::MAX_SURFACE_PIXELS), or either side is longer than 65535
95    /// pixels.
96    pub fn begin_frame(&mut self, width: usize, height: usize) -> Result<Frame<'_>, Error> {
97        let resized = self
98            .surface
99            .resize(width, height)
100            .map_err(|_| Error::SurfaceSize { width, height })?;
101        if resized {
102            self.surface.clear(Color::TRANSPARENT.to_array());
103        }
104        self.forget_last_egui_frame();
105        Ok(Frame { renderer: self })
106    }
107
108    fn rasterize_frame_mesh(
109        &mut self,
110        mesh: RasterMesh<'_>,
111        texture: Option<TextureId>,
112        clip: ClipBounds,
113    ) -> Result<(), Error> {
114        let texture = match texture {
115            None => &EMPTY_TEXTURE,
116            Some(id) => self
117                .textures
118                .get(TextureKey::Native(id))
119                .ok_or(Error::UnknownTexture(id))?,
120        };
121        if clip.is_empty() {
122            return Ok(());
123        }
124        self.solid_fan_polygon_scratch.clear();
125        self.solid_fan_seen_boundary_scratch.clear();
126        let mut context = MeshRasterContext {
127            surface: &mut self.surface,
128            fan_polygon_scratch: &mut self.solid_fan_polygon_scratch,
129            fan_seen_boundary_scratch: &mut self.solid_fan_seen_boundary_scratch,
130            fan_span_cache: &mut self.solid_fan_span_cache,
131            mesh,
132            texture,
133            clip,
134            primitive_index: 0,
135            solid_fan_polygon_scratch_budget: SOLID_FAN_POLYGON_SCRATCH_CAPACITY,
136        };
137        rasterize_mesh_contents(&mut context, &mut None, &mut None, &mut None)?;
138        Ok(())
139    }
140}
141
142/// One frame of drawing into a [`SoftwareRenderer`]'s surface, from
143/// [`SoftwareRenderer::begin_frame`].
144///
145/// Draw calls rasterize immediately, in call order, each blended over what is already there.
146/// See the crate documentation for coordinates, sampling, and blending.
147#[derive(Debug)]
148pub struct Frame<'a> {
149    renderer: &'a mut SoftwareRenderer,
150}
151
152impl Frame<'_> {
153    /// Surface width in pixels.
154    #[must_use]
155    pub const fn width(&self) -> usize {
156        self.renderer.surface.width
157    }
158
159    /// Surface height in pixels.
160    #[must_use]
161    pub const fn height(&self) -> usize {
162        self.renderer.surface.height
163    }
164
165    /// The pixels drawn so far.
166    #[must_use]
167    pub const fn surface(&self) -> &SoftwareSurface {
168        &self.renderer.surface
169    }
170
171    /// Overwrites every pixel with `color`, without blending.
172    pub fn clear(&mut self, color: Color) {
173        self.renderer.surface.clear(color.to_array());
174    }
175
176    /// Blends a solid rectangle over the surface.
177    ///
178    /// A pixel is covered when its center lies in `rect`: `min < center <= max` on each axis.
179    /// A rectangle with `max <= min` on either axis covers nothing.
180    ///
181    /// # Errors
182    ///
183    /// [`Error::NonFiniteRect`] if a coordinate is NaN or infinite.
184    pub fn fill_rect(&mut self, rect: Rect, color: Color, clip: ClipRect) -> Result<(), Error> {
185        self.rect(rect, Rect::FULL_UV, None, color, clip)
186    }
187
188    /// Blends `texture` over `rect`, mapping `uv.min` to the rectangle's top-left corner and
189    /// `uv.max` to its bottom-right, each texel multiplied by the premultiplied `tint`
190    /// ([`Color::WHITE`] leaves it unchanged). Coverage is as in [`Frame::fill_rect`].
191    ///
192    /// # Errors
193    ///
194    /// [`Error::NonFiniteRect`] for a NaN or infinite coordinate in `rect` or `uv`, and
195    /// [`Error::UnknownTexture`] for a freed or foreign texture.
196    pub fn textured_rect(
197        &mut self,
198        rect: Rect,
199        uv: Rect,
200        texture: TextureId,
201        tint: Color,
202        clip: ClipRect,
203    ) -> Result<(), Error> {
204        self.rect(rect, uv, Some(texture), tint, clip)
205    }
206
207    // Rectangles are drawn as egui lays them out (`tl, tr, bl, br` as `(0, 1, 2), (2, 1, 3)`),
208    // which the rasterizer recognizes as a rectangle before any per-triangle work, so a
209    // rectangle drawn here and the same rectangle from egui produce identical pixels.
210    fn rect(
211        &mut self,
212        rect: Rect,
213        uv: Rect,
214        texture: Option<TextureId>,
215        color: Color,
216        clip: ClipRect,
217    ) -> Result<(), Error> {
218        if !rect.is_finite() || !uv.is_finite() {
219            return Err(Error::NonFiniteRect);
220        }
221        if rect.max[0] <= rect.min[0] || rect.max[1] <= rect.min[1] {
222            if let Some(texture) = texture {
223                self.check_texture(texture)?;
224            }
225            return Ok(());
226        }
227        let corner = |x: usize, y: usize| {
228            Vertex::new(
229                [[rect.min[0], rect.max[0]][x], [rect.min[1], rect.max[1]][y]],
230                [[uv.min[0], uv.max[0]][x], [uv.min[1], uv.max[1]][y]],
231                color,
232            )
233        };
234        let vertices = [corner(0, 0), corner(1, 0), corner(0, 1), corner(1, 1)];
235        self.mesh(
236            Mesh {
237                vertices: &vertices,
238                indices: &[0, 1, 2, 2, 1, 3],
239                texture,
240            },
241            clip,
242        )
243    }
244
245    /// Blends a triangle mesh over the surface.
246    ///
247    /// A pixel is covered when its center falls inside a triangle. Centers exactly on an edge
248    /// go to one side by a fixed tie-break, so triangles sharing an edge never both blend a
249    /// pixel on it. Colors interpolate across each triangle; texels are sampled
250    /// nearest-neighbor.
251    ///
252    /// # Errors
253    ///
254    /// [`Error::IndexCount`] if the index count is not a multiple of three,
255    /// [`Error::IndexOutOfRange`] for an index past the vertices,
256    /// [`Error::NonFiniteVertex`] for a NaN or infinite position or texture coordinate on any
257    /// vertex, referenced or not, and [`Error::UnknownTexture`] for a freed or foreign texture.
258    pub fn mesh(&mut self, mesh: Mesh<'_>, clip: ClipRect) -> Result<(), Error> {
259        if !mesh.indices.len().is_multiple_of(3) {
260            return Err(Error::IndexCount(mesh.indices.len()));
261        }
262        let vertex_count = mesh.vertices.len();
263        if let Some(&index) = mesh
264            .indices
265            .iter()
266            .find(|&&index| usize::try_from(index).is_ok_and(|index| index >= vertex_count))
267        {
268            return Err(Error::IndexOutOfRange {
269                index,
270                vertex_count,
271            });
272        }
273        if let Some((index, field)) = mesh
274            .vertices
275            .iter()
276            .enumerate()
277            .find_map(|(index, vertex)| Some((index, vertex.non_finite_field()?)))
278        {
279            return Err(Error::NonFiniteVertex { index, field });
280        }
281        // The draw below looks the texture up once and fails before writing a pixel.
282        let renderer = &mut *self.renderer;
283        let clip = clip.to_bounds(renderer.surface.width, renderer.surface.height);
284        renderer.rasterize_frame_mesh(
285            RasterMesh {
286                vertices: mesh.vertices,
287                indices: mesh.indices,
288            },
289            mesh.texture,
290            clip,
291        )
292    }
293
294    fn check_texture(&self, texture: TextureId) -> Result<(), Error> {
295        if self
296            .renderer
297            .textures
298            .get(TextureKey::Native(texture))
299            .is_some()
300        {
301            Ok(())
302        } else {
303            Err(Error::UnknownTexture(texture))
304        }
305    }
306}
307
308// Compares Frame::mesh against the egui mesh path.
309#[cfg(all(test, feature = "egui"))]
310mod tests {
311    use super::*;
312
313    fn gradient_vertex(x: f32, y: f32, u: f32, v: f32, alpha: u8) -> Vertex {
314        Vertex::new(
315            [x, y],
316            [u, v],
317            Color::from_rgba_unmultiplied(200, 120, 40, alpha),
318        )
319    }
320
321    #[test]
322    fn frame_meshes_match_the_egui_mesh_path() {
323        let vertices = [
324            gradient_vertex(3.25, 2.5, 0.0, 0.0, 255),
325            gradient_vertex(40.0, 4.0, 1.0, 0.0, 180),
326            gradient_vertex(6.0, 28.75, 0.0, 1.0, 90),
327            gradient_vertex(44.5, 30.0, 1.0, 1.0, 20),
328            gradient_vertex(10.0, 10.0, 0.0, 0.0, 255),
329            gradient_vertex(30.0, 10.0, 1.0, 0.0, 255),
330            gradient_vertex(10.0, 20.0, 0.0, 1.0, 255),
331            gradient_vertex(30.0, 20.0, 1.0, 1.0, 255),
332        ];
333        let indices = [0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7];
334        let texels: Vec<u8> = (0..8 * 8)
335            .flat_map(|texel: u8| {
336                Color::from_rgba_unmultiplied(texel * 4, 255 - texel * 4, 90, texel * 4).to_array()
337            })
338            .collect();
339
340        for texture in [false, true] {
341            let mut generic = SoftwareRenderer::default();
342            let mut via_egui = SoftwareRenderer::default();
343            let generic_texture = generic.create_texture(8, 8, &texels).expect("texture");
344            let egui_texture = via_egui.create_texture(8, 8, &texels).expect("texture");
345            let clip = ClipRect::new(2, 1, 40, 29);
346
347            let mut frame = generic.begin_frame(48, 32).expect("frame");
348            frame.clear(Color::from_rgb(17, 20, 28));
349            frame
350                .mesh(
351                    Mesh {
352                        vertices: &vertices,
353                        indices: &indices,
354                        texture: texture.then_some(generic_texture),
355                    },
356                    clip,
357                )
358                .expect("mesh");
359
360            via_egui
361                .begin_frame(48, 32)
362                .expect("frame")
363                .clear(Color::from_rgb(17, 20, 28));
364            let mesh = egui::Mesh {
365                indices: indices.to_vec(),
366                vertices: vertices.iter().map(|vertex| vertex.to_egui()).collect(),
367                texture_id: if texture {
368                    egui_texture.to_egui()
369                } else {
370                    // The egui path samples egui's font atlas white texel for untextured shapes;
371                    // an opaque white 1x1 texture stands in for it.
372                    let white = via_egui.create_texture(1, 1, &[255; 4]).expect("white");
373                    white.to_egui()
374                },
375            };
376            via_egui
377                .rasterize(
378                    &[egui::ClippedPrimitive {
379                        clip_rect: egui::Rect::from_min_max(
380                            egui::pos2(2.0, 1.0),
381                            egui::pos2(40.0, 29.0),
382                        ),
383                        primitive: egui::epaint::Primitive::Mesh(mesh),
384                    }],
385                    None,
386                    None,
387                    None,
388                )
389                .expect("egui mesh");
390
391            assert_eq!(
392                generic.surface.pixels, via_egui.surface.pixels,
393                "textured={texture}"
394            );
395        }
396    }
397}