Skip to main content

nadir_render/
batcher.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! [`SpriteBatcher`]: the work on the CPU of drawing sprites.
16
17use crate::instance::push_instance;
18use crate::plan::{Batch, GlyphQuad, Plan, Resolved};
19use crate::view::pixel_zoom;
20use crate::{Camera2D, FrameStats, SpriteDraw};
21
22/// The program a batch draws with.
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
24pub(crate) enum Pipe {
25    /// The `sprite` program: sprites, and the glyphs of
26    /// [`GlyphMode::Rgba`](crate::GlyphMode::Rgba) texts and of pages that
27    /// show their placeholder.
28    Sprite,
29    /// The `text` program: glyphs whose alpha is a mask.
30    Text,
31}
32
33/// Sorts a frame's sprites, groups them into batches by texture, and packs
34/// the instance of each one drawn: what the [`Renderer`](crate::Renderer)
35/// does on the CPU before it uploads the instances and draws. It is public
36/// so that this work can be measured without a GPU. The renderer gives it
37/// the frame's texts' glyphs too, laid out, which it plans with the
38/// sprites.
39///
40/// It is generic over the texture `K`: the renderer's is its GPU texture,
41/// and a benchmark can use any number. Its lists are reused from one build
42/// to the next, so a steady frame allocates nothing.
43#[derive(Debug)]
44pub struct SpriteBatcher<K> {
45    plan: Plan<(K, Pipe)>,
46    packed: Vec<f32>,
47}
48
49impl<K: Copy + Eq> SpriteBatcher<K> {
50    /// A batcher that has built nothing yet.
51    pub fn new() -> Self {
52        Self {
53            plan: Plan::new(),
54            packed: Vec::new(),
55        }
56    }
57
58    /// Sorts, batches and packs `sprites` as `camera` shows them, in
59    /// pixel-perfect mode.
60    ///
61    /// `texture` gives each sprite's texture: `None` while it is not ready,
62    /// and the sprite is not drawn. Otherwise it gives the texture, and
63    /// whether the sprite shows that texture's placeholder, all of it
64    /// whatever its `uv`, as a sprite whose texture failed to load does.
65    pub fn build(
66        &mut self,
67        sprites: &[SpriteDraw],
68        camera: &Camera2D,
69        texture: impl FnMut(&SpriteDraw) -> Option<(K, bool)>,
70    ) {
71        self.build_with(sprites, &[], camera, texture);
72    }
73
74    /// Builds `sprites` and the texts' `glyphs`, whose textures and
75    /// programs are found, as [`SpriteBatcher::build`] builds sprites: a
76    /// batch is one texture and one program.
77    pub(crate) fn build_with(
78        &mut self,
79        sprites: &[SpriteDraw],
80        glyphs: &[GlyphQuad<(K, Pipe)>],
81        camera: &Camera2D,
82        mut texture: impl FnMut(&SpriteDraw) -> Option<(K, bool)>,
83    ) {
84        self.plan
85            .build_with(sprites, glyphs, |sprite| match texture(sprite) {
86                None => Resolved::Skip,
87                Some((texture, false)) => Resolved::Draw((texture, Pipe::Sprite)),
88                Some((texture, true)) => Resolved::Placeholder((texture, Pipe::Sprite)),
89            });
90        let zoom = pixel_zoom(camera.zoom);
91        self.packed.clear();
92        for drawn in &self.plan.order {
93            let index = drawn.sprite as usize;
94            let sprite = match sprites.get(index) {
95                Some(sprite) => sprite,
96                None => &glyphs[index - sprites.len()].sprite,
97            };
98            push_instance(&mut self.packed, sprite, drawn.placeholder, Some(zoom));
99        }
100    }
101
102    /// The instances of the sprites and glyphs drawn, in draw order:
103    /// [`SPRITE_INSTANCE_FLOATS`](crate::SPRITE_INSTANCE_FLOATS) floats
104    /// each.
105    pub fn instances(&self) -> &[f32] {
106        &self.packed
107    }
108
109    /// What the last build drew. It knows nothing of tile layers, of texts
110    /// or of the UI: `tiles`, `chunks`, `texts`, `skipped_texts` and the
111    /// `ui_` counts are 0, and `batches` counts the batches before a tile
112    /// layer drawn among the sprites splits one in two.
113    pub fn stats(&self) -> FrameStats {
114        // The plan numbers its sprites and glyphs with a u32, so these fit.
115        FrameStats {
116            sprites: self.plan.order.len() as u32 - self.plan.glyphs,
117            skipped: self.plan.skipped,
118            batches: self.plan.batches.len() as u32,
119            tiles: 0,
120            chunks: 0,
121            texts: 0,
122            glyphs: self.plan.glyphs,
123            skipped_texts: 0,
124            ui_sprites: 0,
125            ui_glyphs: 0,
126            ui_texts: 0,
127            ui_batches: 0,
128        }
129    }
130
131    /// The batches of the last build, in draw order.
132    pub(crate) fn batches(&self) -> &[Batch<(K, Pipe)>] {
133        &self.plan.batches
134    }
135
136    /// Where tiles of `layer` and `depth` go among the sprites drawn: see
137    /// [`Plan::position`].
138    pub(crate) fn position(&self, layer: u8, depth: u32) -> u32 {
139        self.plan.position(layer, depth)
140    }
141}
142
143impl<K: Copy + Eq> Default for SpriteBatcher<K> {
144    fn default() -> Self {
145        Self::new()
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use nadir_assets::Handle;
152    use nadir_core::{GenIndex, Vec2};
153
154    use super::*;
155    use crate::SPRITE_INSTANCE_FLOATS;
156
157    fn sprite(texture: u32, y: f32) -> SpriteDraw {
158        let id = GenIndex::new(texture, std::num::NonZeroU32::MIN);
159        SpriteDraw::new(Handle::new(id), Vec2::new(10.0, y), Vec2::splat(8.0))
160    }
161
162    #[test]
163    fn it_skips_what_is_not_ready_and_packs_the_rest_in_draw_order() {
164        // Texture 0 is ready, 1 is loading, 2 failed and shows its
165        // placeholder.
166        let sprites = [
167            sprite(0, 30.0),
168            sprite(1, 10.0),
169            sprite(2, 20.0),
170            sprite(0, 5.0),
171        ];
172        let mut batcher = SpriteBatcher::new();
173        batcher.build(&sprites, &Camera2D::default(), |sprite| {
174            match sprite.texture.id().index() {
175                1 => None,
176                texture => Some((texture, texture == 2)),
177            }
178        });
179        assert_eq!(
180            batcher.stats(),
181            FrameStats {
182                sprites: 3,
183                skipped: 1,
184                batches: 3,
185                ..FrameStats::default()
186            }
187        );
188        let order: Vec<u32> = batcher
189            .batches()
190            .iter()
191            .map(|batch| batch.texture.0)
192            .collect();
193        assert_eq!(order, [0, 2, 0], "by depth: y 5, then 20, then 30");
194        // Every sprite draws with the sprite program, its placeholder too.
195        assert!(
196            batcher
197                .batches()
198                .iter()
199                .all(|batch| batch.texture.1 == Pipe::Sprite)
200        );
201        assert_eq!(batcher.instances().len(), 3 * SPRITE_INSTANCE_FLOATS);
202
203        // A second build replaces the first.
204        batcher.build(&sprites[..1], &Camera2D::default(), |_| Some((0, false)));
205        assert_eq!(batcher.stats().sprites, 1);
206        assert_eq!(batcher.instances().len(), SPRITE_INSTANCE_FLOATS);
207    }
208
209    #[test]
210    fn glyphs_are_packed_after_sprites_at_a_tie_and_split_batches_by_program() {
211        let mut panel = sprite(0, 5.0);
212        panel.sort = crate::SortMode::Fixed(3);
213        let mut quad = panel;
214        quad.position = Vec2::new(40.0, 7.0);
215        quad.pivot = Vec2::ZERO;
216        let glyph = |pipe| GlyphQuad {
217            sprite: quad,
218            text: 0,
219            texture: (0, pipe),
220            placeholder: false,
221        };
222        let glyphs = [glyph(Pipe::Text), glyph(Pipe::Sprite)];
223        let mut batcher = SpriteBatcher::new();
224        batcher.build_with(&[panel], &glyphs, &Camera2D::default(), |_| {
225            Some((0, false))
226        });
227        let stats = batcher.stats();
228        assert_eq!((stats.sprites, stats.glyphs, stats.batches), (1, 2, 3));
229        let batches: Vec<(u32, Pipe)> = batcher.batches().iter().map(|b| b.texture).collect();
230        assert_eq!(
231            batches,
232            [(0, Pipe::Sprite), (0, Pipe::Text), (0, Pipe::Sprite)]
233        );
234        // The glyph's instance is its own quad's: its corner at (40, 7).
235        let second = &batcher.instances()[SPRITE_INSTANCE_FLOATS..];
236        assert_eq!(second[..2], [40.0, 7.0]);
237    }
238}