Skip to main content

nadir_render/
renderer.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The renderer: draws a frame's sprites, texts and tile layers into the
16//! virtual image, scales that up into the output, then draws the UI on
17//! it.
18
19use std::mem;
20use std::time::Instant;
21
22use nadir_assets::{AssetServer, LoadState};
23use nadir_core::{IRect, IVec2, UVec2, Vec2};
24use nadir_gfx::{
25    BufferDesc, BufferId, BufferKind, BufferUsage, Device, GfxError, PassTarget, PipelineDesc,
26    PipelineId, RenderTargetId, Sampler, ShaderSource, TextureFormat, TextureId, TimerId, Topology,
27    VertexLayout, VertexStep,
28};
29
30use crate::batcher::Pipe;
31use crate::chunks::{self, ChunkDraw, Step, TileCache};
32use crate::glyphs::{Server, TextPass};
33use crate::shader::{BLIT, Interface, Program, SPRITE, TEXT, TILE_CHUNK, packed};
34use crate::timing::{GpuTimes, TimerRing};
35use crate::ui::UiPass;
36use crate::view::{self, Upscale, View};
37use crate::{
38    Camera2D, RenderError, RenderFrame, SPRITE_INSTANCE_FLOATS, SpriteBatcher, Texture, TileLayers,
39    UiScale, UiSpace,
40};
41
42/// How the renderer draws.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub struct RenderConfig {
45    /// The size of the virtual image the world is drawn into, in pixels.
46    /// The image is then scaled up into the output by a whole factor
47    /// (pixel-perfect mode).
48    pub virtual_resolution: UVec2,
49}
50
51/// Where a frame is shown: the window, or a render target.
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub struct Output {
54    /// The target. It must be [`TextureFormat::Rgba8Srgb`], as the window
55    /// is.
56    pub target: PassTarget,
57    /// Its size in pixels: for the window, its drawable size.
58    pub size: UVec2,
59}
60
61/// What a frame drew. Its draw calls into the virtual image are `batches`
62/// and `chunks`, and onto the output the blit and `ui_batches`.
63#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
64pub struct FrameStats {
65    /// The sprites of the world drawn.
66    pub sprites: u32,
67    /// The sprites, and the glyphs of texts laid out, of the world and of
68    /// the UI, not drawn because their texture is not ready: still loading,
69    /// failed with no placeholder to show
70    /// ([`OnFailure::Nothing`](nadir_assets::OnFailure)), or unknown to the
71    /// asset server.
72    pub skipped: u32,
73    /// The instanced draws of the world's sprites and texts' glyphs.
74    pub batches: u32,
75    /// The tiles drawn, of every tile layer.
76    pub tiles: u32,
77    /// The instanced draws of tiles: one for each chunk drawn.
78    pub chunks: u32,
79    /// The world's texts laid out and drawn, glyphs not ready aside.
80    pub texts: u32,
81    /// The glyphs drawn, of every text of the world: each a quad, as a
82    /// sprite is.
83    pub glyphs: u32,
84    /// The texts of the world and of the UI not drawn: their font, its
85    /// atlas or its sprite not ready, not loaded, or not the font's.
86    pub skipped_texts: u32,
87    /// The UI's sprites drawn: not those wholly outside their view's clip.
88    pub ui_sprites: u32,
89    /// The UI's glyphs drawn: not those wholly outside their view's clip.
90    pub ui_glyphs: u32,
91    /// The UI's texts laid out, glyphs not ready or cut aside.
92    pub ui_texts: u32,
93    /// The instanced draws of the UI's sprites and glyphs onto the output.
94    pub ui_batches: u32,
95}
96
97/// Draws with `draw`, timed by `timer` if there is one. The timer stops
98/// whether the drawing fails or not, so that the next frame can run one.
99fn timed(
100    device: &mut Device,
101    timer: Option<TimerId>,
102    draw: impl FnOnce(&mut Device) -> Result<(), RenderError>,
103) -> Result<(), RenderError> {
104    let Some(timer) = timer else {
105        return draw(device);
106    };
107    device.begin_timer(timer)?;
108    let drawn = draw(device);
109    let ended = device.end_timer();
110    drawn?;
111    Ok(ended?)
112}
113
114/// The unit quad, as a triangle strip: (0, 0) to (1, 1).
115const QUAD: [f32; 8] = [0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0];
116
117/// The blit's quad, as a triangle strip: clip-space corners, then texture
118/// coordinates. GL stores a render target from its bottom row, so the
119/// bottom of clip space (y = -1) samples v = 0.
120const BLIT_QUAD: [f32; 16] = [
121    -1.0, -1.0, 0.0, 0.0, //
122    1.0, -1.0, 1.0, 0.0, //
123    -1.0, 1.0, 0.0, 1.0, //
124    1.0, 1.0, 1.0, 1.0,
125];
126
127/// The most attributes a vertex buffer slot of a program has room for: as
128/// many as OpenGL 3.3 has in all.
129const ATTRIBUTES: usize = 16;
130
131/// The instances the buffer holds at first. It grows by doubling, and
132/// never shrinks.
133const FIRST_CAPACITY: usize = 256;
134
135/// A tile layer of the frame that draws at least one chunk.
136#[derive(Clone, Copy, Debug)]
137struct ReadyLayer {
138    /// Its layer and depth, as the high bits of a sprite's sort key.
139    layer: u8,
140    depth: u32,
141    /// Its place among the frame's tile layers.
142    submission: u32,
143    texture: TextureId,
144    uniform: [u32; 12],
145    /// Its draws, in `Renderer::chunk_draws`.
146    first: u32,
147    end: u32,
148}
149
150/// The program a pass has bound last.
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152enum Bound {
153    Nothing,
154    Sprites,
155    Text,
156    Tiles,
157}
158
159/// The 2D renderer.
160///
161/// Each frame, [`Renderer::render`] draws the sprites, texts and tile
162/// layers into a render target of the virtual resolution: the sprites and
163/// the texts' glyphs sorted by layer and depth and batched by texture and
164/// program, each tile layer at its own layer and depth among them, a chunk
165/// at a time. It then scales that image up into the output by the largest
166/// whole factor that fits, with bars in the clear color around it, and
167/// draws the frame's [`UiList`](crate::UiList) on the output, at its
168/// resolution.
169pub struct Renderer {
170    virtual_size: UVec2,
171    sprite: PipelineId,
172    tile_chunk: PipelineId,
173    blit: PipelineId,
174    text: PipelineId,
175    quad: BufferId,
176    blit_quad: BufferId,
177    instances: BufferId,
178    /// Instances the buffer holds.
179    capacity: usize,
180    world: RenderTargetId,
181    batcher: SpriteBatcher<TextureId>,
182    texts: TextPass<TextureId>,
183    ui: UiPass<TextureId>,
184    tiles: TileCache,
185    // The tile work of a frame, in lists reused from frame to frame.
186    ready: Vec<ReadyLayer>,
187    chunk_draws: Vec<ChunkDraw>,
188    /// (Position among the sprites, index in `ready`) of each ready layer.
189    positions: Vec<(u32, u32)>,
190    steps: Vec<Step<(TextureId, Pipe)>>,
191    /// Whether the passes are timed on the GPU.
192    gpu_timing: bool,
193    timing: TimerRing<TimerId>,
194}
195
196impl Renderer {
197    /// Makes the renderer's pipelines, buffers and virtual image.
198    ///
199    /// # Errors
200    ///
201    /// [`RenderError::BadConfig`] for an empty virtual resolution, and
202    /// [`RenderError::Gfx`] if the device refuses, for instance a virtual
203    /// resolution over [`nadir_gfx::Caps::max_texture_size`].
204    pub fn new(device: &mut Device, config: &RenderConfig) -> Result<Self, RenderError> {
205        let virtual_size = config.virtual_resolution;
206        if virtual_size.x == 0 || virtual_size.y == 0 {
207            return Err(RenderError::BadConfig("the virtual resolution is empty"));
208        }
209
210        let sprite = pipeline(device, &SPRITE, SPRITE.source())?;
211        let tile_chunk = pipeline(device, &TILE_CHUNK, TILE_CHUNK.source())?;
212        let blit = pipeline(device, &BLIT, BLIT.source())?;
213        let text = pipeline(device, &TEXT, TEXT.source())?;
214
215        let quad = device.create_buffer(&BufferDesc {
216            label: "unit quad",
217            kind: BufferKind::Vertex,
218            usage: BufferUsage::Static,
219            size: size_of_val(&QUAD),
220        })?;
221        device.write_buffer(quad, 0, &QUAD)?;
222        let blit_quad = device.create_buffer(&BufferDesc {
223            label: "blit quad",
224            kind: BufferKind::Vertex,
225            usage: BufferUsage::Static,
226            size: size_of_val(&BLIT_QUAD),
227        })?;
228        device.write_buffer(blit_quad, 0, &BLIT_QUAD)?;
229        let instances = instance_buffer(device, FIRST_CAPACITY)?;
230        let world = device.create_render_target(virtual_size, TextureFormat::Rgba8Srgb)?;
231        Ok(Self {
232            virtual_size,
233            sprite,
234            tile_chunk,
235            blit,
236            text,
237            quad,
238            blit_quad,
239            instances,
240            capacity: FIRST_CAPACITY,
241            world,
242            batcher: SpriteBatcher::new(),
243            texts: TextPass::new(),
244            ui: UiPass::new(),
245            tiles: TileCache::default(),
246            ready: Vec::new(),
247            chunk_draws: Vec::new(),
248            positions: Vec::new(),
249            steps: Vec::new(),
250            gpu_timing: false,
251            timing: TimerRing::new(),
252        })
253    }
254
255    /// Times the passes of each [`Renderer::render`] on the GPU, or stops:
256    /// off at first. On a device without
257    /// [`Caps::timer_queries`](nadir_gfx::Caps::timer_queries) nothing is
258    /// timed.
259    ///
260    /// Each render's times are read back by a later render, two later
261    /// while the GPU keeps up, so that reading never waits for the GPU:
262    /// [`Renderer::gpu_times`]. A render is not timed while the GPU has not
263    /// done the work of the one four renders before it. Timing makes the
264    /// device's timers at its first renders, two a render for four renders,
265    /// which the device keeps until it is dropped. Stopping forgets the
266    /// renders that wait.
267    ///
268    /// A device runs one timer at a time: while timing is on, a timer of
269    /// the caller's running around `render` makes it fail with
270    /// [`GfxError::FrameOrder`].
271    pub fn set_gpu_timing(&mut self, on: bool) {
272        if !on {
273            self.timing.reset();
274        }
275        self.gpu_timing = on;
276    }
277
278    /// Whether the passes are timed on the GPU: [`Renderer::set_gpu_timing`].
279    pub fn gpu_timing(&self) -> bool {
280        self.gpu_timing
281    }
282
283    /// The GPU's times over the passes of earlier renders that the last
284    /// [`Renderer::render`] read back, oldest first: none while timing is
285    /// off ([`Renderer::set_gpu_timing`]), on a device without timer
286    /// queries, and when no render had all its results yet. Each says how
287    /// many renders back it was drawn ([`GpuTimes::renders_ago`]).
288    ///
289    /// A time longer than the time that passed since its render started is
290    /// the driver's mistake (llvmpipe gives one for a context's first
291    /// drawing), and is dropped, with a warning the first time.
292    pub fn gpu_times(&self) -> &[GpuTimes] {
293        self.timing.read()
294    }
295
296    /// Builds `program` again from `source`, for shaders edited while the
297    /// game runs: the next [`Renderer::render`] draws with it, and the
298    /// program it replaces is destroyed. Call it between frames, or in one
299    /// before `render`.
300    ///
301    /// The sources may change anything but the program's interface, which
302    /// the sources it was compiled with declare, its files under
303    /// [`SHADER_DIR`](crate::SHADER_DIR) as they were:
304    ///
305    /// - each `in` variable of the vertex shader is one of the program's
306    ///   attributes, with its location and no other layout qualifier, its
307    ///   type and its name;
308    /// - each uniform block, in either shader, is one of its blocks, whose
309    ///   members must stay as they are: the device checks a block by its
310    ///   size alone;
311    /// - each other uniform is one of its samplers, a `sampler2D`, or has a
312    ///   value of its own (`= …`);
313    /// - the fragment shader has one output, an `out vec4` at location 0
314    ///   and index 0, and writes no `gl_FragColor` or `gl_FragData`.
315    ///
316    /// An attribute, a block or a sampler the sources leave out is taken.
317    /// The declarations are read as written, before a macro is expanded or
318    /// a branch of an `#if` chosen: a declaration a macro makes is not
319    /// seen, and every branch is read. Sources whose braces do not pair up,
320    /// or whose branches do not each hold whole declarations, are refused.
321    ///
322    /// The renderer reads no file: the caller reads the sources, and gives
323    /// them here. A device without Metal reads only the GLSL.
324    ///
325    /// # Errors
326    ///
327    /// [`RenderError::Gfx`] with [`GfxError::Interface`] saying what differs
328    /// when the sources declare another interface, or a uniform block of
329    /// another size; with [`GfxError::Shader`] and the driver's log when
330    /// they do not compile or link; with another [`GfxError`] when the
331    /// device refuses a call. The renderer keeps the program it had, and
332    /// the next frame draws as the last did.
333    pub fn reload_program(
334        &mut self,
335        device: &mut Device,
336        program: Program,
337        source: ShaderSource<'_>,
338    ) -> Result<(), RenderError> {
339        let interface = program.interface();
340        interface
341            .check(source.glsl_vs, source.glsl_fs)
342            .map_err(|reason| GfxError::Interface {
343                label: interface.name.to_string(),
344                reason,
345            })?;
346        let rebuilt = pipeline(device, interface, source)?;
347        let slot = match program {
348            Program::Sprite => &mut self.sprite,
349            Program::TileChunk => &mut self.tile_chunk,
350            Program::Blit => &mut self.blit,
351            Program::Text => &mut self.text,
352        };
353        device.destroy(mem::replace(slot, rebuilt));
354        Ok(())
355    }
356
357    /// Draws `frame` into `output`, with the tile layers its
358    /// [`TileLayerDraw`](crate::TileLayerDraw)s name in `tiles`. Call it
359    /// inside a frame of the device (`begin_frame` and `end_frame`, or their
360    /// offscreen forms).
361    ///
362    /// Each text is laid out in its [`Font`](crate::Font), whose atlas file
363    /// and pages it finds by their paths in `assets`: a text whose font or
364    /// atlas is not ready is not drawn, nor a glyph whose page is not. A
365    /// font whose atlas or page is not loaded at all, or whose atlas has no
366    /// sprite of its name or too few frames, is logged once; so is each
367    /// character a font lacks, which draws the font's fallback. A glyph on
368    /// a page that failed shows the placeholder, as a sprite does, with the
369    /// sprite program.
370    ///
371    /// Sprites whose texture is still loading are not drawn. A texture that
372    /// failed to load shows its placeholder, all of it, whatever the
373    /// sprite's `uv`, when the server shows placeholders
374    /// ([`OnFailure::Placeholder`](nadir_assets::OnFailure)); otherwise its
375    /// sprites are not drawn either. Tile layers do the same with their tile
376    /// set's texture, every tile showing all of a placeholder.
377    ///
378    /// A tile layer that is not in `tiles` is not drawn. The renderer keeps
379    /// each chunk of a layer on the GPU once the view has shown it, packs it
380    /// again only after one of its tiles changes, and frees a layer's chunks
381    /// at the first frame after it leaves `tiles`.
382    ///
383    /// The UI is drawn last, on the output, in the order its
384    /// [`UiList`](crate::UiList) says, each sprite and text in its view's
385    /// [`UiSpace`] for an output of `output.size` and cut to its clip; its
386    /// textures and fonts are found as the world's are.
387    ///
388    /// # Errors
389    ///
390    /// [`RenderError::Gfx`] if the device refuses a call.
391    pub fn render(
392        &mut self,
393        device: &mut Device,
394        assets: &AssetServer,
395        tiles: &TileLayers,
396        frame: &RenderFrame,
397        output: Output,
398    ) -> Result<FrameStats, RenderError> {
399        let timers = if self.gpu_timing && device.caps().timer_queries {
400            self.timing.begin_render(device, Instant::now())?
401        } else {
402            None
403        };
404        let [world_timer, output_timer] = match timers {
405            Some([world, output]) => [Some(world), Some(output)],
406            None => [None, None],
407        };
408        let textures = assets.assets::<Texture>();
409        let texture = |handle| {
410            let textures = textures?;
411            let texture = textures.get(handle)?;
412            let failed = textures.state(handle) == Some(LoadState::Failed);
413            Some((texture.id(), failed))
414        };
415        self.texts.build(&frame.texts, &Server(assets));
416        self.batcher
417            .build_with(&frame.sprites, &self.texts.quads, &frame.camera, |sprite| {
418                texture(sprite.texture)
419            });
420        // The world's glyphs are packed: the text pass lays out the UI's
421        // next, its logs once a font and character for both.
422        let world_texts = (
423            self.texts.texts,
424            self.texts.skipped_texts,
425            self.texts.skipped_glyphs,
426        );
427        self.texts.build(frame.ui.texts(), &Server(assets));
428        self.ui.build(
429            &frame.ui,
430            &self.texts.quads,
431            self.virtual_size,
432            output.size,
433            |sprite| texture(sprite.texture),
434        );
435
436        let view = View::new(&frame.camera, self.virtual_size);
437        self.prepare_tiles(device, tiles, frame, &view, texture)?;
438        let mut stats = self.batcher.stats();
439        let (texts, skipped_texts, skipped_glyphs) = world_texts;
440        stats.skipped += skipped_glyphs + self.ui.skipped + self.texts.skipped_glyphs;
441        stats.texts = texts;
442        stats.skipped_texts = skipped_texts + self.texts.skipped_texts;
443        stats.ui_sprites = self.ui.sprites;
444        stats.ui_glyphs = self.ui.glyphs;
445        stats.ui_texts = self.texts.texts;
446        // Each plan numbers its sprites and glyphs together with a u32;
447        // the UI's instances go after the world's.
448        let world = (stats.sprites + stats.glyphs) as usize;
449        let count = world + (self.ui.sprites + self.ui.glyphs) as usize;
450        if count > self.capacity {
451            let capacity = count.next_power_of_two().max(self.capacity * 2);
452            let instances = instance_buffer(device, capacity)?;
453            device.destroy(self.instances);
454            self.instances = instances;
455            self.capacity = capacity;
456        }
457        if world > 0 {
458            device.write_buffer(self.instances, 0, self.batcher.instances())?;
459        }
460        if count > world {
461            let offset = world * SPRITE_INSTANCE_FLOATS;
462            device.write_buffer(self.instances, offset, &self.ui.packed)?;
463        }
464
465        let clear = frame.clear.to_linear();
466        stats.batches = 0;
467        timed(device, world_timer, |device| {
468            let mut pass = device.begin_pass(self.world.into(), Some(clear))?;
469            pass.set_uniforms(0, &view.uniform())?;
470            let mut bound = Bound::Nothing;
471            for &step in &self.steps {
472                match step {
473                    Step::Sprites {
474                        texture: (texture, pipe),
475                        start,
476                        count,
477                    } => {
478                        // A tile layer between two batches, or in one,
479                        // leaves its own program and buffers bound. The
480                        // sprite and text programs share the instances.
481                        let (wanted, pipeline) = match pipe {
482                            Pipe::Sprite => (Bound::Sprites, self.sprite),
483                            Pipe::Text => (Bound::Text, self.text),
484                        };
485                        if bound != wanted {
486                            pass.set_pipeline(pipeline)?;
487                            pass.set_vertex_buffer(0, self.instances, 0)?;
488                            pass.set_vertex_buffer(1, self.quad, 0)?;
489                            bound = wanted;
490                        }
491                        pass.set_texture(0, texture, Sampler::NearestClamp)?;
492                        pass.draw(0..4, start..start + count)?;
493                        stats.batches += 1;
494                    }
495                    Step::Tiles(index) => {
496                        let layer = self.ready[index as usize];
497                        if bound != Bound::Tiles {
498                            pass.set_pipeline(self.tile_chunk)?;
499                            pass.set_vertex_buffer(1, self.quad, 0)?;
500                            bound = Bound::Tiles;
501                        }
502                        pass.set_uniforms(1, &layer.uniform)?;
503                        pass.set_texture(0, layer.texture, Sampler::NearestClamp)?;
504                        for chunk in &self.chunk_draws[layer.first as usize..layer.end as usize] {
505                            pass.set_vertex_buffer(0, chunk.buffer, 0)?;
506                            pass.draw(0..4, 0..chunk.count)?;
507                            stats.tiles += chunk.count;
508                            stats.chunks += 1;
509                        }
510                    }
511                }
512            }
513            Ok(())
514        })?;
515        timed(device, output_timer, |device| {
516            let upscale = self.upscale(output.size);
517            let mut pass = device.begin_pass(output.target, Some(clear))?;
518            pass.set_viewport(upscale.rect);
519            pass.set_pipeline(self.blit)?;
520            pass.set_vertex_buffer(0, self.blit_quad, 0)?;
521            pass.set_texture(0, self.world, Sampler::NearestClamp)?;
522            pass.draw(0..4, 0..1)?;
523
524            if !self.ui.batches.is_empty() {
525                // The UI is packed in output pixels: one camera for all of
526                // it, each view's clip a scissor.
527                let side = |side: u32| i32::try_from(side).unwrap_or(i32::MAX);
528                let pixels = IVec2::new(side(output.size.x), side(output.size.y));
529                pass.set_viewport(IRect::new(IVec2::ZERO, pixels));
530                let size = output.size.as_vec2();
531                pass.set_uniforms(0, &[2.0 / size.x, -2.0 / size.y, -1.0, 1.0])?;
532                // The UI's instances follow the world's, fewer than u32::MAX.
533                let base = world as u32;
534                let mut bound = Bound::Nothing;
535                let mut view = None;
536                for batch in &self.ui.batches {
537                    let (texture, pipe) = batch.texture;
538                    let (wanted, pipeline) = match pipe {
539                        Pipe::Sprite => (Bound::Sprites, self.sprite),
540                        Pipe::Text => (Bound::Text, self.text),
541                    };
542                    if bound != wanted {
543                        pass.set_pipeline(pipeline)?;
544                        pass.set_vertex_buffer(0, self.instances, 0)?;
545                        pass.set_vertex_buffer(1, self.quad, 0)?;
546                        bound = wanted;
547                    }
548                    if view != Some(batch.view) {
549                        pass.set_scissor(self.ui.scissor(batch.view));
550                        view = Some(batch.view);
551                    }
552                    pass.set_texture(0, texture, Sampler::NearestClamp)?;
553                    let start = base + batch.start;
554                    pass.draw(0..4, start..start + batch.count)?;
555                    stats.ui_batches += 1;
556                }
557            }
558            Ok(())
559        })?;
560        self.timing.end_render();
561        Ok(stats)
562    }
563
564    /// Before the world pass, which borrows the device: frees the chunks of
565    /// layers gone from `tiles`, culls and uploads the chunks of the frame's
566    /// tile layers, and orders the pass's draws, with each layer that draws
567    /// a chunk among the sprites.
568    fn prepare_tiles(
569        &mut self,
570        device: &mut Device,
571        tiles: &TileLayers,
572        frame: &RenderFrame,
573        view: &View,
574        texture: impl Fn(nadir_assets::Handle<Texture>) -> Option<(TextureId, bool)>,
575    ) -> Result<(), RenderError> {
576        self.tiles.evict(device, tiles);
577        self.ready.clear();
578        self.chunk_draws.clear();
579        let clock = chunks::clock_ms(frame.time);
580        let shown = view.world_rect();
581        // A frame of more than u32::MAX tile layers is far past any
582        // budget; such layers are not drawn.
583        for (submission, draw) in (0..u32::MAX).zip(&frame.tile_layers) {
584            let Some(layer) = tiles.get(draw.tiles) else {
585                continue;
586            };
587            let Some((texture, placeholder)) = texture(layer.tileset().texture) else {
588                continue;
589            };
590            let Some(range) = chunks::visible_chunks(layer, shown) else {
591                continue;
592            };
593            // Fewer draws than chunks in all the layers, so they fit.
594            let first = self.chunk_draws.len() as u32;
595            self.tiles
596                .prepare(device, draw.tiles, layer, range, &mut self.chunk_draws)?;
597            let end = self.chunk_draws.len() as u32;
598            if end > first {
599                self.ready.push(ReadyLayer {
600                    layer: draw.layer,
601                    depth: draw.depth,
602                    submission,
603                    texture,
604                    uniform: chunks::layer_uniform(layer, view.zoom(), placeholder, clock),
605                    first,
606                    end,
607                });
608            }
609        }
610        self.ready
611            .sort_unstable_by_key(|layer| (layer.layer, layer.depth, layer.submission));
612        self.positions.clear();
613        for (index, layer) in (0..).zip(&self.ready) {
614            let position = self.batcher.position(layer.layer, layer.depth);
615            self.positions.push((position, index));
616        }
617        chunks::steps(self.batcher.batches(), &self.positions, &mut self.steps);
618        Ok(())
619    }
620
621    /// Where the virtual image lands in an output of `size`.
622    pub fn upscale(&self, size: UVec2) -> Upscale {
623        Upscale::new(self.virtual_size, size)
624    }
625
626    /// Where the UI at `scale` lands in an output of `size`, as it is drawn
627    /// there: [`UiSpace::new`] with the renderer's virtual resolution. Its
628    /// [`UiSpace::to_ui`] gives the UI point under the pointer.
629    pub fn ui_space(&self, scale: UiScale, size: UVec2) -> UiSpace {
630        UiSpace::new(scale, self.virtual_size, size)
631    }
632
633    /// The world point under `screen`, in pixels from the top left of an
634    /// output of `size`, as `camera` shows it: for aiming with the mouse.
635    pub fn screen_to_world(&self, camera: &Camera2D, size: UVec2, screen: Vec2) -> Vec2 {
636        let view = View::new(camera, self.virtual_size);
637        view.unproject(view::screen_to_virtual(&self.upscale(size), screen))
638    }
639
640    /// Where `world` is in an output of `size`, in pixels from its top
641    /// left, as `camera` shows it.
642    pub fn world_to_screen(&self, camera: &Camera2D, size: UVec2, world: Vec2) -> Vec2 {
643        let view = View::new(camera, self.virtual_size);
644        view::virtual_to_screen(&self.upscale(size), view.project(world))
645    }
646}
647
648/// Makes the pipeline of the program `interface` from `source`: its
649/// instances, if it has any, in vertex buffer slot 0, and its vertices in
650/// the next.
651fn pipeline(
652    device: &mut Device,
653    interface: &Interface,
654    source: ShaderSource<'_>,
655) -> Result<PipelineId, RenderError> {
656    let (instance, instance_stride) = packed::<ATTRIBUTES>(interface.instance);
657    let (vertex, vertex_stride) = packed::<ATTRIBUTES>(interface.vertex_attributes);
658    let layouts = [
659        VertexLayout {
660            stride: instance_stride,
661            step: VertexStep::Instance,
662            attributes: &instance[..interface.instance.len()],
663        },
664        VertexLayout {
665            stride: vertex_stride,
666            step: VertexStep::Vertex,
667            attributes: &vertex[..interface.vertex_attributes.len()],
668        },
669    ];
670    let vertex_layouts = if interface.instance.is_empty() {
671        &layouts[1..]
672    } else {
673        &layouts[..]
674    };
675    const {
676        assert!(
677            SPRITE.instance.len() <= ATTRIBUTES
678                && SPRITE.vertex_attributes.len() <= ATTRIBUTES
679                && TILE_CHUNK.instance.len() <= ATTRIBUTES
680                && TILE_CHUNK.vertex_attributes.len() <= ATTRIBUTES
681                && BLIT.instance.len() <= ATTRIBUTES
682                && BLIT.vertex_attributes.len() <= ATTRIBUTES
683                && TEXT.instance.len() <= ATTRIBUTES
684                && TEXT.vertex_attributes.len() <= ATTRIBUTES,
685            "a program has more attributes than a slot has room for"
686        );
687    }
688    Ok(device.create_pipeline(&PipelineDesc {
689        label: interface.name,
690        shader: source,
691        vertex_layouts,
692        uniform_blocks: interface.uniform_blocks,
693        textures: interface.textures,
694        blend: interface.blend,
695        topology: Topology::TriangleStrip,
696        target_format: TextureFormat::Rgba8Srgb,
697    })?)
698}
699
700fn instance_buffer(device: &mut Device, capacity: usize) -> Result<BufferId, RenderError> {
701    Ok(device.create_buffer(&BufferDesc {
702        label: "sprite and glyph instances",
703        kind: BufferKind::Vertex,
704        usage: BufferUsage::Dynamic,
705        size: capacity * SPRITE_INSTANCE_FLOATS * size_of::<f32>(),
706    })?)
707}
708
709/// Reloads on a GPU: what is destroyed, and what is kept.
710#[cfg(all(test, feature = "headless-test"))]
711mod gpu_tests {
712    use nadir_gfx::{GfxError, ResourceKind};
713
714    use super::*;
715
716    /// A device on an offscreen context, or `None` where this system has
717    /// none yet and no renderer is asked for, as the headless tests do.
718    fn device() -> Option<Device> {
719        let expected = std::env::var("NADIR_EXPECT_GL_RENDERER").unwrap_or_default();
720        match Device::new_headless() {
721            Ok(device) => {
722                let renderer = &device.caps().renderer;
723                assert!(
724                    renderer.contains(&expected),
725                    "the renderer is `{renderer}`, not `{expected}`"
726                );
727                Some(device)
728            }
729            Err(GfxError::NoOffscreenContext) if expected.is_empty() => None,
730            Err(error) => panic!("no headless device: {error}"),
731        }
732    }
733
734    /// The renderer's programs, in the order of `Program::ALL`.
735    fn programs(renderer: &Renderer) -> [PipelineId; 4] {
736        [
737            renderer.sprite,
738            renderer.tile_chunk,
739            renderer.blit,
740            renderer.text,
741        ]
742    }
743
744    #[test]
745    fn a_reload_destroys_the_program_it_replaces_and_a_refused_one_keeps_it() {
746        let Some(mut device) = device() else { return };
747        let size = UVec2::new(4, 4);
748        let mut renderer = Renderer::new(
749            &mut device,
750            &RenderConfig {
751                virtual_resolution: size,
752            },
753        )
754        .expect("a renderer");
755        let target = device
756            .create_render_target(size, TextureFormat::Rgba8Srgb)
757            .expect("a target");
758        let alive = |device: &mut Device, pipeline: PipelineId| {
759            device.begin_offscreen_frame().expect("a frame");
760            let set = device
761                .begin_pass(target.into(), None)
762                .expect("a pass")
763                .set_pipeline(pipeline);
764            device.end_offscreen_frame().expect("the end of the frame");
765            match set {
766                Ok(()) => true,
767                Err(GfxError::StaleHandle(ResourceKind::Pipeline)) => false,
768                Err(error) => panic!("{error}"),
769            }
770        };
771        assert_eq!(Program::ALL.len(), 4);
772        for (index, &program) in Program::ALL.iter().enumerate() {
773            let before = programs(&renderer);
774            let source = program.interface().source();
775            renderer
776                .reload_program(&mut device, program, source)
777                .expect("the program rebuilt");
778            let after = programs(&renderer);
779            for (slot, (old, new)) in before.iter().zip(&after).enumerate() {
780                if slot == index {
781                    assert_ne!(old, new, "{}", program.name());
782                    assert!(!alive(&mut device, *old), "{}: the old one", program.name());
783                } else {
784                    assert_eq!(old, new, "{}: another program", program.name());
785                }
786                assert!(alive(&mut device, *new));
787            }
788
789            let broken = ShaderSource {
790                glsl_fs: "#version 330 core\nout vec4 out_color;\nvoid main() { oops }",
791                ..source
792            };
793            assert!(matches!(
794                renderer.reload_program(&mut device, program, broken),
795                Err(RenderError::Gfx(GfxError::Shader { .. }))
796            ));
797            assert_eq!(programs(&renderer), after, "{}: refused", program.name());
798            assert!(alive(&mut device, after[index]));
799        }
800    }
801}