Skip to main content

alpha2_render/cpu/
renderer.rs

1//! The CPU renderer: its built-in catalog, controls and result cache.
2
3use std::collections::{HashMap, HashSet};
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
6
7use super::frames::FramePool;
8use super::image::CpuImage;
9use super::kernels::{CpuKernel, CpuLut, kernel};
10use super::workers::Workers;
11use crate::result_cache::{CachedPicture, ResultCache};
12use crate::{
13    BlendSpace, CacheInvalidation, EffectCatalog, EffectDef, EffectId, GraphError, Lut3dData,
14    RenderCacheKey, RenderControls, RenderError, RenderGraph, RenderQualityControls,
15    ResultCacheStats,
16};
17
18impl CachedPicture for Arc<CpuImage> {
19    fn cached_bytes(&self) -> u64 {
20        self.retained_bytes()
21    }
22}
23
24pub(crate) struct CatalogEntry {
25    pub(crate) definition: Arc<EffectDef>,
26    pub(crate) reads_time: bool,
27    pub(crate) kernel: &'static dyn CpuKernel,
28}
29
30/// Counts of what the CPU renderer has drawn, for metrics.
31#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
32pub struct CpuRenderStats {
33    /// Graphs drawn.
34    pub graphs: u64,
35    /// Nodes drawn (not found in the result cache).
36    pub nodes: u64,
37    /// Time spent drawing graphs, in microseconds.
38    pub render_micros: u64,
39    /// Part of `render_micros` spent converting decoded frames to source pictures.
40    pub present_micros: u64,
41    /// Part of `render_micros` spent in effect, transition and generator passes.
42    pub kernel_micros: u64,
43    /// Part of `render_micros` spent compositing layers.
44    pub composite_micros: u64,
45    /// Part of `render_micros` spent drawing vector scenes.
46    pub vector_micros: u64,
47    /// Part of `render_micros` spent packing pictures into encoder planes.
48    pub pack_micros: u64,
49    /// Sources presented: decoded frames converted to pictures.
50    pub presented_sources: u64,
51    /// Bytes of the largest picture set one graph held at once.
52    pub image_high_water_bytes: u64,
53    /// Pictures drawn into a frame buffer kept from an earlier picture.
54    pub reused_frame_buffers: u64,
55}
56
57#[derive(Default)]
58pub(crate) struct StatCounters {
59    pub(crate) graphs: AtomicU64,
60    pub(crate) nodes: AtomicU64,
61    pub(crate) render_micros: AtomicU64,
62    pub(crate) present_micros: AtomicU64,
63    pub(crate) kernel_micros: AtomicU64,
64    pub(crate) composite_micros: AtomicU64,
65    pub(crate) vector_micros: AtomicU64,
66    pub(crate) pack_micros: AtomicU64,
67    pub(crate) presented_sources: AtomicU64,
68    pub(crate) image_high_water_bytes: AtomicU64,
69}
70
71/// Adds the microseconds since `started` to `counter`.
72pub(crate) fn add_elapsed(counter: &AtomicU64, started: web_time::Instant) {
73    counter.fetch_add(
74        u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX),
75        Ordering::Relaxed,
76    );
77}
78
79/// A renderer that draws [`RenderGraph`]s on the CPU with no GPU or driver.
80///
81/// It draws every built-in of the GPU [`crate::Renderer`] to the same contract: same graph,
82/// same stages, same half-float storage. Runtime WGSL effects have no CPU implementation and
83/// fail with [`RenderError::UnknownEffect`]. Output is identical for any thread count and target.
84pub struct CpuRenderer {
85    pub(crate) workers: Workers,
86    pub(crate) blend_space: BlendSpace,
87    pub(crate) frame_pool: Arc<FramePool>,
88    quality: Mutex<RenderQualityControls>,
89    cache: Mutex<ResultCache<Arc<CpuImage>>>,
90    catalog: HashMap<EffectId, CatalogEntry>,
91    internal: HashSet<EffectId>,
92    resources: std::sync::RwLock<HashMap<String, Arc<CpuLut>>>,
93    /// Vector coverage cached between frames, as on the GPU.
94    pub(crate) coverage: Mutex<alpha2_geometry::raster::CoverageCache>,
95    pub(crate) stats: StatCounters,
96    frames: AtomicU64,
97    repeated: AtomicU64,
98}
99
100impl std::fmt::Debug for CpuRenderer {
101    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        formatter
103            .debug_struct("CpuRenderer")
104            .field("threads", &self.workers.threads())
105            .field("blend_space", &self.blend_space)
106            .finish_non_exhaustive()
107    }
108}
109
110impl CpuRenderer {
111    /// A CPU renderer on `threads` threads (one means the calling thread), with every built-in
112    /// registered.
113    #[must_use]
114    pub fn new(threads: usize) -> Self {
115        Self::with_workers(Workers::new(threads))
116    }
117
118    /// As [`Self::new`], with every band `rows` rows high (`usize::MAX` for one band).
119    #[cfg(test)]
120    pub(crate) fn with_band_rows(threads: usize, rows: usize) -> Self {
121        Self::with_workers(Workers::with_band_rows(threads, rows))
122    }
123
124    fn with_workers(workers: Workers) -> Self {
125        let mut catalog = HashMap::new();
126        let mut internal = HashSet::new();
127        for (definition, is_internal) in crate::builtins::internal_effect_definitions()
128            .into_iter()
129            .map(|definition| (definition, true))
130            .chain(
131                crate::builtin_effect_definitions()
132                    .into_iter()
133                    .chain(crate::builtin_transition_definitions())
134                    .chain(crate::builtin_generator_definitions())
135                    .map(|definition| (definition, false)),
136            )
137        {
138            let Some(kernel) = kernel(&definition.id, definition.version) else {
139                continue;
140            };
141            let id = EffectId::new(definition.id.clone(), definition.version);
142            if is_internal {
143                internal.insert(id.clone());
144            }
145            catalog.insert(
146                id,
147                CatalogEntry {
148                    reads_time: crate::registry::body_reads_time(&definition.wgsl_body),
149                    definition: Arc::new(definition),
150                    kernel,
151                },
152            );
153        }
154        Self {
155            workers,
156            blend_space: BlendSpace::default(),
157            frame_pool: Arc::default(),
158            quality: Mutex::new(RenderQualityControls::default()),
159            cache: Mutex::new(ResultCache::default()),
160            catalog,
161            internal,
162            resources: std::sync::RwLock::default(),
163            coverage: Mutex::new(alpha2_geometry::raster::CoverageCache::default()),
164            stats: StatCounters::default(),
165            frames: AtomicU64::new(0),
166            repeated: AtomicU64::new(0),
167        }
168    }
169
170    /// Blends composites in `blend_space` unless a graph sets its own.
171    #[must_use]
172    pub const fn with_blend_space(mut self, blend_space: BlendSpace) -> Self {
173        self.blend_space = blend_space;
174        self
175    }
176
177    /// Threads the renderer draws on.
178    #[must_use]
179    pub const fn threads(&self) -> usize {
180        self.workers.threads()
181    }
182
183    /// The quality controls passes use now.
184    #[must_use]
185    pub fn quality_controls(&self) -> RenderQualityControls {
186        *self.quality.lock().unwrap_or_else(PoisonError::into_inner)
187    }
188
189    /// Built-ins the GPU registers that this renderer cannot draw, as `(id, version)`; currently
190    /// empty.
191    #[must_use]
192    pub fn unsupported_builtins() -> Vec<(String, u32)> {
193        crate::builtin_effect_definitions()
194            .into_iter()
195            .chain(crate::builtin_transition_definitions())
196            .chain(crate::builtin_generator_definitions())
197            .chain(crate::builtins::internal_effect_definitions())
198            .filter(|definition| kernel(&definition.id, definition.version).is_none())
199            .map(|definition| (definition.id, definition.version))
200            .collect()
201    }
202
203    /// Keeps up to `budget_bytes` of node results for reuse, like
204    /// [`crate::Renderer::set_result_cache_budget`].
205    pub fn set_result_cache_budget(&self, budget_bytes: u64) {
206        self.lock_cache().set_budget(budget_bytes);
207    }
208
209    /// The result cache's counters.
210    #[must_use]
211    pub fn result_cache_stats(&self) -> ResultCacheStats {
212        self.lock_cache().stats()
213    }
214
215    /// Drops every cached result.
216    pub fn clear_result_cache(&self) {
217        self.lock_cache().clear(CacheInvalidation::Explicit);
218    }
219
220    /// What the renderer has drawn so far.
221    #[must_use]
222    pub fn stats(&self) -> CpuRenderStats {
223        CpuRenderStats {
224            graphs: self.stats.graphs.load(Ordering::Relaxed),
225            nodes: self.stats.nodes.load(Ordering::Relaxed),
226            render_micros: self.stats.render_micros.load(Ordering::Relaxed),
227            present_micros: self.stats.present_micros.load(Ordering::Relaxed),
228            kernel_micros: self.stats.kernel_micros.load(Ordering::Relaxed),
229            composite_micros: self.stats.composite_micros.load(Ordering::Relaxed),
230            vector_micros: self.stats.vector_micros.load(Ordering::Relaxed),
231            pack_micros: self.stats.pack_micros.load(Ordering::Relaxed),
232            presented_sources: self.stats.presented_sources.load(Ordering::Relaxed),
233            image_high_water_bytes: self.stats.image_high_water_bytes.load(Ordering::Relaxed),
234            reused_frame_buffers: self.frame_pool.reused(),
235        }
236    }
237
238    /// Frames presented and frames that repeated the previous one, as recorded via
239    /// [`RenderControls::record_frame_outcome`].
240    #[must_use]
241    pub fn frame_outcomes(&self) -> (u64, u64) {
242        (
243            self.frames.load(Ordering::Relaxed),
244            self.repeated.load(Ordering::Relaxed),
245        )
246    }
247
248    /// Registers or replaces 3D LUT `id`, like [`crate::Renderer::register_lut3d`].
249    ///
250    /// # Errors
251    /// [`RenderError::InvalidEffectResource`] for an empty id or an invalid cube.
252    pub fn register_lut3d(
253        &self,
254        id: impl Into<String>,
255        data: &Lut3dData,
256    ) -> Result<(), RenderError> {
257        let id = id.into();
258        if id.is_empty() || !data.is_valid(u32::MAX) {
259            return Err(RenderError::InvalidEffectResource);
260        }
261        // Stored as the GPU's half-float texture stores it.
262        let values = data
263            .values
264            .iter()
265            .map(|rgb| rgb.map(|value| half::f16::from_f32(value).to_f32()))
266            .collect();
267        self.resources_mut().insert(
268            id,
269            Arc::new(CpuLut {
270                edge: data.edge_length,
271                domain_min: data.domain_min,
272                domain_max: data.domain_max,
273                values,
274            }),
275        );
276        self.lock_cache().clear(CacheInvalidation::EffectResources);
277        Ok(())
278    }
279
280    /// Removes every resource and clears the cached results.
281    pub fn clear_effect_resources(&self) {
282        self.resources_mut().clear();
283        self.lock_cache().clear(CacheInvalidation::EffectResources);
284    }
285
286    /// Drops the cached results and idle frame buffers and returns the bytes they held.
287    pub fn release_idle_memory(&self) -> u64 {
288        let mut cache = self.lock_cache();
289        let bytes = cache.stats().bytes;
290        cache.clear(CacheInvalidation::Explicit);
291        drop(cache);
292        bytes + self.frame_pool.release()
293    }
294
295    /// Drops the frame buffers kept for the next frame and returns their bytes; the result cache
296    /// stays.
297    pub fn release_frame_buffers(&self) -> u64 {
298        self.frame_pool.release()
299    }
300
301    /// Removes the resource `id` and returns whether it existed.
302    pub fn unregister_effect_resource(&self, id: &str) -> bool {
303        let removed = self.resources_mut().remove(id).is_some();
304        if removed {
305            self.lock_cache().clear(CacheInvalidation::EffectResources);
306        }
307        removed
308    }
309
310    pub(crate) fn resource(&self, id: &str) -> Option<Arc<CpuLut>> {
311        self.resources
312            .read()
313            .unwrap_or_else(PoisonError::into_inner)
314            .get(id)
315            .cloned()
316    }
317
318    fn resources_mut(&self) -> std::sync::RwLockWriteGuard<'_, HashMap<String, Arc<CpuLut>>> {
319        self.resources
320            .write()
321            .unwrap_or_else(PoisonError::into_inner)
322    }
323
324    pub(crate) fn entry(&self, id: &EffectId) -> Option<&CatalogEntry> {
325        self.catalog.get(id)
326    }
327
328    pub(crate) fn lock_cache(&self) -> MutexGuard<'_, ResultCache<Arc<CpuImage>>> {
329        self.cache.lock().unwrap_or_else(PoisonError::into_inner)
330    }
331}
332
333impl EffectCatalog for CpuRenderer {
334    fn effect_definition(&self, id: &EffectId) -> Option<Arc<EffectDef>> {
335        self.catalog
336            .get(id)
337            .map(|entry| Arc::clone(&entry.definition))
338    }
339
340    fn effect_reads_time(&self, id: &EffectId) -> bool {
341        if let Some(passes) = crate::gaussian_blur::expanded_passes(id.as_str()) {
342            return passes
343                .iter()
344                .any(|pass| self.effect_reads_time(&EffectId::from_static(pass, 1)));
345        }
346        self.catalog.get(id).is_none_or(|entry| entry.reads_time)
347    }
348
349    fn project_effect_id(&self, id: &str, version: u32) -> Option<EffectId> {
350        let key = EffectId::new(id.to_owned(), version);
351        self.catalog
352            .get_key_value(&key)
353            .map(|(id, _)| id)
354            .filter(|id| !self.internal.contains(*id))
355            .cloned()
356    }
357}
358
359impl RenderControls for CpuRenderer {
360    fn set_quality_controls(&self, max_filter_samples: u32) {
361        let next = RenderQualityControls {
362            max_filter_samples: max_filter_samples
363                .clamp(1, RenderQualityControls::MAX_FILTER_SAMPLES),
364        };
365        let mut quality = self.quality.lock().unwrap_or_else(PoisonError::into_inner);
366        if *quality != next {
367            *quality = next;
368            drop(quality);
369            // Results under other controls are different pictures.
370            self.lock_cache().clear(CacheInvalidation::Quality);
371        }
372    }
373
374    fn set_texture_budget_bytes(&self, budget_bytes: u64) {
375        self.frame_pool.set_budget(budget_bytes);
376    }
377
378    fn content_epoch(&self) -> u64 {
379        self.lock_cache().clears()
380    }
381
382    fn record_frame_outcome(&self, presented: bool, repeated: bool) {
383        if presented {
384            self.frames.fetch_add(1, Ordering::Relaxed);
385        }
386        if repeated {
387            self.repeated.fetch_add(1, Ordering::Relaxed);
388        }
389    }
390
391    fn graph_cache_key(&self, graph: &RenderGraph<'_>) -> Result<RenderCacheKey, GraphError> {
392        let plan = graph.compile()?;
393        Ok(crate::graph_cache::cpu_renderer_cache_key(
394            plan.cache_key,
395            graph.blend_space.unwrap_or(self.blend_space).shader_value(),
396            self.quality_controls(),
397        ))
398    }
399}