nadir-render 0.4.0

2D renderer for the Nadir engine: sprite batching, y-sort, tilemap chunks, bitmap text, a UI pass, camera and atlases.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
// Copyright 2026 Joseph Anthony Abbott III
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! The renderer: draws a frame's sprites, texts and tile layers into the
//! virtual image, scales that up into the output, then draws the UI on
//! it.

use std::mem;
use std::time::Instant;

use nadir_assets::{AssetServer, LoadState};
use nadir_core::{IRect, IVec2, UVec2, Vec2};
use nadir_gfx::{
    BufferDesc, BufferId, BufferKind, BufferUsage, Device, GfxError, PassTarget, PipelineDesc,
    PipelineId, RenderTargetId, Sampler, ShaderSource, TextureFormat, TextureId, TimerId, Topology,
    VertexLayout, VertexStep,
};

use crate::batcher::Pipe;
use crate::chunks::{self, ChunkDraw, Step, TileCache};
use crate::glyphs::{Server, TextPass};
use crate::shader::{BLIT, Interface, Program, SPRITE, TEXT, TILE_CHUNK, packed};
use crate::timing::{GpuTimes, TimerRing};
use crate::ui::UiPass;
use crate::view::{self, Upscale, View};
use crate::{
    Camera2D, RenderError, RenderFrame, SPRITE_INSTANCE_FLOATS, SpriteBatcher, Texture, TileLayers,
    UiScale, UiSpace,
};

/// How the renderer draws.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RenderConfig {
    /// The size of the virtual image the world is drawn into, in pixels.
    /// The image is then scaled up into the output by a whole factor
    /// (pixel-perfect mode).
    pub virtual_resolution: UVec2,
}

/// Where a frame is shown: the window, or a render target.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Output {
    /// The target. It must be [`TextureFormat::Rgba8Srgb`], as the window
    /// is.
    pub target: PassTarget,
    /// Its size in pixels: for the window, its drawable size.
    pub size: UVec2,
}

/// What a frame drew. Its draw calls into the virtual image are `batches`
/// and `chunks`, and onto the output the blit and `ui_batches`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct FrameStats {
    /// The sprites of the world drawn.
    pub sprites: u32,
    /// The sprites, and the glyphs of texts laid out, of the world and of
    /// the UI, not drawn because their texture is not ready: still loading,
    /// failed with no placeholder to show
    /// ([`OnFailure::Nothing`](nadir_assets::OnFailure)), or unknown to the
    /// asset server.
    pub skipped: u32,
    /// The instanced draws of the world's sprites and texts' glyphs.
    pub batches: u32,
    /// The tiles drawn, of every tile layer.
    pub tiles: u32,
    /// The instanced draws of tiles: one for each chunk drawn.
    pub chunks: u32,
    /// The world's texts laid out and drawn, glyphs not ready aside.
    pub texts: u32,
    /// The glyphs drawn, of every text of the world: each a quad, as a
    /// sprite is.
    pub glyphs: u32,
    /// The texts of the world and of the UI not drawn: their font, its
    /// atlas or its sprite not ready, not loaded, or not the font's.
    pub skipped_texts: u32,
    /// The UI's sprites drawn: not those wholly outside their view's clip.
    pub ui_sprites: u32,
    /// The UI's glyphs drawn: not those wholly outside their view's clip.
    pub ui_glyphs: u32,
    /// The UI's texts laid out, glyphs not ready or cut aside.
    pub ui_texts: u32,
    /// The instanced draws of the UI's sprites and glyphs onto the output.
    pub ui_batches: u32,
}

/// Draws with `draw`, timed by `timer` if there is one. The timer stops
/// whether the drawing fails or not, so that the next frame can run one.
fn timed(
    device: &mut Device,
    timer: Option<TimerId>,
    draw: impl FnOnce(&mut Device) -> Result<(), RenderError>,
) -> Result<(), RenderError> {
    let Some(timer) = timer else {
        return draw(device);
    };
    device.begin_timer(timer)?;
    let drawn = draw(device);
    let ended = device.end_timer();
    drawn?;
    Ok(ended?)
}

/// The unit quad, as a triangle strip: (0, 0) to (1, 1).
const QUAD: [f32; 8] = [0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0];

/// The blit's quad, as a triangle strip: clip-space corners, then texture
/// coordinates. GL stores a render target from its bottom row, so the
/// bottom of clip space (y = -1) samples v = 0.
const BLIT_QUAD: [f32; 16] = [
    -1.0, -1.0, 0.0, 0.0, //
    1.0, -1.0, 1.0, 0.0, //
    -1.0, 1.0, 0.0, 1.0, //
    1.0, 1.0, 1.0, 1.0,
];

/// The most attributes a vertex buffer slot of a program has room for: as
/// many as OpenGL 3.3 has in all.
const ATTRIBUTES: usize = 16;

/// The instances the buffer holds at first. It grows by doubling, and
/// never shrinks.
const FIRST_CAPACITY: usize = 256;

/// A tile layer of the frame that draws at least one chunk.
#[derive(Clone, Copy, Debug)]
struct ReadyLayer {
    /// Its layer and depth, as the high bits of a sprite's sort key.
    layer: u8,
    depth: u32,
    /// Its place among the frame's tile layers.
    submission: u32,
    texture: TextureId,
    uniform: [u32; 12],
    /// Its draws, in `Renderer::chunk_draws`.
    first: u32,
    end: u32,
}

/// The program a pass has bound last.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Bound {
    Nothing,
    Sprites,
    Text,
    Tiles,
}

/// The 2D renderer.
///
/// Each frame, [`Renderer::render`] draws the sprites, texts and tile
/// layers into a render target of the virtual resolution: the sprites and
/// the texts' glyphs sorted by layer and depth and batched by texture and
/// program, each tile layer at its own layer and depth among them, a chunk
/// at a time. It then scales that image up into the output by the largest
/// whole factor that fits, with bars in the clear color around it, and
/// draws the frame's [`UiList`](crate::UiList) on the output, at its
/// resolution.
pub struct Renderer {
    virtual_size: UVec2,
    sprite: PipelineId,
    tile_chunk: PipelineId,
    blit: PipelineId,
    text: PipelineId,
    quad: BufferId,
    blit_quad: BufferId,
    instances: BufferId,
    /// Instances the buffer holds.
    capacity: usize,
    world: RenderTargetId,
    batcher: SpriteBatcher<TextureId>,
    texts: TextPass<TextureId>,
    ui: UiPass<TextureId>,
    tiles: TileCache,
    // The tile work of a frame, in lists reused from frame to frame.
    ready: Vec<ReadyLayer>,
    chunk_draws: Vec<ChunkDraw>,
    /// (Position among the sprites, index in `ready`) of each ready layer.
    positions: Vec<(u32, u32)>,
    steps: Vec<Step<(TextureId, Pipe)>>,
    /// Whether the passes are timed on the GPU.
    gpu_timing: bool,
    timing: TimerRing<TimerId>,
}

impl Renderer {
    /// Makes the renderer's pipelines, buffers and virtual image.
    ///
    /// # Errors
    ///
    /// [`RenderError::BadConfig`] for an empty virtual resolution, and
    /// [`RenderError::Gfx`] if the device refuses, for instance a virtual
    /// resolution over [`nadir_gfx::Caps::max_texture_size`].
    pub fn new(device: &mut Device, config: &RenderConfig) -> Result<Self, RenderError> {
        let virtual_size = config.virtual_resolution;
        if virtual_size.x == 0 || virtual_size.y == 0 {
            return Err(RenderError::BadConfig("the virtual resolution is empty"));
        }

        let sprite = pipeline(device, &SPRITE, SPRITE.source())?;
        let tile_chunk = pipeline(device, &TILE_CHUNK, TILE_CHUNK.source())?;
        let blit = pipeline(device, &BLIT, BLIT.source())?;
        let text = pipeline(device, &TEXT, TEXT.source())?;

        let quad = device.create_buffer(&BufferDesc {
            label: "unit quad",
            kind: BufferKind::Vertex,
            usage: BufferUsage::Static,
            size: size_of_val(&QUAD),
        })?;
        device.write_buffer(quad, 0, &QUAD)?;
        let blit_quad = device.create_buffer(&BufferDesc {
            label: "blit quad",
            kind: BufferKind::Vertex,
            usage: BufferUsage::Static,
            size: size_of_val(&BLIT_QUAD),
        })?;
        device.write_buffer(blit_quad, 0, &BLIT_QUAD)?;
        let instances = instance_buffer(device, FIRST_CAPACITY)?;
        let world = device.create_render_target(virtual_size, TextureFormat::Rgba8Srgb)?;
        Ok(Self {
            virtual_size,
            sprite,
            tile_chunk,
            blit,
            text,
            quad,
            blit_quad,
            instances,
            capacity: FIRST_CAPACITY,
            world,
            batcher: SpriteBatcher::new(),
            texts: TextPass::new(),
            ui: UiPass::new(),
            tiles: TileCache::default(),
            ready: Vec::new(),
            chunk_draws: Vec::new(),
            positions: Vec::new(),
            steps: Vec::new(),
            gpu_timing: false,
            timing: TimerRing::new(),
        })
    }

    /// Times the passes of each [`Renderer::render`] on the GPU, or stops:
    /// off at first. On a device without
    /// [`Caps::timer_queries`](nadir_gfx::Caps::timer_queries) nothing is
    /// timed.
    ///
    /// Each render's times are read back by a later render, two later
    /// while the GPU keeps up, so that reading never waits for the GPU:
    /// [`Renderer::gpu_times`]. A render is not timed while the GPU has not
    /// done the work of the one four renders before it. Timing makes the
    /// device's timers at its first renders, two a render for four renders,
    /// which the device keeps until it is dropped. Stopping forgets the
    /// renders that wait.
    ///
    /// A device runs one timer at a time: while timing is on, a timer of
    /// the caller's running around `render` makes it fail with
    /// [`GfxError::FrameOrder`].
    pub fn set_gpu_timing(&mut self, on: bool) {
        if !on {
            self.timing.reset();
        }
        self.gpu_timing = on;
    }

    /// Whether the passes are timed on the GPU: [`Renderer::set_gpu_timing`].
    pub fn gpu_timing(&self) -> bool {
        self.gpu_timing
    }

    /// The GPU's times over the passes of earlier renders that the last
    /// [`Renderer::render`] read back, oldest first: none while timing is
    /// off ([`Renderer::set_gpu_timing`]), on a device without timer
    /// queries, and when no render had all its results yet. Each says how
    /// many renders back it was drawn ([`GpuTimes::renders_ago`]).
    ///
    /// A time longer than the time that passed since its render started is
    /// the driver's mistake (llvmpipe gives one for a context's first
    /// drawing), and is dropped, with a warning the first time.
    pub fn gpu_times(&self) -> &[GpuTimes] {
        self.timing.read()
    }

    /// Builds `program` again from `source`, for shaders edited while the
    /// game runs: the next [`Renderer::render`] draws with it, and the
    /// program it replaces is destroyed. Call it between frames, or in one
    /// before `render`.
    ///
    /// The sources may change anything but the program's interface, which
    /// the sources it was compiled with declare, its files under
    /// [`SHADER_DIR`](crate::SHADER_DIR) as they were:
    ///
    /// - each `in` variable of the vertex shader is one of the program's
    ///   attributes, with its location and no other layout qualifier, its
    ///   type and its name;
    /// - each uniform block, in either shader, is one of its blocks, whose
    ///   members must stay as they are: the device checks a block by its
    ///   size alone;
    /// - each other uniform is one of its samplers, a `sampler2D`, or has a
    ///   value of its own (`= …`);
    /// - the fragment shader has one output, an `out vec4` at location 0
    ///   and index 0, and writes no `gl_FragColor` or `gl_FragData`.
    ///
    /// An attribute, a block or a sampler the sources leave out is taken.
    /// The declarations are read as written, before a macro is expanded or
    /// a branch of an `#if` chosen: a declaration a macro makes is not
    /// seen, and every branch is read. Sources whose braces do not pair up,
    /// or whose branches do not each hold whole declarations, are refused.
    ///
    /// The renderer reads no file: the caller reads the sources, and gives
    /// them here. A device without Metal reads only the GLSL.
    ///
    /// # Errors
    ///
    /// [`RenderError::Gfx`] with [`GfxError::Interface`] saying what differs
    /// when the sources declare another interface, or a uniform block of
    /// another size; with [`GfxError::Shader`] and the driver's log when
    /// they do not compile or link; with another [`GfxError`] when the
    /// device refuses a call. The renderer keeps the program it had, and
    /// the next frame draws as the last did.
    pub fn reload_program(
        &mut self,
        device: &mut Device,
        program: Program,
        source: ShaderSource<'_>,
    ) -> Result<(), RenderError> {
        let interface = program.interface();
        interface
            .check(source.glsl_vs, source.glsl_fs)
            .map_err(|reason| GfxError::Interface {
                label: interface.name.to_string(),
                reason,
            })?;
        let rebuilt = pipeline(device, interface, source)?;
        let slot = match program {
            Program::Sprite => &mut self.sprite,
            Program::TileChunk => &mut self.tile_chunk,
            Program::Blit => &mut self.blit,
            Program::Text => &mut self.text,
        };
        device.destroy(mem::replace(slot, rebuilt));
        Ok(())
    }

    /// Draws `frame` into `output`, with the tile layers its
    /// [`TileLayerDraw`](crate::TileLayerDraw)s name in `tiles`. Call it
    /// inside a frame of the device (`begin_frame` and `end_frame`, or their
    /// offscreen forms).
    ///
    /// Each text is laid out in its [`Font`](crate::Font), whose atlas file
    /// and pages it finds by their paths in `assets`: a text whose font or
    /// atlas is not ready is not drawn, nor a glyph whose page is not. A
    /// font whose atlas or page is not loaded at all, or whose atlas has no
    /// sprite of its name or too few frames, is logged once; so is each
    /// character a font lacks, which draws the font's fallback. A glyph on
    /// a page that failed shows the placeholder, as a sprite does, with the
    /// sprite program.
    ///
    /// Sprites whose texture is still loading are not drawn. A texture that
    /// failed to load shows its placeholder, all of it, whatever the
    /// sprite's `uv`, when the server shows placeholders
    /// ([`OnFailure::Placeholder`](nadir_assets::OnFailure)); otherwise its
    /// sprites are not drawn either. Tile layers do the same with their tile
    /// set's texture, every tile showing all of a placeholder.
    ///
    /// A tile layer that is not in `tiles` is not drawn. The renderer keeps
    /// each chunk of a layer on the GPU once the view has shown it, packs it
    /// again only after one of its tiles changes, and frees a layer's chunks
    /// at the first frame after it leaves `tiles`.
    ///
    /// The UI is drawn last, on the output, in the order its
    /// [`UiList`](crate::UiList) says, each sprite and text in its view's
    /// [`UiSpace`] for an output of `output.size` and cut to its clip; its
    /// textures and fonts are found as the world's are.
    ///
    /// # Errors
    ///
    /// [`RenderError::Gfx`] if the device refuses a call.
    pub fn render(
        &mut self,
        device: &mut Device,
        assets: &AssetServer,
        tiles: &TileLayers,
        frame: &RenderFrame,
        output: Output,
    ) -> Result<FrameStats, RenderError> {
        let timers = if self.gpu_timing && device.caps().timer_queries {
            self.timing.begin_render(device, Instant::now())?
        } else {
            None
        };
        let [world_timer, output_timer] = match timers {
            Some([world, output]) => [Some(world), Some(output)],
            None => [None, None],
        };
        let textures = assets.assets::<Texture>();
        let texture = |handle| {
            let textures = textures?;
            let texture = textures.get(handle)?;
            let failed = textures.state(handle) == Some(LoadState::Failed);
            Some((texture.id(), failed))
        };
        self.texts.build(&frame.texts, &Server(assets));
        self.batcher
            .build_with(&frame.sprites, &self.texts.quads, &frame.camera, |sprite| {
                texture(sprite.texture)
            });
        // The world's glyphs are packed: the text pass lays out the UI's
        // next, its logs once a font and character for both.
        let world_texts = (
            self.texts.texts,
            self.texts.skipped_texts,
            self.texts.skipped_glyphs,
        );
        self.texts.build(frame.ui.texts(), &Server(assets));
        self.ui.build(
            &frame.ui,
            &self.texts.quads,
            self.virtual_size,
            output.size,
            |sprite| texture(sprite.texture),
        );

        let view = View::new(&frame.camera, self.virtual_size);
        self.prepare_tiles(device, tiles, frame, &view, texture)?;
        let mut stats = self.batcher.stats();
        let (texts, skipped_texts, skipped_glyphs) = world_texts;
        stats.skipped += skipped_glyphs + self.ui.skipped + self.texts.skipped_glyphs;
        stats.texts = texts;
        stats.skipped_texts = skipped_texts + self.texts.skipped_texts;
        stats.ui_sprites = self.ui.sprites;
        stats.ui_glyphs = self.ui.glyphs;
        stats.ui_texts = self.texts.texts;
        // Each plan numbers its sprites and glyphs together with a u32;
        // the UI's instances go after the world's.
        let world = (stats.sprites + stats.glyphs) as usize;
        let count = world + (self.ui.sprites + self.ui.glyphs) as usize;
        if count > self.capacity {
            let capacity = count.next_power_of_two().max(self.capacity * 2);
            let instances = instance_buffer(device, capacity)?;
            device.destroy(self.instances);
            self.instances = instances;
            self.capacity = capacity;
        }
        if world > 0 {
            device.write_buffer(self.instances, 0, self.batcher.instances())?;
        }
        if count > world {
            let offset = world * SPRITE_INSTANCE_FLOATS;
            device.write_buffer(self.instances, offset, &self.ui.packed)?;
        }

        let clear = frame.clear.to_linear();
        stats.batches = 0;
        timed(device, world_timer, |device| {
            let mut pass = device.begin_pass(self.world.into(), Some(clear))?;
            pass.set_uniforms(0, &view.uniform())?;
            let mut bound = Bound::Nothing;
            for &step in &self.steps {
                match step {
                    Step::Sprites {
                        texture: (texture, pipe),
                        start,
                        count,
                    } => {
                        // A tile layer between two batches, or in one,
                        // leaves its own program and buffers bound. The
                        // sprite and text programs share the instances.
                        let (wanted, pipeline) = match pipe {
                            Pipe::Sprite => (Bound::Sprites, self.sprite),
                            Pipe::Text => (Bound::Text, self.text),
                        };
                        if bound != wanted {
                            pass.set_pipeline(pipeline)?;
                            pass.set_vertex_buffer(0, self.instances, 0)?;
                            pass.set_vertex_buffer(1, self.quad, 0)?;
                            bound = wanted;
                        }
                        pass.set_texture(0, texture, Sampler::NearestClamp)?;
                        pass.draw(0..4, start..start + count)?;
                        stats.batches += 1;
                    }
                    Step::Tiles(index) => {
                        let layer = self.ready[index as usize];
                        if bound != Bound::Tiles {
                            pass.set_pipeline(self.tile_chunk)?;
                            pass.set_vertex_buffer(1, self.quad, 0)?;
                            bound = Bound::Tiles;
                        }
                        pass.set_uniforms(1, &layer.uniform)?;
                        pass.set_texture(0, layer.texture, Sampler::NearestClamp)?;
                        for chunk in &self.chunk_draws[layer.first as usize..layer.end as usize] {
                            pass.set_vertex_buffer(0, chunk.buffer, 0)?;
                            pass.draw(0..4, 0..chunk.count)?;
                            stats.tiles += chunk.count;
                            stats.chunks += 1;
                        }
                    }
                }
            }
            Ok(())
        })?;
        timed(device, output_timer, |device| {
            let upscale = self.upscale(output.size);
            let mut pass = device.begin_pass(output.target, Some(clear))?;
            pass.set_viewport(upscale.rect);
            pass.set_pipeline(self.blit)?;
            pass.set_vertex_buffer(0, self.blit_quad, 0)?;
            pass.set_texture(0, self.world, Sampler::NearestClamp)?;
            pass.draw(0..4, 0..1)?;

            if !self.ui.batches.is_empty() {
                // The UI is packed in output pixels: one camera for all of
                // it, each view's clip a scissor.
                let side = |side: u32| i32::try_from(side).unwrap_or(i32::MAX);
                let pixels = IVec2::new(side(output.size.x), side(output.size.y));
                pass.set_viewport(IRect::new(IVec2::ZERO, pixels));
                let size = output.size.as_vec2();
                pass.set_uniforms(0, &[2.0 / size.x, -2.0 / size.y, -1.0, 1.0])?;
                // The UI's instances follow the world's, fewer than u32::MAX.
                let base = world as u32;
                let mut bound = Bound::Nothing;
                let mut view = None;
                for batch in &self.ui.batches {
                    let (texture, pipe) = batch.texture;
                    let (wanted, pipeline) = match pipe {
                        Pipe::Sprite => (Bound::Sprites, self.sprite),
                        Pipe::Text => (Bound::Text, self.text),
                    };
                    if bound != wanted {
                        pass.set_pipeline(pipeline)?;
                        pass.set_vertex_buffer(0, self.instances, 0)?;
                        pass.set_vertex_buffer(1, self.quad, 0)?;
                        bound = wanted;
                    }
                    if view != Some(batch.view) {
                        pass.set_scissor(self.ui.scissor(batch.view));
                        view = Some(batch.view);
                    }
                    pass.set_texture(0, texture, Sampler::NearestClamp)?;
                    let start = base + batch.start;
                    pass.draw(0..4, start..start + batch.count)?;
                    stats.ui_batches += 1;
                }
            }
            Ok(())
        })?;
        self.timing.end_render();
        Ok(stats)
    }

    /// Before the world pass, which borrows the device: frees the chunks of
    /// layers gone from `tiles`, culls and uploads the chunks of the frame's
    /// tile layers, and orders the pass's draws, with each layer that draws
    /// a chunk among the sprites.
    fn prepare_tiles(
        &mut self,
        device: &mut Device,
        tiles: &TileLayers,
        frame: &RenderFrame,
        view: &View,
        texture: impl Fn(nadir_assets::Handle<Texture>) -> Option<(TextureId, bool)>,
    ) -> Result<(), RenderError> {
        self.tiles.evict(device, tiles);
        self.ready.clear();
        self.chunk_draws.clear();
        let clock = chunks::clock_ms(frame.time);
        let shown = view.world_rect();
        // A frame of more than u32::MAX tile layers is far past any
        // budget; such layers are not drawn.
        for (submission, draw) in (0..u32::MAX).zip(&frame.tile_layers) {
            let Some(layer) = tiles.get(draw.tiles) else {
                continue;
            };
            let Some((texture, placeholder)) = texture(layer.tileset().texture) else {
                continue;
            };
            let Some(range) = chunks::visible_chunks(layer, shown) else {
                continue;
            };
            // Fewer draws than chunks in all the layers, so they fit.
            let first = self.chunk_draws.len() as u32;
            self.tiles
                .prepare(device, draw.tiles, layer, range, &mut self.chunk_draws)?;
            let end = self.chunk_draws.len() as u32;
            if end > first {
                self.ready.push(ReadyLayer {
                    layer: draw.layer,
                    depth: draw.depth,
                    submission,
                    texture,
                    uniform: chunks::layer_uniform(layer, view.zoom(), placeholder, clock),
                    first,
                    end,
                });
            }
        }
        self.ready
            .sort_unstable_by_key(|layer| (layer.layer, layer.depth, layer.submission));
        self.positions.clear();
        for (index, layer) in (0..).zip(&self.ready) {
            let position = self.batcher.position(layer.layer, layer.depth);
            self.positions.push((position, index));
        }
        chunks::steps(self.batcher.batches(), &self.positions, &mut self.steps);
        Ok(())
    }

    /// Where the virtual image lands in an output of `size`.
    pub fn upscale(&self, size: UVec2) -> Upscale {
        Upscale::new(self.virtual_size, size)
    }

    /// Where the UI at `scale` lands in an output of `size`, as it is drawn
    /// there: [`UiSpace::new`] with the renderer's virtual resolution. Its
    /// [`UiSpace::to_ui`] gives the UI point under the pointer.
    pub fn ui_space(&self, scale: UiScale, size: UVec2) -> UiSpace {
        UiSpace::new(scale, self.virtual_size, size)
    }

    /// The world point under `screen`, in pixels from the top left of an
    /// output of `size`, as `camera` shows it: for aiming with the mouse.
    pub fn screen_to_world(&self, camera: &Camera2D, size: UVec2, screen: Vec2) -> Vec2 {
        let view = View::new(camera, self.virtual_size);
        view.unproject(view::screen_to_virtual(&self.upscale(size), screen))
    }

    /// Where `world` is in an output of `size`, in pixels from its top
    /// left, as `camera` shows it.
    pub fn world_to_screen(&self, camera: &Camera2D, size: UVec2, world: Vec2) -> Vec2 {
        let view = View::new(camera, self.virtual_size);
        view::virtual_to_screen(&self.upscale(size), view.project(world))
    }
}

/// Makes the pipeline of the program `interface` from `source`: its
/// instances, if it has any, in vertex buffer slot 0, and its vertices in
/// the next.
fn pipeline(
    device: &mut Device,
    interface: &Interface,
    source: ShaderSource<'_>,
) -> Result<PipelineId, RenderError> {
    let (instance, instance_stride) = packed::<ATTRIBUTES>(interface.instance);
    let (vertex, vertex_stride) = packed::<ATTRIBUTES>(interface.vertex_attributes);
    let layouts = [
        VertexLayout {
            stride: instance_stride,
            step: VertexStep::Instance,
            attributes: &instance[..interface.instance.len()],
        },
        VertexLayout {
            stride: vertex_stride,
            step: VertexStep::Vertex,
            attributes: &vertex[..interface.vertex_attributes.len()],
        },
    ];
    let vertex_layouts = if interface.instance.is_empty() {
        &layouts[1..]
    } else {
        &layouts[..]
    };
    const {
        assert!(
            SPRITE.instance.len() <= ATTRIBUTES
                && SPRITE.vertex_attributes.len() <= ATTRIBUTES
                && TILE_CHUNK.instance.len() <= ATTRIBUTES
                && TILE_CHUNK.vertex_attributes.len() <= ATTRIBUTES
                && BLIT.instance.len() <= ATTRIBUTES
                && BLIT.vertex_attributes.len() <= ATTRIBUTES
                && TEXT.instance.len() <= ATTRIBUTES
                && TEXT.vertex_attributes.len() <= ATTRIBUTES,
            "a program has more attributes than a slot has room for"
        );
    }
    Ok(device.create_pipeline(&PipelineDesc {
        label: interface.name,
        shader: source,
        vertex_layouts,
        uniform_blocks: interface.uniform_blocks,
        textures: interface.textures,
        blend: interface.blend,
        topology: Topology::TriangleStrip,
        target_format: TextureFormat::Rgba8Srgb,
    })?)
}

fn instance_buffer(device: &mut Device, capacity: usize) -> Result<BufferId, RenderError> {
    Ok(device.create_buffer(&BufferDesc {
        label: "sprite and glyph instances",
        kind: BufferKind::Vertex,
        usage: BufferUsage::Dynamic,
        size: capacity * SPRITE_INSTANCE_FLOATS * size_of::<f32>(),
    })?)
}

/// Reloads on a GPU: what is destroyed, and what is kept.
#[cfg(all(test, feature = "headless-test"))]
mod gpu_tests {
    use nadir_gfx::{GfxError, ResourceKind};

    use super::*;

    /// A device on an offscreen context, or `None` where this system has
    /// none yet and no renderer is asked for, as the headless tests do.
    fn device() -> Option<Device> {
        let expected = std::env::var("NADIR_EXPECT_GL_RENDERER").unwrap_or_default();
        match Device::new_headless() {
            Ok(device) => {
                let renderer = &device.caps().renderer;
                assert!(
                    renderer.contains(&expected),
                    "the renderer is `{renderer}`, not `{expected}`"
                );
                Some(device)
            }
            Err(GfxError::NoOffscreenContext) if expected.is_empty() => None,
            Err(error) => panic!("no headless device: {error}"),
        }
    }

    /// The renderer's programs, in the order of `Program::ALL`.
    fn programs(renderer: &Renderer) -> [PipelineId; 4] {
        [
            renderer.sprite,
            renderer.tile_chunk,
            renderer.blit,
            renderer.text,
        ]
    }

    #[test]
    fn a_reload_destroys_the_program_it_replaces_and_a_refused_one_keeps_it() {
        let Some(mut device) = device() else { return };
        let size = UVec2::new(4, 4);
        let mut renderer = Renderer::new(
            &mut device,
            &RenderConfig {
                virtual_resolution: size,
            },
        )
        .expect("a renderer");
        let target = device
            .create_render_target(size, TextureFormat::Rgba8Srgb)
            .expect("a target");
        let alive = |device: &mut Device, pipeline: PipelineId| {
            device.begin_offscreen_frame().expect("a frame");
            let set = device
                .begin_pass(target.into(), None)
                .expect("a pass")
                .set_pipeline(pipeline);
            device.end_offscreen_frame().expect("the end of the frame");
            match set {
                Ok(()) => true,
                Err(GfxError::StaleHandle(ResourceKind::Pipeline)) => false,
                Err(error) => panic!("{error}"),
            }
        };
        assert_eq!(Program::ALL.len(), 4);
        for (index, &program) in Program::ALL.iter().enumerate() {
            let before = programs(&renderer);
            let source = program.interface().source();
            renderer
                .reload_program(&mut device, program, source)
                .expect("the program rebuilt");
            let after = programs(&renderer);
            for (slot, (old, new)) in before.iter().zip(&after).enumerate() {
                if slot == index {
                    assert_ne!(old, new, "{}", program.name());
                    assert!(!alive(&mut device, *old), "{}: the old one", program.name());
                } else {
                    assert_eq!(old, new, "{}: another program", program.name());
                }
                assert!(alive(&mut device, *new));
            }

            let broken = ShaderSource {
                glsl_fs: "#version 330 core\nout vec4 out_color;\nvoid main() { oops }",
                ..source
            };
            assert!(matches!(
                renderer.reload_program(&mut device, program, broken),
                Err(RenderError::Gfx(GfxError::Shader { .. }))
            ));
            assert_eq!(programs(&renderer), after, "{}: refused", program.name());
            assert!(alive(&mut device, after[index]));
        }
    }
}