Skip to main content

three_rs/renderer/
info.rs

1//! `renderer.info` (three.js/src/renderers/common/Info.js): what the last
2//! frame drew, what it had to build, and what the renderer is still holding.
3//!
4//! Time is the proof a frame is cheap but not the diagnosis (issue #57): it
5//! jitters, so its ceiling has to be generous, and a regression that re-uploads
6//! every geometry of a small scene stays under it. These are counts, so they
7//! are exact and a steady frame's build block is asserted at zero rather than
8//! under a bound (issue #67).
9
10use wgpu::PrimitiveTopology;
11
12/// What one frame drew and what it cost to get there.
13///
14/// three.js resets `render` and `memory`-adjacent per-frame fields at the top
15/// of `Renderer.render()` and exposes `info.autoReset` for the composed frame,
16/// where one application frame is several `render()` calls; this port does the
17/// same. See [`Info::auto_reset`].
18#[derive(Clone, Debug, Default, PartialEq, Eq)]
19#[non_exhaustive]
20pub struct Info {
21    /// `info.autoReset`: reset [`render`](Self::render) and
22    /// [`build`](Self::build) at the top of every [`Renderer::render`].
23    ///
24    /// A rung whose frame is several renders — a pass into a render target and
25    /// then a full-screen quad (rtt, depth texture), three `PassNode`s and a
26    /// `RenderPipeline` (postprocessing masking) — wants the counts for the
27    /// whole frame, so it turns this off and calls [`Info::reset`] itself, the
28    /// way three.js' postprocessing does. `three_rs::testing::strip` is the
29    /// only caller in the tree.
30    ///
31    /// [`Renderer::render`]: crate::Renderer::render
32    pub auto_reset: bool,
33
34    /// Reset every frame: what was drawn.
35    pub render: RenderCounts,
36    /// Reset every frame: what the frame had to build or upload. Every field
37    /// is zero on a frame whose scene the renderer has already seen.
38    pub build: BuildCounts,
39    /// Not reset: what the renderer is holding on to right now.
40    pub memory: MemoryCounts,
41    /// Not reset: `info.compute`.
42    pub compute: ComputeCounts,
43}
44
45/// `info.compute`.
46///
47/// three.js has a second field, `frameCalls`, cleared by `Info.reset()` — which
48/// its animation loop calls at the *top of the frame callback*
49/// (`Animation.js:81`), before `renderer.compute()` runs. This port has no
50/// animation loop and resets in [`Renderer::render`], which runs *after* the
51/// frame's compute calls, so a `frame_calls` here would always read zero. The
52/// cumulative count is the honest one; the per-frame question "did this frame
53/// build a compute pipeline" is answered by [`BuildCounts`] instead.
54///
55/// [`Renderer::render`]: crate::Renderer::render
56#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
57#[non_exhaustive]
58pub struct ComputeCounts {
59    /// `info.compute.calls`: `Renderer::compute()` calls since startup,
60    /// `onInit`'s recursive call included — three counts it too.
61    pub calls: u64,
62}
63
64/// `info.render`.
65#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
66#[non_exhaustive]
67pub struct RenderCounts {
68    /// Draw calls (`drawArrays` / `drawElements`; here `draw` /
69    /// `draw_indexed`), instanced draws counting once.
70    pub calls: u64,
71    /// Primitives, with the instance count multiplied in, as three.js counts
72    /// them.
73    pub triangles: u64,
74    /// Points drawn, instance count multiplied in.
75    pub points: u64,
76    /// Line segments drawn, instance count multiplied in.
77    pub lines: u64,
78}
79
80/// The per-frame build block: the work a steady frame must not do.
81#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
82#[non_exhaustive]
83pub struct BuildCounts {
84    /// `NodeBuilder::build` calls — a material's WGSL generated, and compiled
85    /// into a [`programs`](MemoryCounts::programs) entry if that WGSL is new.
86    pub programs_compiled: u64,
87    /// Render pipelines created for a program and a pass state.
88    pub pipelines_built: u64,
89    /// Geometries uploaded to the GPU (`Geometries.get()`'s misses).
90    pub geometries_uploaded: u64,
91    /// Attribute and index buffers written as part of those uploads — four for
92    /// a geometry with position, normal, uv and an index — plus one for each
93    /// `InstancedBufferAttribute` (an `InstancedMesh`'s `instanceMatrix` or
94    /// `instanceColor`) written because it is new or its version moved
95    /// (issue #89). Per-draw uniforms (morph influences, bone matrices) are
96    /// written into a buffer the draw already has, which is not a build and is
97    /// not counted here or anywhere.
98    pub buffers_written: u64,
99    /// Textures uploaded: 2D, cube and the morph data-array textures.
100    pub textures_uploaded: u64,
101    /// GPU buffers created for bindings: a draw's uniform groups, bone
102    /// matrices and morph influences the first time it is drawn, an
103    /// `InstancedBufferAttribute`'s buffer the first time it is drawn or when
104    /// it outgrows the one it has, a `range()` / `uniformArray()` /
105    /// instanced-attribute buffer, an `instancedArray()`'s storage
106    /// (issue #137).
107    pub buffers_created: u64,
108    /// Texture views created for bindings — one per texture and view
109    /// dimension, and again when a render target is re-allocated.
110    pub views_created: u64,
111    /// Samplers created — one per distinct filter / wrap / compare
112    /// combination for the renderer's life.
113    pub samplers_created: u64,
114    /// Bind groups created — one per draw group the first time it is drawn,
115    /// and again when one of its resources is replaced.
116    pub bind_groups_created: u64,
117}
118
119/// `info.memory` plus `info.programs.length`: resident counts, never reset.
120#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
121#[non_exhaustive]
122pub struct MemoryCounts {
123    /// Entries in the uploaded-geometry cache, swept as the consumer drops
124    /// geometries (issue #58).
125    pub geometries: usize,
126    /// Entries in the 2D and cube texture caches, swept as the consumer drops
127    /// textures (issue #158). A render target's own colour texture and a morph
128    /// data-array texture live on the texture rather than in a renderer map,
129    /// so they upload but do not land here; they are freed with their owner.
130    pub textures: usize,
131    /// Distinct compiled programs — `renderer.info.programs.length`: render
132    /// programs plus compute pipelines. Two materials that generate the same
133    /// WGSL share one. A program goes once nothing has named it for a few
134    /// frames (issue #237), so this falls as well as rises.
135    pub programs: usize,
136}
137
138impl Info {
139    pub(crate) fn new() -> Self {
140        Self {
141            auto_reset: true,
142            ..Self::default()
143        }
144    }
145
146    /// `info.reset()`: clear the two per-frame blocks, leaving `memory`.
147    pub fn reset(&mut self) {
148        self.render = RenderCounts::default();
149        self.build = BuildCounts::default();
150    }
151
152    /// One `draw` / `draw_indexed`: `elements` vertices or indices, drawn
153    /// `instances` times.
154    pub(crate) fn record_draw(
155        &mut self,
156        topology: PrimitiveTopology,
157        elements: u32,
158        instances: u32,
159    ) {
160        self.render.calls += 1;
161
162        let (elements, instances) = (u64::from(elements), u64::from(instances));
163        match topology {
164            PrimitiveTopology::TriangleList => self.render.triangles += elements / 3 * instances,
165            PrimitiveTopology::TriangleStrip => {
166                self.render.triangles += elements.saturating_sub(2) * instances
167            }
168            PrimitiveTopology::LineList => self.render.lines += elements / 2 * instances,
169            PrimitiveTopology::LineStrip => {
170                self.render.lines += elements.saturating_sub(1) * instances
171            }
172            PrimitiveTopology::PointList => self.render.points += elements * instances,
173        }
174    }
175}
176
177impl BuildCounts {
178    /// Everything this frame built or uploaded. Zero is the steady frame.
179    pub fn total(&self) -> u64 {
180        self.programs_compiled
181            + self.pipelines_built
182            + self.geometries_uploaded
183            + self.buffers_written
184            + self.textures_uploaded
185            + self.buffers_created
186            + self.views_created
187            + self.samplers_created
188            + self.bind_groups_created
189    }
190}
191
192impl std::fmt::Display for Info {
193    /// One line, as the e2e harness and the film strip's gutter print it.
194    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195        write!(
196            f,
197            "calls {} triangles {} lines {} | programs {} pipelines {} geometries {} \
198             buffers {} textures {} | created {} buffers {} views {} samplers {} bind groups \
199             | resident {} geometries {} textures {} programs",
200            self.render.calls,
201            self.render.triangles,
202            self.render.lines,
203            self.build.programs_compiled,
204            self.build.pipelines_built,
205            self.build.geometries_uploaded,
206            self.build.buffers_written,
207            self.build.textures_uploaded,
208            self.build.buffers_created,
209            self.build.views_created,
210            self.build.samplers_created,
211            self.build.bind_groups_created,
212            self.memory.geometries,
213            self.memory.textures,
214            self.memory.programs,
215        )
216    }
217}