Skip to main content

repame_view2d/
batch.rs

1//! GPU sprite batch: instanced textured quads as a [`WgpuCallback`].
2//! Owns the atlas texture array and instance buffer. Feeds from
3//! [`AtlasUpload`]s, draws through a caller-supplied camera matrix.
4//!
5//! ```ignore
6//! let mut batch = SpriteBatch::new(BatchDesc::default());
7//! batch.set_camera(screen_camera([1920.0, 1080.0]));
8//! for s in &input.sprites {
9//!     batch.push_sprite(s);
10//! }
11//! Embedded(Modifier::new().fill_max_size(), Callback::new(batch))
12//! ```
13//!
14//! NOTE: World space is y-down (canvas/snapshot convention). Instance rows map
15//! quad corners to world coords; the camera uniform maps world to clip.
16//! Draw order is `z`-sorted stable (Bevy `z` semantics) *within* each blend
17//! range, then ranges draw alpha, multiply, additive: push order across
18//! blend modes is NOT preserved (an additive muzzle flash pushed under an
19//! alpha smoke sprite still composites over it). Budget `z` knowing the
20//! ranges reorder: interleaved alpha/additive scenes cannot rely on push
21//! order across the blend boundary. Each batch id owns its pipelines in
22//! `CallbackResources` (like `FullscreenPass`'s id map), so viewports +
23//! minimaps coexist.
24//!
25//! Lighting: group(2) carries a light map, always bound (the identity map when
26//! a batch names none), and the fragment shader consumes it as
27//! `color * modulate * map.a + map.rgb`. Name one with
28//! [`SpriteBatch::set_light_source`] and put a [`Light2dPass`] with the same id
29//! and camera in the same scene and target; the light pass publishes its map
30//! before any batch paints, whatever the node order.
31
32use std::collections::{HashMap, HashSet};
33use std::sync::{Arc, Mutex};
34
35use bytemuck::{Pod, Zeroable};
36use glam::Mat4;
37use repose_render_wgpu::{CallbackRenderPass, CallbackResources, ScreenDescriptor, WgpuCallback};
38use wgpu::util::DeviceExt;
39
40use super::{SpriteBlend, SpriteInstance};
41
42/// Texture sampling for atlas layers.
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
44pub enum TextureFilter {
45    /// Pixel-art crisp (nt default).
46    #[default]
47    Nearest,
48    Linear,
49}
50
51/// Batch construction parameters. Pages map 1:1 onto array layers.
52#[derive(Clone, Copy, Debug)]
53pub struct BatchDesc {
54    /// Square atlas layer edge in pixels.
55    pub layer_size: u32,
56    /// Array layer count (= max atlas pages).
57    pub layers: u32,
58    pub filter: TextureFilter,
59    /// Atlas content generation behind the uploads.
60    pub uploads_gen: u64,
61}
62
63impl Default for BatchDesc {
64    fn default() -> Self {
65        Self {
66            layer_size: 2048,
67            layers: 4,
68            filter: TextureFilter::Nearest,
69            uploads_gen: 0,
70        }
71    }
72}
73
74/// One pending atlas upload: blit `rgba` (tight `w`*`h`*4 bytes) into
75/// `page` at (`x`, `y`). Built from a `repame-atlas` drain by the game.
76#[derive(Clone, Debug)]
77pub struct AtlasUpload {
78    pub page: u32,
79    pub x: u32,
80    pub y: u32,
81    pub w: u32,
82    pub h: u32,
83    pub rgba: Vec<u8>,
84}
85
86impl AtlasUpload {
87    /// Bridge an atlas placement to a GPU upload. `rgba` must hold the
88    /// sprite's pixels row-major, `w`*`h`*4 bytes; mismatches are dropped
89    /// with a warning at `prepare` time.
90    pub fn from_write(write: &repame_atlas::AtlasWrite, rgba: Vec<u8>) -> Self {
91        Self {
92            page: write.page,
93            x: write.x,
94            y: write.y,
95            w: write.w,
96            h: write.h,
97            rgba,
98        }
99    }
100
101    /// 1x1 white texel upload for [`repame_atlas::Atlas::ensure_white`]:
102    /// pair with the drained write for the white key (usually 1x1 at the
103    /// returned `x/y/page`). Sampling it gives solid tint (particles,
104    /// untextured quads) instead of random atlas art.
105    pub fn white(page: u32, x: u32, y: u32) -> Self {
106        Self {
107            page,
108            x,
109            y,
110            w: 1,
111            h: 1,
112            rgba: vec![255, 255, 255, 255],
113        }
114    }
115
116    /// White upload built straight from the drained [`repame_atlas::AtlasWrite`]
117    /// for the white key.
118    pub fn white_for(write: &repame_atlas::AtlasWrite) -> Self {
119        Self {
120            page: write.page,
121            x: write.x,
122            y: write.y,
123            w: write.w.max(1),
124            h: write.h.max(1),
125            rgba: vec![255; write.w.max(1) as usize * write.h.max(1) as usize * 4],
126        }
127    }
128}
129
130/// Transform rows mapping quad corners (-0.5..0.5) to world coords,
131/// honoring size, rotation, anchor, and mirror. Matches the canvas path
132/// pixel-for-pixel at the default anchor: corner (-0.5,-0.5) lands on
133/// `center - size / 2`.
134pub fn instance_rows(
135    center: [f32; 2],
136    size: [f32; 2],
137    rotation: f32,
138    anchor: [f32; 2],
139    flip_x: bool,
140    flip_y: bool,
141) -> ([f32; 4], [f32; 4]) {
142    let (c, s) = (rotation.cos(), rotation.sin());
143    let sx = if flip_x { -size[0] } else { size[0] };
144    let sy = if flip_y { -size[1] } else { size[1] };
145    // Normalized offset of the anchor from the quad middle: the anchor
146    // point itself must land on `center`.
147    let (ax, ay) = (0.5 - anchor[0], 0.5 - anchor[1]);
148    (
149        [c * sx, -s * sy, 0.0, center[0] + c * sx * ax - s * sy * ay],
150        [s * sx, c * sy, 0.0, center[1] + s * sx * ax + c * sy * ay],
151    )
152}
153
154/// UV rect for one cell of a sprite-sheet grid: `hframes` columns by
155/// `vframes` rows, `frame` counted row-major from the top-left.
156///
157/// Returns `(uv_min, uv_max)` normalized to `0..1`, ready for
158/// [`SpriteInstance`] `uv_min`/`uv_max`. The grid
159/// covers the whole texture: cell `(col, row)` spans
160/// `col/hframes..(col+1)/hframes` by `row/vframes..(row+1)/vframes`.
161///
162/// - Out-of-range `frame` values clamp to the last cell instead of
163///   wrapping; advance the frame index with your animation clock.
164/// - Degenerate grids (`hframes` or `vframes` of `0`) yield the full
165///   texture, matching a single-frame sprite.
166///
167/// ```rust
168/// use repame_view2d::{frame_uv, sprite_aabb};
169///
170/// // 4x2 sheet: frame 5 is column 1, row 1.
171/// let (mn, mx) = frame_uv(4, 2, 5);
172/// assert_eq!(mn, [0.25, 0.5]);
173/// assert_eq!(mx, [0.5, 1.0]);
174/// ```
175pub fn frame_uv(hframes: u32, vframes: u32, frame: u32) -> ([f32; 2], [f32; 2]) {
176    let hf = hframes.max(1);
177    let vf = vframes.max(1);
178    let f = frame.min(hf * vf - 1);
179    let col = f % hf;
180    let row = f / hf;
181    (
182        [col as f32 / hf as f32, row as f32 / vf as f32],
183        [(col + 1) as f32 / hf as f32, (row + 1) as f32 / vf as f32],
184    )
185}
186
187/// World-space axis-aligned bounds of a sprite quad.
188///
189/// Returns `([min_x, min_y], [max_x, max_y])` through the same
190/// [`instance_rows`] math as the GPU batch, so the box matches the drawn
191/// quad: exact for unrotated sprites, the outer box for rotated ones.
192/// `flip_x`/`flip_y` do not change the box (mirroring preserves extents).
193///
194/// Useful for click hit-testing and layout: a press at world point `p`
195/// hits the sprite when `min <= p <= max`.
196///
197/// ```rust
198/// use repame_view2d::{frame_uv, sprite_aabb};
199///
200/// let (mn, mx) = sprite_aabb([400.0, 300.0], [64.0, 80.0], 0.0, [0.5, 0.5], false, false);
201/// assert_eq!(mn, [368.0, 260.0]);
202/// assert_eq!(mx, [432.0, 340.0]);
203/// ```
204pub fn sprite_aabb(
205    center: [f32; 2],
206    size: [f32; 2],
207    rotation: f32,
208    anchor: [f32; 2],
209    flip_x: bool,
210    flip_y: bool,
211) -> ([f32; 2], [f32; 2]) {
212    let (row0, row1) = instance_rows(center, size, rotation, anchor, flip_x, flip_y);
213    let mut min = [f32::INFINITY, f32::INFINITY];
214    let mut max = [f32::NEG_INFINITY, f32::NEG_INFINITY];
215    for corner in [[-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]] {
216        let x = row0[0] * corner[0] + row0[1] * corner[1] + row0[3];
217        let y = row1[0] * corner[0] + row1[1] * corner[1] + row1[3];
218        min[0] = min[0].min(x);
219        min[1] = min[1].min(y);
220        max[0] = max[0].max(x);
221        max[1] = max[1].max(y);
222    }
223    (min, max)
224}
225
226/// Y-down orthographic camera: world (0,0) is the top-left of the
227/// viewport, matching canvas orientation by construction. Standalone
228/// batches and tests use this directly; viewport snapshots frame through
229/// `fit_view_proj` (contain-fit + look) instead.
230pub fn screen_camera(viewport_px: [f32; 2]) -> Mat4 {
231    // Right-handed, 0..1 depth: matches wgpu NDC.
232    glam::camera::rh::proj::directx::orthographic(
233        0.0,
234        viewport_px[0].max(1.0),
235        viewport_px[1].max(1.0),
236        0.0,
237        -1000.0,
238        1000.0,
239    )
240}
241
242#[repr(C)]
243#[derive(Clone, Copy, Pod, Zeroable)]
244struct CameraUniform {
245    view_proj: [[f32; 4]; 4],
246}
247
248#[repr(C)]
249#[derive(Clone, Copy, Pod, Zeroable)]
250struct BatchInstance {
251    row0: [f32; 4],
252    row1: [f32; 4],
253    uv_min: [f32; 2],
254    uv_max: [f32; 2],
255    tint: [f32; 4],
256    page: f32,
257    z: f32,
258    flags: u32,
259    /// Half a texel in normalized UV, used to inset the UV rect to texel
260    /// centres in the vertex shader. Zero disables the inset.
261    texel: f32,
262    /// Light layer to sample, resolved from the mask on push. `32` reads the
263    /// identity layer.
264    layer: u32,
265}
266
267// Locked to `shaders/sprite.wgsl::Instance` (row0@0, row1@16,
268// uv_min@32, uv_max@40, tint@48, page@64, z@68, flags@72, texel@76,
269// layer@80; stride 84).
270// If this fires, update the WGSL offsets and the vertex buffer layout
271// below together.
272const _: () = assert!(size_of::<BatchInstance>() == 84);
273
274/// Group 2 of the sprite shaders: the light map an instance's layer reads.
275/// Matches the WGSL `Lightmap` struct (48 bytes).
276#[repr(C)]
277#[derive(Clone, Copy, Pod, Zeroable)]
278struct LightmapUniform {
279    /// `world * xform.xy + xform.zw` is the light map uv.
280    xform: [f32; 4],
281    /// rgb modulates the item colour before light; a is unused.
282    modulate: [f32; 4],
283    /// x: highest layer an instance may sample (the identity layer).
284    layer: [u32; 4],
285}
286
287const _: () = assert!(size_of::<LightmapUniform>() == 48);
288
289/// Identity light map: `(rgb = 0, a = 1)` on every texel, so an unlit batch
290/// multiplies by one and adds nothing. Two layers because a one-layer array
291/// texture is unsafe to sample on GL/ANGLE (see [`atlas_shape`]).
292const IDENTITY_LIGHTMAP_LAYERS: u32 = 2;
293
294/// Per-frame snapshot batch. `Send + Sync` so it can cross into the
295/// compositor thread via [`repose_render_wgpu::Callback`].
296///
297/// Each batch id owns its pipelines/instances in `CallbackResources`
298/// (like `FullscreenPass`'s id map). Re-keying the atlas (a new
299/// [`BatchDesc`] or `uploads_gen`) drops its contents; the game re-fills
300/// it with the uploads that came with the new descriptor.
301pub struct SpriteBatch {
302    id: String,
303    desc: BatchDesc,
304    camera: [[f32; 4]; 4],
305    instances: Vec<BatchInstance>,
306    uploads: Vec<AtlasUpload>,
307    light_source: Option<String>,
308    light_modulate: [f32; 3],
309}
310
311impl SpriteBatch {
312    pub fn new(desc: BatchDesc) -> Self {
313        Self::with_id("sprite_batch.default", desc)
314    }
315
316    pub fn with_id(id: impl Into<String>, desc: BatchDesc) -> Self {
317        Self {
318            id: id.into(),
319            desc,
320            camera: Mat4::IDENTITY.to_cols_array_2d(),
321            instances: Vec::new(),
322            uploads: Vec::new(),
323            light_source: None,
324            light_modulate: [1.0, 1.0, 1.0],
325        }
326    }
327
328    pub fn id(&self) -> &str {
329        &self.id
330    }
331
332    pub fn clear(&mut self) {
333        self.instances.clear();
334        self.uploads.clear();
335    }
336
337    pub fn len(&self) -> usize {
338        self.instances.len()
339    }
340
341    pub fn is_empty(&self) -> bool {
342        self.instances.is_empty()
343    }
344
345    /// View-projection matrix, y-down screen convention (see
346    /// [`screen_camera`]).
347    pub fn set_camera(&mut self, view_proj: Mat4) {
348        self.camera = view_proj.to_cols_array_2d();
349    }
350
351    /// Queue atlas uploads, applied in the next `prepare`.
352    pub fn upload(&mut self, upload: AtlasUpload) {
353        self.uploads.push(upload);
354    }
355
356    /// Queue several uploads at once (per-frame atlas drains).
357    pub fn extend_uploads(&mut self, uploads: impl IntoIterator<Item = AtlasUpload>) {
358        self.uploads.extend(uploads);
359    }
360
361    /// Light every sprite in this batch from the light map of the
362    /// [`Light2dPass`](crate::Light2dPass) with this id.
363    ///
364    /// The pass and the batch must share one camera
365    /// ([`set_camera`](Self::set_camera) on both); the light map is published
366    /// as a world-space rect, so a batch drawn into any rectangle of the same
367    /// target lines up without further setup. A batch whose pass has not
368    /// prepared yet draws unlit for that frame.
369    pub fn set_light_source(&mut self, id: impl Into<String>) {
370        self.light_source = Some(id.into());
371    }
372
373    /// Draw unlit: the identity light map, modulation ignored.
374    pub fn clear_light_source(&mut self) {
375        self.light_source = None;
376    }
377
378    /// Scene darkness for this batch: multiplies every sprite's colour before
379    /// the light map adds light. `[1.0; 3]` (default) is neutral and `[0.0; 3]`
380    /// is black; a batch with no light source ignores it. Values are clamped to
381    /// `0..` and a non-finite channel falls back to `1.0`, so one bad frame
382    /// cannot blacken or NaN the whole batch.
383    pub fn set_light_modulate(&mut self, rgb: [f32; 3]) {
384        self.light_modulate =
385            rgb.map(|c| if c.is_finite() { c.max(0.0) } else { 1.0 });
386    }
387
388    /// Push one textured quad.
389    #[allow(clippy::too_many_arguments)]
390    pub fn push(
391        &mut self,
392        center: [f32; 2],
393        size: [f32; 2],
394        rotation: f32,
395        anchor: [f32; 2],
396        flip_x: bool,
397        flip_y: bool,
398        uv_min: [f32; 2],
399        uv_max: [f32; 2],
400        tint: [f32; 4],
401        page: u32,
402    ) {
403        self.push_blended(
404            center,
405            size,
406            rotation,
407            anchor,
408            flip_x,
409            flip_y,
410            uv_min,
411            uv_max,
412            tint,
413            page,
414            0.0,
415            SpriteBlend::Alpha,
416        );
417    }
418
419    /// Push one textured quad on an explicit light layer.
420    #[allow(clippy::too_many_arguments)]
421    pub fn push_masked(
422        &mut self,
423        center: [f32; 2],
424        size: [f32; 2],
425        rotation: f32,
426        anchor: [f32; 2],
427        flip_x: bool,
428        flip_y: bool,
429        uv_min: [f32; 2],
430        uv_max: [f32; 2],
431        tint: [f32; 4],
432        page: u32,
433        light_mask: u32,
434    ) {
435        self.push_blended_masked(
436            center,
437            size,
438            rotation,
439            anchor,
440            flip_x,
441            flip_y,
442            uv_min,
443            uv_max,
444            tint,
445            page,
446            0.0,
447            SpriteBlend::Alpha,
448            light_mask,
449        );
450    }
451
452    /// Push with explicit `z` + blend; lit by layer 0 (light mask `1`). Use
453    /// [`Self::push_blended_masked`] to put the sprite on another layer.
454    #[allow(clippy::too_many_arguments)]
455    pub fn push_blended(
456        &mut self,
457        center: [f32; 2],
458        size: [f32; 2],
459        rotation: f32,
460        anchor: [f32; 2],
461        flip_x: bool,
462        flip_y: bool,
463        uv_min: [f32; 2],
464        uv_max: [f32; 2],
465        tint: [f32; 4],
466        page: u32,
467        z: f32,
468        blend: SpriteBlend,
469    ) {
470        self.push_blended_masked(
471            center, size, rotation, anchor, flip_x, flip_y, uv_min, uv_max, tint, page, z, blend,
472            1,
473        );
474    }
475
476    /// Push with explicit `z`, blend, and light layer bits.
477    #[allow(clippy::too_many_arguments)]
478    pub fn push_blended_masked(
479        &mut self,
480        center: [f32; 2],
481        size: [f32; 2],
482        rotation: f32,
483        anchor: [f32; 2],
484        flip_x: bool,
485        flip_y: bool,
486        uv_min: [f32; 2],
487        uv_max: [f32; 2],
488        tint: [f32; 4],
489        page: u32,
490        z: f32,
491        blend: SpriteBlend,
492        light_mask: u32,
493    ) {
494        let (row0, row1) = instance_rows(center, size, rotation, anchor, flip_x, flip_y);
495        let flags = match blend {
496            SpriteBlend::Alpha => 0,
497            SpriteBlend::Additive => 1,
498            SpriteBlend::Multiply => 2,
499        };
500        self.instances.push(BatchInstance {
501            row0,
502            row1,
503            uv_min,
504            uv_max,
505            tint,
506            page: page as f32,
507            z,
508            flags,
509            texel: 0.5 / self.desc.layer_size.max(1) as f32,
510            layer: light_mask.trailing_zeros(),
511        });
512    }
513
514    /// Bridge a snapshot sprite into the batch.
515    ///
516    /// The atlas and the render target are both `Rgba8UnormSrgb`, so the
517    /// sampled texel and the written pixel are already in linear space and
518    /// the tint has to be linearized here; [`Self::push`] takes one
519    /// directly.
520    pub fn push_sprite(&mut self, s: &SpriteInstance) {
521        self.push_blended_masked(
522            [s.center.x, s.center.y],
523            [s.size.x, s.size.y],
524            s.rotation,
525            [s.anchor.x, s.anchor.y],
526            s.flip_x,
527            s.flip_y,
528            [s.uv_min.x, s.uv_min.y],
529            [s.uv_max.x, s.uv_max.y],
530            super::rgba8(s.color).to_linear(),
531            s.page,
532            s.z,
533            s.blend,
534            s.light_mask,
535        );
536    }
537}
538
539#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
540struct AtlasDescriptor {
541    layer_size: u32,
542    layers: u32,
543    filter: TextureFilter,
544}
545
546#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
547struct AtlasKey {
548    descriptor: AtlasDescriptor,
549    generation: u64,
550}
551
552struct AtlasLayout {
553    tex_layout: wgpu::BindGroupLayout,
554    sampler: wgpu::Sampler,
555}
556
557struct AtlasResources {
558    texture: wgpu::Texture,
559    tex_bind: wgpu::BindGroup,
560    applied_gen: Arc<Mutex<Option<u64>>>,
561    /// Generation already reported as unfilled, so the report lands once per
562    /// generation rather than once per frame.
563    starved_gen: Arc<Mutex<Option<u64>>>,
564}
565
566struct BatchEntry {
567    key: (wgpu::TextureFormat, u32, u32, u32, TextureFilter),
568    pipeline_alpha: wgpu::RenderPipeline,
569    pipeline_multiply: wgpu::RenderPipeline,
570    pipeline_additive: wgpu::RenderPipeline,
571    corners: wgpu::Buffer,
572    instances: wgpu::Buffer,
573    instance_cap: usize,
574    /// Sorted ranges: `0..alpha` alpha, `alpha..multiply_end` multiply,
575    /// `multiply_end..total` additive.
576    last_alpha: u32,
577    last_multiply_end: u32,
578    last_total: u32,
579    camera: wgpu::Buffer,
580    cam_bind: wgpu::BindGroup,
581    atlas: Arc<AtlasResources>,
582    atlas_key: AtlasKey,
583    /// Per-batch light uniforms (world -> uv, modulate, layer clamp).
584    light_uniform: wgpu::Buffer,
585    /// Group 2 for the sprite pipelines: the light map this batch reads, or
586    /// the shared identity map when it has no light source.
587    light_bind: Arc<wgpu::BindGroup>,
588    /// What `light_bind` was built from, so it is rebuilt only when the light
589    /// map's texture changes (the rect rides in the uniform instead).
590    light_key: Option<(String, u64)>,
591    /// Whether the missing-light-map warning was already logged, so a broken
592    /// setup is loud once instead of every frame.
593    light_starved: bool,
594}
595
596struct BatchResources {
597    batches: HashMap<String, BatchEntry>,
598    atlases: HashMap<AtlasKey, Arc<AtlasResources>>,
599    layouts: HashMap<AtlasDescriptor, Arc<AtlasLayout>>,
600    light_layout: wgpu::BindGroupLayout,
601    light_sampler: wgpu::Sampler,
602    /// Kept alive for `identity_bind`, which holds only the view.
603    #[allow(dead_code)]
604    identity_lightmap: wgpu::Texture,
605    identity_bind: Arc<wgpu::BindGroup>,
606}
607
608impl BatchResources {
609    fn prune_atlases(&mut self) {
610        let live: HashSet<AtlasKey> = self.batches.values().map(|entry| entry.atlas_key).collect();
611        self.atlases.retain(|key, _| live.contains(key));
612    }
613}
614
615const CORNERS: &[f32] = &[
616    -0.5, -0.5, //
617    0.5, -0.5, //
618    0.5, 0.5, //
619    -0.5, -0.5, //
620    0.5, 0.5, //
621    -0.5, 0.5, //
622];
623
624fn sampler_desc(filter: TextureFilter) -> wgpu::SamplerDescriptor<'static> {
625    let f = match filter {
626        TextureFilter::Nearest => wgpu::FilterMode::Nearest,
627        TextureFilter::Linear => wgpu::FilterMode::Linear,
628    };
629    let m = match filter {
630        TextureFilter::Nearest => wgpu::MipmapFilterMode::Nearest,
631        TextureFilter::Linear => wgpu::MipmapFilterMode::Linear,
632    };
633    wgpu::SamplerDescriptor {
634        label: Some("sprite_batch_sampler"),
635        address_mode_u: wgpu::AddressMode::ClampToEdge,
636        address_mode_v: wgpu::AddressMode::ClampToEdge,
637        address_mode_w: wgpu::AddressMode::ClampToEdge,
638        mag_filter: f,
639        min_filter: f,
640        mipmap_filter: m,
641        lod_min_clamp: 0.0,
642        lod_max_clamp: 1.0,
643        compare: None,
644        anisotropy_clamp: 1,
645        border_color: None,
646    }
647}
648
649/// The atlas view dimension and the shader that matches it.
650///
651/// A single-layer atlas is a plain `D2` texture. GL/ANGLE (which is what a
652/// browser actually hands wgpu) assumes `D2` for a one-layer texture and
653/// misreports a `D2Array` view of it, after which sampling returns black and
654/// every sprite disappears with no validation error anywhere. So a one-layer
655/// atlas is never made an array in the first place.
656pub(crate) fn atlas_shape(layers: u32) -> (wgpu::TextureViewDimension, bool) {
657    if layers <= 1 {
658        (wgpu::TextureViewDimension::D2, false)
659    } else {
660        (wgpu::TextureViewDimension::D2Array, true)
661    }
662}
663
664pub(crate) fn sprite_shader(layers: u32) -> &'static str {
665    if atlas_shape(layers).1 {
666        include_str!("../shaders/sprite.wgsl")
667    } else {
668        include_str!("../shaders/sprite_single.wgsl")
669    }
670}
671
672/// Group 2 layout shared by every batch: the light map array, its sampler, and
673/// the per-batch light uniform.
674fn create_light_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
675    device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
676        label: Some("sprite_batch_light_bgl"),
677        entries: &[
678            wgpu::BindGroupLayoutEntry {
679                binding: 0,
680                visibility: wgpu::ShaderStages::FRAGMENT,
681                ty: wgpu::BindingType::Texture {
682                    sample_type: wgpu::TextureSampleType::Float { filterable: true },
683                    view_dimension: wgpu::TextureViewDimension::D2Array,
684                    multisampled: false,
685                },
686                count: None,
687            },
688            wgpu::BindGroupLayoutEntry {
689                binding: 1,
690                visibility: wgpu::ShaderStages::FRAGMENT,
691                ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
692                count: None,
693            },
694            wgpu::BindGroupLayoutEntry {
695                binding: 2,
696                visibility: wgpu::ShaderStages::FRAGMENT,
697                ty: wgpu::BindingType::Buffer {
698                    ty: wgpu::BufferBindingType::Uniform,
699                    has_dynamic_offset: false,
700                    min_binding_size: None,
701                },
702                count: None,
703            },
704        ],
705    })
706}
707
708/// The identity light map every batch binds until it names a real one: a
709/// `1x1` texel of `(rgb = 0, a = 1)`, which the sprite shader's
710/// `color * modulate * a + rgb` turns into plain `color`.
711fn create_identity_lightmap(
712    device: &wgpu::Device,
713    queue: &wgpu::Queue,
714    layout: &wgpu::BindGroupLayout,
715) -> (wgpu::Texture, Arc<wgpu::BindGroup>) {
716    let texture = device.create_texture(&wgpu::TextureDescriptor {
717        label: Some("sprite_batch_identity_lightmap"),
718        size: wgpu::Extent3d {
719            width: 1,
720            height: 1,
721            depth_or_array_layers: IDENTITY_LIGHTMAP_LAYERS,
722        },
723        mip_level_count: 1,
724        sample_count: 1,
725        dimension: wgpu::TextureDimension::D2,
726        format: wgpu::TextureFormat::Rgba8Unorm,
727        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
728        view_formats: &[],
729    });
730    queue.write_texture(
731        wgpu::TexelCopyTextureInfo {
732            texture: &texture,
733            mip_level: 0,
734            origin: wgpu::Origin3d::ZERO,
735            aspect: wgpu::TextureAspect::All,
736        },
737        &[0, 0, 0, 255, 0, 0, 0, 255],
738        wgpu::TexelCopyBufferLayout {
739            offset: 0,
740            bytes_per_row: Some(4),
741            rows_per_image: Some(1),
742        },
743        wgpu::Extent3d {
744            width: 1,
745            height: 1,
746            depth_or_array_layers: IDENTITY_LIGHTMAP_LAYERS,
747        },
748    );
749    let view = texture.create_view(&wgpu::TextureViewDescriptor {
750        dimension: Some(wgpu::TextureViewDimension::D2Array),
751        ..Default::default()
752    });
753    let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
754        label: Some("sprite_batch_identity_light"),
755        contents: bytemuck::bytes_of(&LightmapUniform {
756            xform: [0.0; 4],
757            modulate: [1.0, 1.0, 1.0, 0.0],
758            layer: [0; 4],
759        }),
760        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
761    });
762    let sampler = device.create_sampler(&sampler_desc(TextureFilter::Nearest));
763    let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
764        label: Some("sprite_batch_identity_light_bg"),
765        layout,
766        entries: &[
767            wgpu::BindGroupEntry {
768                binding: 0,
769                resource: wgpu::BindingResource::TextureView(&view),
770            },
771            wgpu::BindGroupEntry {
772                binding: 1,
773                resource: wgpu::BindingResource::Sampler(&sampler),
774            },
775            wgpu::BindGroupEntry {
776                binding: 2,
777                resource: uniform.as_entire_binding(),
778            },
779        ],
780    });
781    (texture, Arc::new(bind))
782}
783
784fn create_atlas_layout(device: &wgpu::Device, filter: TextureFilter, layers: u32) -> AtlasLayout {    let (dimension, _) = atlas_shape(layers);
785    let sampler = device.create_sampler(&sampler_desc(filter));
786    let tex_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
787        label: Some("sprite_batch_tex_bgl"),
788        entries: &[
789            wgpu::BindGroupLayoutEntry {
790                binding: 0,
791                visibility: wgpu::ShaderStages::FRAGMENT,
792                ty: wgpu::BindingType::Texture {
793                    sample_type: wgpu::TextureSampleType::Float { filterable: true },
794                    view_dimension: dimension,
795                    multisampled: false,
796                },
797                count: None,
798            },
799            wgpu::BindGroupLayoutEntry {
800                binding: 1,
801                visibility: wgpu::ShaderStages::FRAGMENT,
802                ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
803                count: None,
804            },
805        ],
806    });
807    AtlasLayout {
808        tex_layout,
809        sampler,
810    }
811}
812
813fn create_atlas(device: &wgpu::Device, key: AtlasKey, layout: &AtlasLayout) -> AtlasResources {
814    let descriptor = key.descriptor;
815    let texture = device.create_texture(&wgpu::TextureDescriptor {
816        label: Some("sprite_batch_atlas"),
817        size: wgpu::Extent3d {
818            width: descriptor.layer_size,
819            height: descriptor.layer_size,
820            depth_or_array_layers: descriptor.layers,
821        },
822        mip_level_count: 1,
823        sample_count: 1,
824        dimension: wgpu::TextureDimension::D2,
825        format: wgpu::TextureFormat::Rgba8UnormSrgb,
826        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
827        view_formats: &[],
828    });
829    let (dimension, _) = atlas_shape(descriptor.layers);
830    let view = texture.create_view(&wgpu::TextureViewDescriptor {
831        dimension: Some(dimension),
832        ..Default::default()
833    });
834    let tex_bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
835        label: Some("sprite_batch_tex_bg"),
836        layout: &layout.tex_layout,
837        entries: &[
838            wgpu::BindGroupEntry {
839                binding: 0,
840                resource: wgpu::BindingResource::TextureView(&view),
841            },
842            wgpu::BindGroupEntry {
843                binding: 1,
844                resource: wgpu::BindingResource::Sampler(&layout.sampler),
845            },
846        ],
847    });
848    AtlasResources {
849        texture,
850        tex_bind,
851        applied_gen: Arc::new(Mutex::new(None)),
852        starved_gen: Arc::new(Mutex::new(None)),
853    }
854}
855
856impl SpriteBatch {
857    fn ensure_resources(
858        &self,
859        device: &wgpu::Device,
860        queue: &wgpu::Queue,
861        screen: &ScreenDescriptor,
862        resources: &mut CallbackResources,
863    ) {
864        let descriptor = AtlasDescriptor {
865            layer_size: self.desc.layer_size,
866            layers: self.desc.layers,
867            filter: self.desc.filter,
868        };
869        let atlas_key = AtlasKey {
870            descriptor,
871            generation: self.desc.uploads_gen,
872        };
873        let key = (
874            screen.target_format,
875            screen.sample_count,
876            self.desc.layer_size,
877            self.desc.layers,
878            self.desc.filter,
879        );
880        if resources.get::<BatchResources>().is_none() {
881            let light_layout = create_light_layout(device);
882            let (identity_lightmap, identity_bind) =
883                create_identity_lightmap(device, queue, &light_layout);
884            resources.insert(BatchResources {
885                batches: HashMap::new(),
886                atlases: HashMap::new(),
887                layouts: HashMap::new(),
888                light_layout,
889                light_sampler: device.create_sampler(&sampler_desc(TextureFilter::Linear)),
890                identity_lightmap,
891                identity_bind,
892            });
893        }
894        let layout = resources
895            .get_mut::<BatchResources>()
896            .expect("batch resources initialized")
897            .layouts
898            .entry(descriptor)
899            .or_insert_with(|| {
900                Arc::new(create_atlas_layout(
901                    device,
902                    descriptor.filter,
903                    descriptor.layers,
904                ))
905            })
906            .clone();
907        let atlas = resources
908            .get_mut::<BatchResources>()
909            .expect("batch resources initialized")
910            .atlases
911            .entry(atlas_key)
912            .or_insert_with(|| Arc::new(create_atlas(device, atlas_key, &layout)))
913            .clone();
914        let needs = resources
915            .get::<BatchResources>()
916            .expect("batch resources initialized")
917            .batches
918            .get(self.id.as_str())
919            .is_none_or(|entry| entry.key != key);
920        if !needs {
921            if let Some(all) = resources.get_mut::<BatchResources>()
922                && let Some(entry) = all.batches.get_mut(self.id.as_str())
923            {
924                entry.atlas = atlas;
925                entry.atlas_key = atlas_key;
926                all.prune_atlases();
927            }
928            return;
929        }
930        if resources
931            .get::<BatchResources>()
932            .is_some_and(|all| all.batches.contains_key(self.id.as_str()))
933        {
934            log::warn!(
935                "sprite_batch[{}]: rebuilding pipeline for format/sample/descriptor change",
936                self.id
937            );
938        }
939        let light_layout = resources
940            .get::<BatchResources>()
941            .expect("batch resources initialized")
942            .light_layout
943            .clone();
944        let light_uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
945            label: Some("sprite_batch_light_uniforms"),
946            contents: bytemuck::bytes_of(&LightmapUniform {
947                xform: [0.0; 4],
948                modulate: [1.0, 1.0, 1.0, 0.0],
949                layer: [0; 4],
950            }),
951            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
952        });
953        let light_bind = resources
954            .get::<BatchResources>()
955            .expect("batch resources initialized")
956            .identity_bind
957            .clone();
958        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
959            label: Some("sprite_batch"),
960            source: wgpu::ShaderSource::Wgsl(sprite_shader(self.desc.layers).into()),
961        });
962        let corners = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
963            label: Some("sprite_batch_corners"),
964            contents: bytemuck::cast_slice(CORNERS),
965            usage: wgpu::BufferUsages::VERTEX,
966        });
967        let camera = device.create_buffer(&wgpu::BufferDescriptor {
968            label: Some("sprite_batch_camera"),
969            size: 64,
970            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
971            mapped_at_creation: false,
972        });
973        let instances = device.create_buffer(&wgpu::BufferDescriptor {
974            label: Some("sprite_batch_instances"),
975            size: (self.instances.len().max(1) * size_of::<BatchInstance>()) as u64,
976            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
977            mapped_at_creation: false,
978        });
979        let cam_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
980            label: Some("sprite_batch_cam_bgl"),
981            entries: &[wgpu::BindGroupLayoutEntry {
982                binding: 0,
983                visibility: wgpu::ShaderStages::VERTEX,
984                ty: wgpu::BindingType::Buffer {
985                    ty: wgpu::BufferBindingType::Uniform,
986                    has_dynamic_offset: false,
987                    min_binding_size: None,
988                },
989                count: None,
990            }],
991        });
992        let cam_bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
993            label: Some("sprite_batch_cam_bg"),
994            layout: &cam_layout,
995            entries: &[wgpu::BindGroupEntry {
996                binding: 0,
997                resource: camera.as_entire_binding(),
998            }],
999        });
1000        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1001            label: Some("sprite_batch_pl"),
1002            bind_group_layouts: &[
1003                Some(&cam_layout),
1004                Some(&layout.tex_layout),
1005                Some(&light_layout),
1006            ],
1007            immediate_size: 0,
1008        });
1009        let vertex_buffers = [
1010            Some(wgpu::VertexBufferLayout {
1011                array_stride: 8,
1012                step_mode: wgpu::VertexStepMode::Vertex,
1013                attributes: &[wgpu::VertexAttribute {
1014                    format: wgpu::VertexFormat::Float32x2,
1015                    offset: 0,
1016                    shader_location: 0,
1017                }],
1018            }),
1019            Some(wgpu::VertexBufferLayout {
1020                array_stride: size_of::<BatchInstance>() as u64,
1021                step_mode: wgpu::VertexStepMode::Instance,
1022                attributes: &[
1023                    wgpu::VertexAttribute {
1024                        format: wgpu::VertexFormat::Float32x4,
1025                        offset: 0,
1026                        shader_location: 2,
1027                    },
1028                    wgpu::VertexAttribute {
1029                        format: wgpu::VertexFormat::Float32x4,
1030                        offset: 16,
1031                        shader_location: 3,
1032                    },
1033                    wgpu::VertexAttribute {
1034                        format: wgpu::VertexFormat::Float32x2,
1035                        offset: 32,
1036                        shader_location: 4,
1037                    },
1038                    wgpu::VertexAttribute {
1039                        format: wgpu::VertexFormat::Float32x2,
1040                        offset: 40,
1041                        shader_location: 5,
1042                    },
1043                    wgpu::VertexAttribute {
1044                        format: wgpu::VertexFormat::Float32x4,
1045                        offset: 48,
1046                        shader_location: 6,
1047                    },
1048                    wgpu::VertexAttribute {
1049                        format: wgpu::VertexFormat::Float32,
1050                        offset: 64,
1051                        shader_location: 7,
1052                    },
1053                    wgpu::VertexAttribute {
1054                        format: wgpu::VertexFormat::Float32,
1055                        offset: 68,
1056                        shader_location: 8,
1057                    },
1058                    wgpu::VertexAttribute {
1059                        format: wgpu::VertexFormat::Uint32,
1060                        offset: 72,
1061                        shader_location: 9,
1062                    },
1063                    wgpu::VertexAttribute {
1064                        format: wgpu::VertexFormat::Float32,
1065                        offset: 76,
1066                        shader_location: 10,
1067                    },
1068                    wgpu::VertexAttribute {
1069                        format: wgpu::VertexFormat::Uint32,
1070                        offset: 80,
1071                        shader_location: 11,
1072                    },
1073                ],
1074            }),
1075        ];
1076        let mk_pipeline = |label: &'static str, blend: wgpu::BlendState| {
1077            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1078                label: Some(label),
1079                layout: Some(&pipeline_layout),
1080                vertex: wgpu::VertexState {
1081                    module: &shader,
1082                    entry_point: Some("vs_main"),
1083                    buffers: &vertex_buffers,
1084                    compilation_options: Default::default(),
1085                },
1086                fragment: Some(wgpu::FragmentState {
1087                    module: &shader,
1088                    entry_point: Some("fs_main"),
1089                    targets: &[Some(wgpu::ColorTargetState {
1090                        format: screen.target_format,
1091                        blend: Some(blend),
1092                        write_mask: wgpu::ColorWrites::ALL,
1093                    })],
1094                    compilation_options: Default::default(),
1095                }),
1096                primitive: wgpu::PrimitiveState {
1097                    topology: wgpu::PrimitiveTopology::TriangleList,
1098                    ..Default::default()
1099                },
1100                depth_stencil: Some(wgpu::DepthStencilState {
1101                    format: wgpu::TextureFormat::Depth24PlusStencil8,
1102                    depth_write_enabled: Some(false),
1103                    depth_compare: Some(wgpu::CompareFunction::Always),
1104                    stencil: wgpu::StencilState {
1105                        front: wgpu::StencilFaceState {
1106                            compare: wgpu::CompareFunction::LessEqual,
1107                            ..Default::default()
1108                        },
1109                        back: wgpu::StencilFaceState {
1110                            compare: wgpu::CompareFunction::LessEqual,
1111                            ..Default::default()
1112                        },
1113                        ..Default::default()
1114                    },
1115                    bias: wgpu::DepthBiasState::default(),
1116                }),
1117                multisample: wgpu::MultisampleState {
1118                    count: screen.sample_count,
1119                    mask: !0,
1120                    alpha_to_coverage_enabled: false,
1121                },
1122                multiview_mask: None,
1123                cache: None,
1124            })
1125        };
1126        let pipeline_alpha = mk_pipeline("sprite_batch_pipeline", wgpu::BlendState::ALPHA_BLENDING);
1127        let pipeline_multiply = mk_pipeline(
1128            "sprite_batch_pipeline_mul",
1129            wgpu::BlendState {
1130                color: wgpu::BlendComponent {
1131                    src_factor: wgpu::BlendFactor::Dst,
1132                    dst_factor: wgpu::BlendFactor::Zero,
1133                    operation: wgpu::BlendOperation::Add,
1134                },
1135                alpha: wgpu::BlendComponent::OVER,
1136            },
1137        );
1138        let pipeline_additive = mk_pipeline(
1139            "sprite_batch_pipeline_add",
1140            wgpu::BlendState {
1141                color: wgpu::BlendComponent {
1142                    src_factor: wgpu::BlendFactor::SrcAlpha,
1143                    dst_factor: wgpu::BlendFactor::One,
1144                    operation: wgpu::BlendOperation::Add,
1145                },
1146                alpha: wgpu::BlendComponent {
1147                    src_factor: wgpu::BlendFactor::One,
1148                    dst_factor: wgpu::BlendFactor::One,
1149                    operation: wgpu::BlendOperation::Add,
1150                },
1151            },
1152        );
1153        let entry = BatchEntry {
1154            key,
1155            pipeline_alpha,
1156            pipeline_multiply,
1157            pipeline_additive,
1158            corners,
1159            instances,
1160            instance_cap: self.instances.len().max(1),
1161            last_alpha: 0,
1162            last_multiply_end: 0,
1163            last_total: 0,
1164            camera,
1165            cam_bind,
1166            atlas,
1167            atlas_key,
1168            light_uniform,
1169            light_bind,
1170            light_key: None,
1171            light_starved: false,
1172        };
1173        resources
1174            .get_mut::<BatchResources>()
1175            .expect("batch resources initialized")
1176            .batches
1177            .insert(self.id.clone(), entry);
1178        resources
1179            .get_mut::<BatchResources>()
1180            .expect("batch resources initialized")
1181            .prune_atlases();
1182    }
1183
1184    /// Record this batch's instance counts after uploading. Split out so
1185    /// sibling payloads (e.g. viewport views rebuilding the batch per
1186    /// frame) can share one prepared pipeline.
1187    fn finish_prepare(
1188        &self,
1189        alpha: u32,
1190        multiply_end: u32,
1191        total: u32,
1192        resources: &mut CallbackResources,
1193    ) {
1194        if let Some(all) = resources.get_mut::<BatchResources>()
1195            && let Some(res) = all.batches.get_mut(self.id.as_str())
1196        {
1197            res.last_alpha = alpha;
1198            res.last_multiply_end = multiply_end;
1199            res.last_total = total;
1200        }
1201    }
1202
1203    /// Point this batch at the light map the renderer's `finish_prepare` hook
1204    /// makes visible after every `prepare` has run, so scene order between a
1205    /// light pass and its consumers does not matter.
1206    ///
1207    /// Runs on the renderer's `finish_prepare`; also safe to call directly.
1208    pub fn resolve_lightmap(
1209        &self,
1210        device: &wgpu::Device,
1211        queue: &wgpu::Queue,
1212        resources: &mut CallbackResources,
1213    ) {
1214        let source = self.light_source.as_deref();
1215        let info = source.and_then(|id| super::lightpass::lookup_lightmap(resources, id));
1216        let Some(all) = resources.get_mut::<BatchResources>() else {
1217            return;
1218        };
1219        let Some(res) = all.batches.get_mut(self.id.as_str()) else {
1220            return;
1221        };
1222        if let Some(id) = source
1223            && info.is_none()
1224            && !res.light_starved
1225        {
1226            res.light_starved = true;
1227            log::warn!(
1228                "sprite_batch[{}]: no light map published by pass '{id}'; drawing unlit. \
1229                 The pass must be in the same scene and render into the same target as this batch.",
1230                self.id
1231            );
1232        }
1233        if info.is_some() {
1234            res.light_starved = false;
1235        }
1236        let key = match (&info, source) {
1237            (Some(info), Some(id)) => Some((id.to_string(), info.generation)),
1238            _ => None,
1239        };
1240        if res.light_key != key {
1241            res.light_key = key;
1242            res.light_bind = match &info {
1243                Some(info) => Arc::new(device.create_bind_group(&wgpu::BindGroupDescriptor {
1244                    label: Some("sprite_batch_light_bg"),
1245                    layout: &all.light_layout,
1246                    entries: &[
1247                        wgpu::BindGroupEntry {
1248                            binding: 0,
1249                            resource: wgpu::BindingResource::TextureView(&info.view),
1250                        },
1251                        wgpu::BindGroupEntry {
1252                            binding: 1,
1253                            resource: wgpu::BindingResource::Sampler(&all.light_sampler),
1254                        },
1255                        wgpu::BindGroupEntry {
1256                            binding: 2,
1257                            resource: res.light_uniform.as_entire_binding(),
1258                        },
1259                    ],
1260                })),
1261                None => all.identity_bind.clone(),
1262            };
1263        }
1264        // The world rect moves with the camera, so the uv transform is written
1265        // every frame; the bind group only changes when the map is recreated.
1266        let uniform = match &info {
1267            Some(info) => LightmapUniform {
1268                xform: [
1269                    1.0 / info.world_rect[2],
1270                    1.0 / info.world_rect[3],
1271                    -info.world_rect[0] / info.world_rect[2],
1272                    -info.world_rect[1] / info.world_rect[3],
1273                ],
1274                modulate: [
1275                    self.light_modulate[0],
1276                    self.light_modulate[1],
1277                    self.light_modulate[2],
1278                    0.0,
1279                ],
1280                layer: [info.layer_clamp, 0, 0, 0],
1281            },
1282            None => LightmapUniform {
1283                xform: [0.0; 4],
1284                modulate: [1.0, 1.0, 1.0, 0.0],
1285                layer: [0; 4],
1286            },
1287        };
1288        queue.write_buffer(&res.light_uniform, 0, bytemuck::bytes_of(&uniform));
1289    }
1290
1291    fn blend_group(flags: u32) -> u32 {
1292        match flags {
1293            1 => 2, // additive last
1294            2 => 1, // multiply middle
1295            _ => 0, // alpha first
1296        }
1297    }
1298
1299    /// Painter's order within one blend range: `z` ascending, with the
1300    /// push index breaking ties (stable for the producer's draw order).
1301    /// Across ranges the blend group dominates: all alpha draws before any
1302    /// multiply, all multiply before any additive, regardless of `z` or
1303    /// push order.
1304    /// `page` must NEVER participate: atlas page is a packing accident,
1305    /// and sorting on it reorders same-z sprites (bandit guns under
1306    /// bodies, bullet layers misaligned, camp floors over the vortex).
1307    fn sorted_instances(&self) -> (Vec<BatchInstance>, u32, u32) {
1308        let mut v: Vec<(usize, BatchInstance)> =
1309            self.instances.iter().copied().enumerate().collect();
1310        v.sort_by(|(ia, a), (ib, b)| {
1311            Self::blend_group(a.flags)
1312                .cmp(&Self::blend_group(b.flags))
1313                .then_with(|| a.z.total_cmp(&b.z).then_with(|| ia.cmp(ib)))
1314        });
1315        let v: Vec<BatchInstance> = v.into_iter().map(|(_, inst)| inst).collect();
1316        let alpha = v
1317            .iter()
1318            .take_while(|i| Self::blend_group(i.flags) == 0)
1319            .count() as u32;
1320        let multiply_end = alpha
1321            + v[alpha as usize..]
1322                .iter()
1323                .take_while(|i| Self::blend_group(i.flags) == 1)
1324                .count() as u32;
1325        (v, alpha, multiply_end)
1326    }
1327
1328    /// Game-owned passes can drive this batch into their OWN
1329    /// render target instead.
1330    pub fn prepare_with_uploads(
1331        &self,
1332        device: &wgpu::Device,
1333        queue: &wgpu::Queue,
1334        _encoder: &mut wgpu::CommandEncoder,
1335        screen: &ScreenDescriptor,
1336        resources: &mut CallbackResources,
1337        uploads: &[AtlasUpload],
1338    ) -> Vec<wgpu::CommandBuffer> {
1339        self.ensure_resources(device, queue, screen, resources);
1340        let (sorted, alpha, multiply_end) = self.sorted_instances();
1341        let total = sorted.len() as u32;
1342        let Some(all) = resources.get_mut::<BatchResources>() else {
1343            return Vec::new();
1344        };
1345        let Some(res) = all.batches.get_mut(self.id.as_str()) else {
1346            return Vec::new();
1347        };
1348
1349        if sorted.len() > res.instance_cap {
1350            let new_cap = sorted.len().next_power_of_two().max(64);
1351            res.instances = device.create_buffer(&wgpu::BufferDescriptor {
1352                label: Some("sprite_batch_instances"),
1353                size: (new_cap * size_of::<BatchInstance>()) as u64,
1354                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
1355                mapped_at_creation: false,
1356            });
1357            res.instance_cap = new_cap;
1358        }
1359        queue.write_buffer(
1360            &res.camera,
1361            0,
1362            bytemuck::cast_slice(&[CameraUniform {
1363                view_proj: self.camera,
1364            }]),
1365        );
1366        if !sorted.is_empty() {
1367            queue.write_buffer(&res.instances, 0, bytemuck::cast_slice(&sorted));
1368        }
1369        let atlas = res.atlas.clone();
1370        // The atlas trails `desc.uploads_gen` until the generation's uploads
1371        // have been written, and it cannot be drawn from before then.
1372        let atlas_behind = atlas
1373            .applied_gen
1374            .lock()
1375            .map(|generation| *generation != Some(self.desc.uploads_gen))
1376            .unwrap_or(true);
1377        if atlas_behind && uploads.is_empty() {
1378            self.report_atlas_starved(&atlas);
1379            self.finish_prepare(alpha, multiply_end, total, resources);
1380            return Vec::new();
1381        }
1382        let mut wrote_any = false;
1383        for up in uploads {
1384            if !atlas_behind {
1385                continue;
1386            }
1387            let expected = up.w as usize * up.h as usize * 4;
1388            if up.page >= self.desc.layers
1389                || up.x + up.w > self.desc.layer_size
1390                || up.y + up.h > self.desc.layer_size
1391                || up.rgba.len() != expected
1392            {
1393                log::warn!(
1394                    "sprite_batch: dropping out-of-range upload page={} {}x{}+{}+{} ({} bytes)",
1395                    up.page,
1396                    up.w,
1397                    up.h,
1398                    up.x,
1399                    up.y,
1400                    up.rgba.len()
1401                );
1402                continue;
1403            }
1404            queue.write_texture(
1405                wgpu::TexelCopyTextureInfo {
1406                    texture: &atlas.texture,
1407                    mip_level: 0,
1408                    origin: wgpu::Origin3d {
1409                        x: up.x,
1410                        y: up.y,
1411                        z: up.page,
1412                    },
1413                    aspect: wgpu::TextureAspect::All,
1414                },
1415                &up.rgba,
1416                wgpu::TexelCopyBufferLayout {
1417                    offset: 0,
1418                    bytes_per_row: Some(up.w * 4),
1419                    rows_per_image: Some(up.h),
1420                },
1421                wgpu::Extent3d {
1422                    width: up.w,
1423                    height: up.h,
1424                    depth_or_array_layers: 1,
1425                },
1426            );
1427            wrote_any = true;
1428        }
1429        if atlas_behind
1430            && wrote_any
1431            && let Ok(mut generation) = atlas.applied_gen.lock()
1432        {
1433            *generation = Some(self.desc.uploads_gen);
1434        }
1435        self.finish_prepare(alpha, multiply_end, total, resources);
1436        Vec::new()
1437    }
1438
1439    /// The atlas trails its descriptor and nothing is queued to fill it, so the
1440    /// batch draws nothing at all.
1441    fn report_atlas_starved(&self, atlas: &AtlasResources) {
1442        let Ok(mut reported) = atlas.starved_gen.lock() else {
1443            return;
1444        };
1445        if *reported == Some(self.desc.uploads_gen) {
1446            return;
1447        }
1448        *reported = Some(self.desc.uploads_gen);
1449        log::error!(
1450            "sprite_batch[{}]: atlas generation {} is unfilled and no uploads arrived, \
1451             drawing nothing; pass that generation's uploads on every frame until \
1452             the batch applies them, because the first frame carrying them may be \
1453             built before the view is prepared and then discarded",
1454            self.id,
1455            self.desc.uploads_gen
1456        );
1457    }
1458}
1459
1460trait BatchRenderPass {
1461    fn set_bind_group(&mut self, index: u32, bind_group: &wgpu::BindGroup, offsets: &[u32]);
1462    fn set_vertex_buffer(&mut self, slot: u32, buffer: wgpu::BufferSlice<'_>);
1463    fn set_pipeline(&mut self, pipeline: &wgpu::RenderPipeline);
1464    fn draw(&mut self, vertices: std::ops::Range<u32>, instances: std::ops::Range<u32>);
1465}
1466
1467impl BatchRenderPass for wgpu::RenderPass<'_> {
1468    fn set_bind_group(&mut self, index: u32, bind_group: &wgpu::BindGroup, offsets: &[u32]) {
1469        self.set_bind_group(index, bind_group, offsets);
1470    }
1471
1472    fn set_vertex_buffer(&mut self, slot: u32, buffer: wgpu::BufferSlice<'_>) {
1473        self.set_vertex_buffer(slot, buffer);
1474    }
1475
1476    fn set_pipeline(&mut self, pipeline: &wgpu::RenderPipeline) {
1477        self.set_pipeline(pipeline);
1478    }
1479
1480    fn draw(&mut self, vertices: std::ops::Range<u32>, instances: std::ops::Range<u32>) {
1481        self.draw(vertices, instances);
1482    }
1483}
1484
1485impl BatchRenderPass for CallbackRenderPass<'_, '_> {
1486    fn set_bind_group(&mut self, index: u32, bind_group: &wgpu::BindGroup, offsets: &[u32]) {
1487        self.set_bind_group(index, bind_group, offsets);
1488    }
1489
1490    fn set_vertex_buffer(&mut self, slot: u32, buffer: wgpu::BufferSlice<'_>) {
1491        self.set_vertex_buffer(slot, buffer);
1492    }
1493
1494    fn set_pipeline(&mut self, pipeline: &wgpu::RenderPipeline) {
1495        self.set_pipeline(pipeline);
1496    }
1497
1498    fn draw(&mut self, vertices: std::ops::Range<u32>, instances: std::ops::Range<u32>) {
1499        self.draw(vertices, instances);
1500    }
1501}
1502
1503fn draw_batch_with_pass<P: BatchRenderPass>(
1504    id: &str,
1505    rpass: &mut P,
1506    resources: &CallbackResources,
1507) {
1508    let Some(all) = resources.get::<BatchResources>() else {
1509        return;
1510    };
1511    let Some(res) = all.batches.get(id) else {
1512        return;
1513    };
1514    if res.last_total == 0 {
1515        return;
1516    }
1517    rpass.set_bind_group(0, &res.cam_bind, &[]);
1518    rpass.set_bind_group(1, &res.atlas.tex_bind, &[]);
1519    rpass.set_bind_group(2, res.light_bind.as_ref(), &[]);
1520    rpass.set_vertex_buffer(0, res.corners.slice(..));
1521    rpass.set_vertex_buffer(1, res.instances.slice(..));
1522    if res.last_alpha > 0 {
1523        rpass.set_pipeline(&res.pipeline_alpha);
1524        rpass.draw(0..6, 0..res.last_alpha);
1525    }
1526    if res.last_multiply_end > res.last_alpha {
1527        rpass.set_pipeline(&res.pipeline_multiply);
1528        rpass.draw(0..6, res.last_alpha..res.last_multiply_end);
1529    }
1530    if res.last_total > res.last_multiply_end {
1531        rpass.set_pipeline(&res.pipeline_additive);
1532        rpass.draw(0..6, res.last_multiply_end..res.last_total);
1533    }
1534}
1535
1536/// Draw the prepared batch for one id. Shared by [`SpriteBatch`] and
1537/// viewport payloads so all GPU consumers issue identical draw calls.
1538pub fn draw_batch_with_id(
1539    id: &str,
1540    rpass: &mut wgpu::RenderPass<'_>,
1541    resources: &CallbackResources,
1542) {
1543    draw_batch_with_pass(id, rpass, resources);
1544}
1545
1546pub(crate) fn draw_batch_with_id_callback(
1547    id: &str,
1548    rpass: &mut CallbackRenderPass<'_, '_>,
1549    resources: &CallbackResources,
1550) {
1551    draw_batch_with_pass(id, rpass, resources);
1552}
1553
1554/// Draw the default batch (backward compat for single-batch apps).
1555pub fn draw_batch(rpass: &mut wgpu::RenderPass<'_>, resources: &CallbackResources) {
1556    draw_batch_with_id("sprite_batch.default", rpass, resources);
1557}
1558
1559impl WgpuCallback for SpriteBatch {
1560    fn resource_key(&self) -> Option<&str> {
1561        Some(super::lightpass::SHARED_CALLBACK_KEY)
1562    }
1563
1564    fn resource_type_id(&self) -> std::any::TypeId {
1565        std::any::TypeId::of::<super::lightpass::LightScope>()
1566    }
1567
1568    fn prepare(
1569        &self,
1570        device: &wgpu::Device,
1571        queue: &wgpu::Queue,
1572        encoder: &mut wgpu::CommandEncoder,
1573        screen: &ScreenDescriptor,
1574        resources: &mut CallbackResources,
1575    ) -> Vec<wgpu::CommandBuffer> {
1576        self.prepare_with_uploads(device, queue, encoder, screen, resources, &self.uploads)
1577    }
1578
1579    fn finish_prepare(
1580        &self,
1581        device: &wgpu::Device,
1582        queue: &wgpu::Queue,
1583        _encoder: &mut wgpu::CommandEncoder,
1584        _screen: &ScreenDescriptor,
1585        resources: &mut CallbackResources,
1586    ) -> Vec<wgpu::CommandBuffer> {
1587        self.resolve_lightmap(device, queue, resources);
1588        Vec::new()
1589    }
1590
1591    fn paint(
1592        &self,
1593        _info: repose_core::PaintCallbackInfo,
1594        rpass: &mut CallbackRenderPass<'_, '_>,
1595        resources: &CallbackResources,
1596    ) {
1597        draw_batch_with_id_callback(self.id.as_str(), rpass, resources);
1598    }
1599}
1600
1601/// One view's worth of atlas draws: the sprite rows for this frame plus the
1602/// shared atlas uploads. Each scene node owns its frame, so several views can
1603/// batch from one atlas without sharing (and clobbering) one batch; the pixel
1604/// data itself rides an `Arc` and is never cloned.
1605pub struct BatchFrame {
1606    batch: SpriteBatch,
1607    uploads: std::sync::Arc<[AtlasUpload]>,
1608}
1609
1610impl BatchFrame {
1611    pub fn new(batch: SpriteBatch, uploads: std::sync::Arc<[AtlasUpload]>) -> Self {
1612        Self { batch, uploads }
1613    }
1614
1615    pub fn node(self, rect: repose_core::Rect) -> repose_core::SceneNode {
1616        repose_core::SceneNode::Callback {
1617            rect,
1618            payload: repose_render_wgpu::Callback::new(self),
1619        }
1620    }
1621}
1622
1623impl WgpuCallback for BatchFrame {
1624    fn resource_key(&self) -> Option<&str> {
1625        Some(super::lightpass::SHARED_CALLBACK_KEY)
1626    }
1627
1628    fn resource_type_id(&self) -> std::any::TypeId {
1629        std::any::TypeId::of::<super::lightpass::LightScope>()
1630    }
1631
1632    fn prepare(
1633        &self,
1634        device: &wgpu::Device,
1635        queue: &wgpu::Queue,
1636        encoder: &mut wgpu::CommandEncoder,
1637        screen: &ScreenDescriptor,
1638        resources: &mut CallbackResources,
1639    ) -> Vec<wgpu::CommandBuffer> {
1640        self.batch
1641            .prepare_with_uploads(device, queue, encoder, screen, resources, &self.uploads)
1642    }
1643
1644    fn finish_prepare(
1645        &self,
1646        device: &wgpu::Device,
1647        queue: &wgpu::Queue,
1648        _encoder: &mut wgpu::CommandEncoder,
1649        _screen: &ScreenDescriptor,
1650        resources: &mut CallbackResources,
1651    ) -> Vec<wgpu::CommandBuffer> {
1652        self.batch.resolve_lightmap(device, queue, resources);
1653        Vec::new()
1654    }
1655
1656    fn paint(
1657        &self,
1658        _info: repose_core::PaintCallbackInfo,
1659        rpass: &mut CallbackRenderPass<'_, '_>,
1660        resources: &CallbackResources,
1661    ) {
1662        draw_batch_with_id_callback(&self.batch.id, rpass, resources);
1663    }
1664}
1665
1666#[cfg(test)]
1667mod tests {
1668    use super::*;
1669
1670    fn apply(rows: ([f32; 4], [f32; 4]), corner: [f32; 2]) -> [f32; 2] {
1671        let (r0, r1) = rows;
1672        [
1673            r0[0] * corner[0] + r0[1] * corner[1] + r0[3],
1674            r1[0] * corner[0] + r1[1] * corner[1] + r1[3],
1675        ]
1676    }
1677
1678    #[test]
1679    fn default_rows_match_canvas_top_left() {
1680        let rows = instance_rows([400.0, 300.0], [64.0, 80.0], 0.0, [0.5, 0.5], false, false);
1681        let tl = apply(rows, [-0.5, -0.5]);
1682        let br = apply(rows, [0.5, 0.5]);
1683        assert_eq!(tl, [368.0, 260.0]);
1684        assert_eq!(br, [432.0, 340.0]);
1685    }
1686
1687    #[test]
1688    fn frame_uv_indexes_row_major() {
1689        // 4x2 sheet: frame 5 is column 1, row 1.
1690        let (mn, mx) = frame_uv(4, 2, 5);
1691        assert_eq!(mn, [0.25, 0.5]);
1692        assert_eq!(mx, [0.5, 1.0]);
1693        // First cell starts at the origin; clamping holds the last cell.
1694        assert_eq!(frame_uv(4, 2, 0).0, [0.0, 0.0]);
1695        assert_eq!(frame_uv(4, 2, 99), frame_uv(4, 2, 7));
1696        assert_eq!(frame_uv(0, 0, 3), ([0.0, 0.0], [1.0, 1.0]));
1697    }
1698
1699    #[test]
1700    fn sprite_aabb_matches_unrotated_quad() {
1701        let (mn, mx) = sprite_aabb([400.0, 300.0], [64.0, 80.0], 0.0, [0.5, 0.5], false, false);
1702        assert_eq!(mn, [368.0, 260.0]);
1703        assert_eq!(mx, [432.0, 340.0]);
1704        // A quarter turn swaps the footprint: 64x80 becomes 80x64.
1705        let (mn, mx) = sprite_aabb(
1706            [0.0, 0.0],
1707            [64.0, 80.0],
1708            std::f32::consts::FRAC_PI_2,
1709            [0.5, 0.5],
1710            false,
1711            false,
1712        );
1713        assert!((mn[0] + 40.0).abs() < 1e-4 && (mn[1] + 32.0).abs() < 1e-4);
1714        assert!((mx[0] - 40.0).abs() < 1e-4 && (mx[1] - 32.0).abs() < 1e-4);
1715    }
1716
1717    #[test]
1718    fn quarter_turn_rotates_footprint() {
1719        let rows = instance_rows(
1720            [0.0, 0.0],
1721            [64.0, 80.0],
1722            std::f32::consts::FRAC_PI_2,
1723            [0.5, 0.5],
1724            false,
1725            false,
1726        );
1727        // Local top-left (-32,-40) rotates to (40,-32) in y-down space.
1728        let p = apply(rows, [-0.5, -0.5]);
1729        assert!(
1730            (p[0] - 40.0).abs() < 1e-4 && (p[1] + 32.0).abs() < 1e-4,
1731            "got {p:?}"
1732        );
1733    }
1734
1735    #[test]
1736    fn top_left_anchor_pins_corner() {
1737        let rows = instance_rows([100.0, 100.0], [64.0, 80.0], 0.0, [0.0, 0.0], false, false);
1738        let tl = apply(rows, [-0.5, -0.5]);
1739        assert_eq!(tl, [100.0, 100.0]);
1740    }
1741
1742    #[test]
1743    fn flip_x_mirrors_around_anchor() {
1744        let plain = instance_rows([0.0, 0.0], [64.0, 8.0], 0.0, [0.5, 0.5], false, false);
1745        let flipped = instance_rows([0.0, 0.0], [64.0, 8.0], 0.0, [0.5, 0.5], true, false);
1746        let a = apply(plain, [-0.5, 0.0]);
1747        let b = apply(flipped, [-0.5, 0.0]);
1748        assert_eq!(a, [-32.0, 0.0]);
1749        assert_eq!(b, [32.0, 0.0]);
1750    }
1751
1752    #[test]
1753    fn screen_camera_is_y_down() {
1754        let cam = screen_camera([800.0, 600.0]);
1755        let top_left = cam.project_point3(glam::Vec3::new(0.0, 0.0, 0.0));
1756        let bottom_right = cam.project_point3(glam::Vec3::new(800.0, 600.0, 0.0));
1757        let center = cam.project_point3(glam::Vec3::new(400.0, 300.0, 0.0));
1758        // NDC y-up: screen top is +1, screen bottom is -1.
1759        assert!((top_left.x + 1.0).abs() < 1e-5 && (top_left.y - 1.0).abs() < 1e-5);
1760        assert!((bottom_right.x - 1.0).abs() < 1e-5 && (bottom_right.y + 1.0).abs() < 1e-5);
1761        assert!(center.x.abs() < 1e-5 && center.y.abs() < 1e-5);
1762    }
1763
1764    #[test]
1765    fn push_sprite_bridges_snapshot_fields() {
1766        let mut batch = SpriteBatch::new(BatchDesc::default());
1767        batch.push_sprite(&SpriteInstance {
1768            center: glam::Vec2::new(10.0, 20.0),
1769            size: glam::Vec2::new(4.0, 6.0),
1770            uv_min: glam::Vec2::new(0.25, 0.5),
1771            uv_max: glam::Vec2::new(0.5, 0.75),
1772            color: [1.0, 0.5, 0.25, 0.8],
1773            page: 3,
1774            ..Default::default()
1775        });
1776        assert_eq!(batch.len(), 1);
1777        let inst = batch.instances[0];
1778        assert_eq!(inst.uv_min, [0.25, 0.5]);
1779        assert_eq!(inst.uv_max, [0.5, 0.75]);
1780        // The snapshot tint is display-referred; the batch linearizes it.
1781        assert_eq!(
1782            inst.tint,
1783            crate::rgba8([1.0, 0.5, 0.25, 0.8]).to_linear(),
1784            "tint reaches the batch in linear space"
1785        );
1786        assert_eq!(inst.page, 3.0);
1787        // Default anchor centers: top-left at (8, 17).
1788        let p = apply((inst.row0, inst.row1), [-0.5, -0.5]);
1789        assert_eq!(p, [8.0, 17.0]);
1790        assert_eq!(inst.layer, 0, "sprites default to light layer 0");
1791    }
1792
1793    #[test]
1794    fn z_and_blend_sort_into_ranges() {
1795        use super::super::SpriteBlend;
1796        let mut batch = SpriteBatch::with_id("test.sort", BatchDesc::default());
1797        let quad = |z: f32, blend: SpriteBlend| SpriteInstance {
1798            center: glam::Vec2::new(0.0, 0.0),
1799            size: glam::Vec2::new(1.0, 1.0),
1800            z,
1801            blend,
1802            ..Default::default()
1803        };
1804        batch.push_sprite(&quad(5.0, SpriteBlend::Alpha));
1805        batch.push_sprite(&quad(1.0, SpriteBlend::Additive));
1806        batch.push_sprite(&quad(3.0, SpriteBlend::Multiply));
1807        batch.push_sprite(&quad(2.0, SpriteBlend::Alpha));
1808        batch.push_sprite(&quad(0.0, SpriteBlend::Multiply));
1809        let (sorted, alpha, mul_end) = batch.sorted_instances();
1810        assert_eq!((alpha, mul_end, sorted.len() as u32), (2, 4, 5));
1811        assert_eq!([sorted[0].z, sorted[1].z], [2.0, 5.0]);
1812        assert_eq!([sorted[2].z, sorted[3].z], [0.0, 3.0]);
1813        assert_eq!(sorted[4].z, 1.0);
1814        assert_eq!(sorted[4].flags, 1);
1815    }
1816
1817    /// Atlas page is a packing accident, not a draw key: same-z
1818    /// same-blend sprites keep push order regardless of page (bandit
1819    /// guns over bodies, bullet layers aligned, camp floors under the
1820    /// vortex — all same-z pairs the old page tiebreak reordered).
1821    #[test]
1822    fn same_z_keeps_push_order_across_pages() {
1823        use super::super::SpriteBlend;
1824        let mut batch = SpriteBatch::with_id("test.pages", BatchDesc::default());
1825        let quad = |page: u32| SpriteInstance {
1826            center: glam::Vec2::new(0.0, 0.0),
1827            size: glam::Vec2::new(1.0, 1.0),
1828            z: 0.0,
1829            blend: SpriteBlend::Alpha,
1830            page,
1831            ..Default::default()
1832        };
1833        batch.push_sprite(&quad(1));
1834        batch.push_sprite(&quad(0));
1835        let (sorted, _, _) = batch.sorted_instances();
1836        assert_eq!([sorted[0].page, sorted[1].page], [1.0, 0.0]);
1837    }
1838
1839    #[test]
1840    fn white_upload_is_1x1_white() {
1841        let up = AtlasUpload::white(2, 5, 7);
1842        assert_eq!((up.page, up.x, up.y, up.w, up.h), (2, 5, 7, 1, 1));
1843        assert_eq!(up.rgba, vec![255, 255, 255, 255]);
1844    }
1845
1846    #[test]
1847    fn single_layer_atlas_draws_tinted_sprites() {
1848        // A one-layer atlas must be a plain D2 texture, not a one-element
1849        // D2Array: GL/ANGLE assumes D2 for it and then samples the array view
1850        // as black, which silently erases every sprite with no validation
1851        // error. Guards the shape choice for the layout, the view and the
1852        // shader together, since they only agree as a set.
1853        assert_eq!(
1854            crate::batch::atlas_shape(1),
1855            (wgpu::TextureViewDimension::D2, false)
1856        );
1857        assert_eq!(
1858            crate::batch::atlas_shape(4),
1859            (wgpu::TextureViewDimension::D2Array, true)
1860        );
1861        assert!(
1862            crate::batch::sprite_shader(1)
1863                .contains("@group(1) @binding(0) var atlas: texture_2d<f32>")
1864                && !crate::batch::sprite_shader(1)
1865                    .contains("@group(1) @binding(0) var atlas: texture_2d_array"),
1866            "single-layer shader samples a 2d atlas"
1867        );
1868        assert!(
1869            crate::batch::sprite_shader(4)
1870                .contains("@group(1) @binding(0) var atlas: texture_2d_array"),
1871            "multi-layer shader samples an array atlas"
1872        );
1873        // The light map is an array in both variants; a one-layer light map
1874        // would hit the same GL/ANGLE trap, so batches always allocate two.
1875        assert!(
1876            crate::batch::sprite_shader(1)
1877                .contains("@group(2) @binding(0) var lightmap: texture_2d_array<f32>"),
1878            "the light map is sampled as an array regardless of atlas shape"
1879        );
1880    }
1881
1882    /// End-to-end GPU proof: upload atlas pages, draw textured quads
1883    /// offscreen, and assert exact pixels (positions, colors, page,
1884    /// mirror). sRGB primaries are transfer-function fixed points, so
1885    /// asserts are exact. Skips gracefully where no GPU exists.
1886    #[test]
1887    fn offscreen_batch_draws_oriented_textured_quads() {
1888        use repose_core::{Color, Rect, Scene, SceneNode};
1889        use repose_render_wgpu::{Callback, offscreen::OffscreenRenderer};
1890
1891        let mut renderer = match OffscreenRenderer::new_blocking(256, 256, 1) {
1892            Ok(r) => r,
1893            Err(e) => {
1894                eprintln!("SKIP offscreen batch test (no GPU): {e}");
1895                return;
1896            }
1897        };
1898        // Page 0 (2x2, row-major top first): R G / B W.
1899        let page0 = vec![
1900            255, 0, 0, 255, //
1901            0, 255, 0, 255, //
1902            0, 0, 255, 255, //
1903            255, 255, 255, 255,
1904        ];
1905        // Page 1: solid magenta.
1906        let page1 = [255, 0, 255, 255].repeat(4);
1907        let mut batch = SpriteBatch::new(BatchDesc {
1908            layer_size: 2,
1909            layers: 2,
1910            filter: TextureFilter::Nearest,
1911            ..Default::default()
1912        });
1913        batch.upload(AtlasUpload {
1914            page: 0,
1915            x: 0,
1916            y: 0,
1917            w: 2,
1918            h: 2,
1919            rgba: page0,
1920        });
1921        batch.upload(AtlasUpload {
1922            page: 1,
1923            x: 0,
1924            y: 0,
1925            w: 2,
1926            h: 2,
1927            rgba: page1,
1928        });
1929        batch.set_camera(screen_camera([256.0, 256.0]));
1930        // Big quad over the middle sampling page 0 fully.
1931        batch.push(
1932            [128.0, 128.0],
1933            [128.0, 128.0],
1934            0.0,
1935            [0.5, 0.5],
1936            false,
1937            false,
1938            [0.0, 0.0],
1939            [1.0, 1.0],
1940            [1.0, 1.0, 1.0, 1.0],
1941            0,
1942        );
1943        // Small quad bottom-right sampling page 1.
1944        batch.push(
1945            [224.0, 224.0],
1946            [32.0, 32.0],
1947            0.0,
1948            [0.5, 0.5],
1949            false,
1950            false,
1951            [0.0, 0.0],
1952            [1.0, 1.0],
1953            [1.0, 1.0, 1.0, 1.0],
1954            1,
1955        );
1956        let scene = Scene {
1957            clear_color: Color::from_rgba(0, 0, 0, 255),
1958            nodes: vec![SceneNode::Callback {
1959                rect: Rect {
1960                    x: 0.0,
1961                    y: 0.0,
1962                    w: 256.0,
1963                    h: 256.0,
1964                },
1965                payload: Callback::new(batch),
1966            }],
1967        };
1968        let px = renderer
1969            .render_rgba(&scene, Some([0.0, 0.0, 0.0, 1.0]))
1970            .expect("offscreen render");
1971        let at = |x: u32, y: u32| -> [u8; 4] {
1972            let i = ((y * 256 + x) * 4) as usize;
1973            [px[i], px[i + 1], px[i + 2], px[i + 3]]
1974        };
1975        // Orientation: uv (0,0) is the PNG top-left.
1976        assert_eq!(at(64, 64), [255, 0, 0, 255], "top-left red");
1977        assert_eq!(at(191, 64), [0, 255, 0, 255], "top-right green");
1978        assert_eq!(at(64, 191), [0, 0, 255, 255], "bottom-left blue");
1979        assert_eq!(at(191, 191), [255, 255, 255, 255], "bottom-right white");
1980        assert_eq!(at(224, 224), [255, 0, 255, 255], "page 1 magenta");
1981        assert_eq!(at(8, 8), [0, 0, 0, 255], "background clear");
1982
1983        // Mirror check: same quad flipped samples the opposite column.
1984        let mut flipped = SpriteBatch::new(BatchDesc {
1985            layer_size: 2,
1986            layers: 2,
1987            filter: TextureFilter::Nearest,
1988            ..Default::default()
1989        });
1990        flipped.set_camera(screen_camera([256.0, 256.0]));
1991        flipped.push(
1992            [128.0, 128.0],
1993            [128.0, 128.0],
1994            0.0,
1995            [0.5, 0.5],
1996            true,
1997            false,
1998            [0.0, 0.0],
1999            [1.0, 1.0],
2000            [1.0, 1.0, 1.0, 1.0],
2001            0,
2002        );
2003        let scene = Scene {
2004            clear_color: Color::from_rgba(0, 0, 0, 255),
2005            nodes: vec![SceneNode::Callback {
2006                rect: Rect {
2007                    x: 0.0,
2008                    y: 0.0,
2009                    w: 256.0,
2010                    h: 256.0,
2011                },
2012                payload: Callback::new(flipped),
2013            }],
2014        };
2015        let px = renderer
2016            .render_rgba(&scene, Some([0.0, 0.0, 0.0, 1.0]))
2017            .expect("offscreen render");
2018        let at = |x: u32, y: u32| -> [u8; 4] {
2019            let i = ((y * 256 + x) * 4) as usize;
2020            [px[i], px[i + 1], px[i + 2], px[i + 3]]
2021        };
2022        assert_eq!(at(64, 64), [0, 255, 0, 255], "flipped top-left green");
2023        assert_eq!(at(191, 191), [0, 0, 255, 255], "flipped bottom-right blue");
2024    }
2025
2026    /// Sibling batch nodes with distinct ids draw independently. GPU
2027    /// resources are keyed by batch id, so two runs sharing one id would
2028    /// collide and only the last prepared run would paint; the unified
2029    /// producer gives every run its own id for exactly this reason.
2030    #[test]
2031    fn distinct_batch_ids_compose_in_one_scene() {
2032        use repose_core::{Color, Rect, Scene};
2033        use repose_render_wgpu::offscreen::OffscreenRenderer;
2034        use std::sync::Arc;
2035
2036        let mut renderer = match OffscreenRenderer::new_blocking(256, 256, 1) {
2037            Ok(r) => r,
2038            Err(e) => {
2039                eprintln!("SKIP batch compose test (no GPU): {e}");
2040                return;
2041            }
2042        };
2043        let page = vec![
2044            255, 0, 0, 255, //
2045            0, 255, 0, 255, //
2046            0, 0, 255, 255, //
2047            255, 255, 255, 255,
2048        ];
2049        let uploads: Arc<[AtlasUpload]> = Arc::from(vec![AtlasUpload {
2050            page: 0,
2051            x: 0,
2052            y: 0,
2053            w: 2,
2054            h: 2,
2055            rgba: page,
2056        }]);
2057        let desc = BatchDesc {
2058            layer_size: 2,
2059            layers: 1,
2060            filter: TextureFilter::Nearest,
2061            ..Default::default()
2062        };
2063        let mut left = SpriteBatch::with_id("test.compose.left", desc.clone());
2064        left.set_camera(screen_camera([256.0, 256.0]));
2065        left.push(
2066            [64.0, 128.0],
2067            [64.0, 64.0],
2068            0.0,
2069            [0.5, 0.5],
2070            false,
2071            false,
2072            [0.0, 0.0],
2073            [1.0, 1.0],
2074            [1.0, 1.0, 1.0, 1.0],
2075            0,
2076        );
2077        let mut right = SpriteBatch::with_id("test.compose.right", desc.clone());
2078        right.set_camera(screen_camera([256.0, 256.0]));
2079        right.push(
2080            [192.0, 128.0],
2081            [64.0, 64.0],
2082            0.0,
2083            [0.5, 0.5],
2084            false,
2085            false,
2086            [0.0, 0.0],
2087            [1.0, 1.0],
2088            [1.0, 1.0, 1.0, 1.0],
2089            0,
2090        );
2091        let full = Rect {
2092            x: 0.0,
2093            y: 0.0,
2094            w: 256.0,
2095            h: 256.0,
2096        };
2097        let scene = Scene {
2098            clear_color: Color::from_rgba(0, 0, 0, 255),
2099            nodes: vec![
2100                BatchFrame::new(left, uploads.clone()).node(full),
2101                BatchFrame::new(right, uploads.clone()).node(full),
2102            ],
2103        };
2104        let px = renderer
2105            .render_rgba(&scene, Some([0.0, 0.0, 0.0, 1.0]))
2106            .expect("offscreen render");
2107        let at = |x: u32, y: u32| -> [u8; 4] {
2108            let i = ((y * 256 + x) * 4) as usize;
2109            [px[i], px[i + 1], px[i + 2], px[i + 3]]
2110        };
2111        assert_eq!(at(40, 104), [255, 0, 0, 255], "left run red");
2112        assert_eq!(at(168, 104), [255, 0, 0, 255], "right run red");
2113    }
2114}