Skip to main content

dream_soft_render/
renderer.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3use crate::Vertex;
4use crate::geometry::RasterMesh;
5use std::io;
6use std::time::Instant;
7
8#[cfg(feature = "egui")]
9mod egui_frame;
10mod fan;
11mod frame;
12mod quad;
13mod stats;
14
15#[cfg(feature = "egui")]
16pub use egui_frame::{RenderFrame, RenderOutcome, RenderTimings, TextureEvidence};
17pub use frame::{Frame, Mesh};
18
19use super::raster::{
20    ClipBounds, RasterStats, SolidFanRasterParams, SolidFanSpanCache, classify_triangle,
21    polygon_raster_bounds, rasterize_solid_fan_with_cache, rasterize_triangle,
22};
23use super::surface::SoftwareSurface;
24use super::texture::{TextureImage, TextureStore};
25use fan::{
26    FanBoundaryKey, SOLID_FAN_MIN_TRIANGLES, SolidFanPolygonScratch, SolidFanRun, solid_fan_run,
27};
28use quad::try_rasterize_quad_window;
29use stats::{
30    PrimitiveStats, RasterTimings, SolidFanRasterRecord, SolidFanRasterWork, TriangleSource,
31};
32
33/// A CPU rasterizer that owns an RGBA8 [`SoftwareSurface`] and a texture store.
34///
35/// Draw with [`SoftwareRenderer::begin_frame`], or, with the `egui` feature, run egui frames
36/// through `SoftwareRenderer::render_egui`. Both write the same surface.
37#[derive(Debug)]
38pub struct SoftwareRenderer {
39    surface: SoftwareSurface,
40    textures: TextureStore,
41    solid_fan_polygon_scratch: Vec<usize>,
42    solid_fan_seen_boundary_scratch: Vec<FanBoundaryKey>,
43    solid_fan_span_cache: SolidFanSpanCache,
44    #[cfg(feature = "egui")]
45    skip_unchanged_frames: bool,
46    // Primitives last rasterized into `surface`, valid only while `previous_frame_valid`.
47    #[cfg(feature = "egui")]
48    previous_primitives: Vec<egui::ClippedPrimitive>,
49    #[cfg(feature = "egui")]
50    previous_frame_valid: bool,
51}
52
53const SOLID_FAN_POLYGON_SCRATCH_CAPACITY: usize = 4096;
54
55impl Default for SoftwareRenderer {
56    fn default() -> Self {
57        Self {
58            surface: SoftwareSurface::default(),
59            textures: TextureStore::default(),
60            solid_fan_polygon_scratch: Vec::with_capacity(SOLID_FAN_POLYGON_SCRATCH_CAPACITY),
61            solid_fan_seen_boundary_scratch: Vec::with_capacity(SOLID_FAN_POLYGON_SCRATCH_CAPACITY),
62            solid_fan_span_cache: SolidFanSpanCache::default(),
63            #[cfg(feature = "egui")]
64            skip_unchanged_frames: true,
65            #[cfg(feature = "egui")]
66            previous_primitives: Vec::new(),
67            #[cfg(feature = "egui")]
68            previous_frame_valid: false,
69        }
70    }
71}
72
73impl SoftwareRenderer {
74    /// The surface holding the most recently rendered frame.
75    #[must_use]
76    pub const fn surface(&self) -> &SoftwareSurface {
77        &self.surface
78    }
79
80    /// Drawing or changing textures outside egui leaves the last egui frame's pixels stale, so
81    /// the next egui frame must rasterize even if egui's output did not change.
82    #[cfg_attr(not(feature = "egui"), allow(clippy::unused_self))]
83    const fn forget_last_egui_frame(&mut self) {
84        #[cfg(feature = "egui")]
85        {
86            self.previous_frame_valid = false;
87        }
88    }
89}
90
91fn rasterize_mesh_contents(
92    context: &mut MeshRasterContext<'_>,
93    stats: &mut Option<&mut PrimitiveStats>,
94    raster_stats: &mut Option<&mut RasterStats>,
95    raster_timings: &mut Option<&mut RasterTimings>,
96) -> io::Result<()> {
97    let mut index_offset = 0;
98    while index_offset + 2 < context.mesh.indices.len() {
99        if context.try_rasterize_quad_at(index_offset, stats, raster_stats, raster_timings)? {
100            index_offset += 6;
101            continue;
102        }
103
104        if let Some(fan_triangle_count) =
105            context.try_rasterize_solid_fan_at(index_offset, stats, raster_stats, raster_timings)?
106        {
107            index_offset += fan_triangle_count * 3;
108            continue;
109        }
110
111        context.rasterize_generic_triangle_at(index_offset, stats, raster_stats, raster_timings)?;
112        index_offset += 3;
113    }
114    Ok(())
115}
116
117struct MeshRasterContext<'a> {
118    surface: &'a mut SoftwareSurface,
119    fan_polygon_scratch: &'a mut Vec<usize>,
120    fan_seen_boundary_scratch: &'a mut Vec<FanBoundaryKey>,
121    fan_span_cache: &'a mut SolidFanSpanCache,
122    mesh: RasterMesh<'a>,
123    texture: &'a TextureImage,
124    clip: ClipBounds,
125    primitive_index: usize,
126    solid_fan_polygon_scratch_budget: usize,
127}
128
129#[cfg(feature = "egui")]
130fn mesh_quad_vertices<'a>(
131    mesh: RasterMesh<'a>,
132    quad: &[u32],
133) -> io::Result<Option<[&'a Vertex; 6]>> {
134    let i0 = mesh_index_to_usize(quad[0])?;
135    let i1 = mesh_index_to_usize(quad[1])?;
136    let i2 = mesh_index_to_usize(quad[2])?;
137    let i3 = mesh_index_to_usize(quad[3])?;
138    let i4 = mesh_index_to_usize(quad[4])?;
139    let i5 = mesh_index_to_usize(quad[5])?;
140    let (Some(v0), Some(v1), Some(v2), Some(v3), Some(v4), Some(v5)) = (
141        mesh.vertices.get(i0),
142        mesh.vertices.get(i1),
143        mesh.vertices.get(i2),
144        mesh.vertices.get(i3),
145        mesh.vertices.get(i4),
146        mesh.vertices.get(i5),
147    ) else {
148        return Ok(None);
149    };
150    Ok(Some([v0, v1, v2, v3, v4, v5]))
151}
152
153impl MeshRasterContext<'_> {
154    fn try_rasterize_quad_at(
155        &mut self,
156        index_offset: usize,
157        stats: &mut Option<&mut PrimitiveStats>,
158        raster_stats: &mut Option<&mut RasterStats>,
159        raster_timings: &mut Option<&mut RasterTimings>,
160    ) -> io::Result<bool> {
161        if index_offset + 5 >= self.mesh.indices.len() {
162            return Ok(false);
163        }
164        let quad = &self.mesh.indices[index_offset..index_offset + 6];
165        let mut instrumentation = RasterInstrumentation {
166            primitive_stats: borrow_optional_mut(stats),
167            raster_stats: borrow_optional_mut(raster_stats),
168            timings: borrow_optional_mut(raster_timings),
169        };
170        try_rasterize_quad_window(
171            self.surface,
172            self.mesh,
173            self.texture,
174            self.clip,
175            quad,
176            self.source(index_offset),
177            &mut instrumentation,
178        )
179    }
180
181    fn first_triangle_has_mixed_vertex_colors(&self, index_offset: usize) -> bool {
182        let color_at = |slot: usize| {
183            usize::try_from(self.mesh.indices[index_offset + slot])
184                .ok()
185                .and_then(|index| self.mesh.vertices.get(index))
186                .map(|vertex| vertex.color)
187        };
188        match (color_at(0), color_at(1), color_at(2)) {
189            (Some(c0), Some(c1), Some(c2)) => c0 != c1 || c0 != c2,
190            // Leave malformed indices to the full probe, which reports them.
191            _ => false,
192        }
193    }
194
195    fn try_rasterize_solid_fan_at(
196        &mut self,
197        index_offset: usize,
198        stats: &mut Option<&mut PrimitiveStats>,
199        raster_stats: &mut Option<&mut RasterStats>,
200        raster_timings: &mut Option<&mut RasterTimings>,
201    ) -> io::Result<Option<usize>> {
202        if self.remaining_triangles_at(index_offset) < SOLID_FAN_MIN_TRIANGLES {
203            if let Some(stats) = borrow_optional_mut(stats) {
204                stats.solid_fan_probe.preflight_reject_too_few_triangles += 1;
205            }
206            return Ok(None);
207        }
208        // Every triangle of a solid fan has one vertex color, so a first triangle with mixed
209        // colors (feathered edges, gradients) rejects before any geometry is examined.
210        if self.first_triangle_has_mixed_vertex_colors(index_offset) {
211            if let Some(stats) = borrow_optional_mut(stats) {
212                stats.solid_fan_probe.preflight_reject_mixed_vertex_colors += 1;
213            }
214            return Ok(None);
215        }
216
217        let fan_probe_start = raster_timings.as_ref().map(|_| Instant::now());
218        let fan = solid_fan_run(
219            self.mesh,
220            self.texture,
221            self.clip,
222            index_offset,
223            SolidFanPolygonScratch {
224                polygon: &mut *self.fan_polygon_scratch,
225                seen_boundaries: &mut *self.fan_seen_boundary_scratch,
226                budget: self.solid_fan_polygon_scratch_budget,
227            },
228            stats.as_deref_mut().map(|stats| &mut stats.solid_fan_probe),
229        )?;
230        let fan_accepted = fan.is_some();
231        if let (Some(start), Some(timings)) = (fan_probe_start, borrow_optional_mut(raster_timings))
232        {
233            timings.record_solid_fan_probe(fan_accepted, start.elapsed().as_micros());
234        }
235        let Some(fan) = fan else {
236            self.fan_polygon_scratch.clear();
237            return Ok(None);
238        };
239        let mut instrumentation = RasterInstrumentation {
240            primitive_stats: borrow_optional_mut(stats),
241            raster_stats: borrow_optional_mut(raster_stats),
242            timings: borrow_optional_mut(raster_timings),
243        };
244        let source = self.source(index_offset);
245        rasterize_solid_fan_run(
246            SolidFanRasterRunContext {
247                surface: self.surface,
248                mesh: self.mesh,
249                fan_span_cache: self.fan_span_cache,
250                clip: self.clip,
251                source,
252            },
253            &fan,
254            self.fan_polygon_scratch,
255            &mut instrumentation,
256        );
257        let fan_triangle_count = fan.triangle_count;
258        self.fan_polygon_scratch.clear();
259        Ok(Some(fan_triangle_count))
260    }
261
262    fn remaining_triangles_at(&self, index_offset: usize) -> usize {
263        self.mesh.indices[index_offset..].len() / 3
264    }
265
266    fn rasterize_generic_triangle_at(
267        &mut self,
268        index_offset: usize,
269        stats: &mut Option<&mut PrimitiveStats>,
270        raster_stats: &mut Option<&mut RasterStats>,
271        raster_timings: &mut Option<&mut RasterTimings>,
272    ) -> io::Result<()> {
273        let Some([v0, v1, v2]) = mesh_triangle_vertices(self.mesh, index_offset)? else {
274            return Ok(());
275        };
276        let source = self.source(index_offset);
277        if let Some(stats) = borrow_optional_mut(stats) {
278            stats.record_generic_triangle(v0, v1, v2, self.texture, self.clip, source);
279        }
280        rasterize_generic_triangle(
281            self.surface,
282            [v0, v1, v2],
283            self.texture,
284            self.clip,
285            raster_stats,
286            raster_timings,
287        );
288        Ok(())
289    }
290
291    const fn source(&self, index_offset: usize) -> TriangleSource {
292        TriangleSource {
293            primitive_index: self.primitive_index,
294            mesh_index_offset: index_offset,
295        }
296    }
297}
298
299fn mesh_triangle_vertices(
300    mesh: RasterMesh<'_>,
301    index_offset: usize,
302) -> io::Result<Option<[&Vertex; 3]>> {
303    let triangle = &mesh.indices[index_offset..index_offset + 3];
304    let i0 = mesh_index_to_usize(triangle[0])?;
305    let i1 = mesh_index_to_usize(triangle[1])?;
306    let i2 = mesh_index_to_usize(triangle[2])?;
307    let Some(v0) = mesh.vertices.get(i0) else {
308        return Ok(None);
309    };
310    let Some(v1) = mesh.vertices.get(i1) else {
311        return Ok(None);
312    };
313    let Some(v2) = mesh.vertices.get(i2) else {
314        return Ok(None);
315    };
316    Ok(Some([v0, v1, v2]))
317}
318
319fn rasterize_generic_triangle(
320    surface: &mut SoftwareSurface,
321    vertices: [&Vertex; 3],
322    texture: &TextureImage,
323    clip: ClipBounds,
324    raster_stats: &mut Option<&mut RasterStats>,
325    raster_timings: &mut Option<&mut RasterTimings>,
326) {
327    let [v0, v1, v2] = vertices;
328    let triangle_classification = raster_timings
329        .as_ref()
330        .map(|_| classify_triangle(v0, v1, v2, texture));
331    let triangle_start = raster_timings.as_ref().map(|_| Instant::now());
332    rasterize_triangle(
333        surface,
334        v0,
335        v1,
336        v2,
337        texture,
338        clip,
339        borrow_optional_mut(raster_stats),
340    );
341    if let (Some(start), Some(classification), Some(timings)) = (
342        triangle_start,
343        triangle_classification,
344        borrow_optional_mut(raster_timings),
345    ) {
346        timings.record_generic_triangle(classification, start.elapsed().as_micros());
347    }
348}
349
350fn rasterize_solid_fan_run(
351    context: SolidFanRasterRunContext<'_>,
352    fan: &SolidFanRun,
353    fan_polygon: &[usize],
354    instrumentation: &mut RasterInstrumentation<'_>,
355) {
356    let SolidFanRasterRunContext {
357        surface,
358        mesh,
359        fan_span_cache,
360        clip,
361        source,
362    } = context;
363    let fan_work_before = instrumentation
364        .raster_stats
365        .as_deref()
366        .map(SolidFanRasterWork::from_stats);
367    let fan_bounds = instrumentation
368        .primitive_stats
369        .as_ref()
370        .and_then(|_| polygon_raster_bounds(mesh.vertices, &fan_polygon[..fan.polygon_len], clip));
371    let fan_start = instrumentation.timing_start();
372    rasterize_solid_fan_with_cache(
373        surface,
374        SolidFanRasterParams {
375            vertices: mesh.vertices,
376            polygon: &fan_polygon[..fan.polygon_len],
377            triangle_count: fan.triangle_count,
378            color: fan.color,
379            clip,
380        },
381        &mut instrumentation.raster_stats(),
382        Some(fan_span_cache),
383    );
384    let elapsed_us = fan_start.map_or(0, |start| start.elapsed().as_micros());
385    let fan_work_after = instrumentation
386        .raster_stats
387        .as_deref()
388        .map(SolidFanRasterWork::from_stats);
389    let fan_work = fan_work_before
390        .zip(fan_work_after)
391        .map_or_else(SolidFanRasterWork::default, |(before, after)| {
392            after - before
393        });
394    if let Some(stats) = instrumentation.primitive_stats() {
395        stats.solid_fan_runs += 1;
396        stats.solid_fan_triangles += fan.triangle_count;
397        stats.record_solid_fan(SolidFanRasterRecord {
398            source,
399            triangle_count: fan.triangle_count,
400            polygon_vertices: fan.polygon_len,
401            alpha: fan.color[3],
402            bounds: fan_bounds,
403            work: fan_work,
404            elapsed_us,
405        });
406    }
407    if let Some(timings) = instrumentation.timings() {
408        timings.solid_fan_raster += elapsed_us;
409    }
410}
411
412struct SolidFanRasterRunContext<'a> {
413    surface: &'a mut SoftwareSurface,
414    mesh: RasterMesh<'a>,
415    fan_span_cache: &'a mut SolidFanSpanCache,
416    clip: ClipBounds,
417    source: TriangleSource,
418}
419
420struct RasterInstrumentation<'a> {
421    primitive_stats: Option<&'a mut PrimitiveStats>,
422    raster_stats: Option<&'a mut RasterStats>,
423    timings: Option<&'a mut RasterTimings>,
424}
425
426impl RasterInstrumentation<'_> {
427    fn primitive_stats(&mut self) -> Option<&mut PrimitiveStats> {
428        borrow_optional_mut(&mut self.primitive_stats)
429    }
430
431    fn raster_stats(&mut self) -> Option<&mut RasterStats> {
432        borrow_optional_mut(&mut self.raster_stats)
433    }
434
435    fn timings(&mut self) -> Option<&mut RasterTimings> {
436        borrow_optional_mut(&mut self.timings)
437    }
438
439    const fn collects_stats(&self) -> bool {
440        self.primitive_stats.is_some() || self.raster_stats.is_some() || self.timings.is_some()
441    }
442
443    fn timing_start(&self) -> Option<Instant> {
444        self.timings.as_ref().map(|_| Instant::now())
445    }
446}
447
448fn mesh_index_to_usize(index: u32) -> io::Result<usize> {
449    usize::try_from(index).map_err(|_| io::Error::other("mesh index does not fit usize"))
450}
451
452fn borrow_optional_mut<'a, T>(option: &'a mut Option<&mut T>) -> Option<&'a mut T> {
453    option.as_mut().map(|value| &mut **value)
454}