Skip to main content

nadir_render/
ui.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 UI: sprites and texts drawn on the output after the world is scaled
16//! up into it, at the output's resolution, by layer and depth and then in
17//! the order they are pushed (ADR-0055).
18
19use std::fmt;
20
21use nadir_core::{IRect, IVec2, Rect, UVec2, Vec2};
22
23use crate::batcher::Pipe;
24use crate::instance::{instance, pivot_offset, uv_and_pivot};
25use crate::plan::GlyphQuad;
26use crate::view::{Upscale, snap};
27use crate::{SPRITE_INSTANCE_FLOATS, SortMode, SpriteDraw, TextDraw, TextList};
28
29/// The smallest free scale: an eighth of an output pixel per UI unit.
30const MIN_FREE_SCALE: f32 = 1.0 / 8.0;
31
32/// The largest free scale: 64 output pixels per UI unit.
33const MAX_FREE_SCALE: f32 = 64.0;
34
35/// How the UI units of a [`UiView`] map onto the output.
36#[non_exhaustive]
37#[derive(Clone, Copy, Debug, PartialEq)]
38pub enum UiScale {
39    /// Pixel UI: a UI unit is this many pixels of the virtual image (0 is
40    /// 1), scaled up with the world by the upscale's whole factor, from the
41    /// image's top-left corner, and cut to the image: nothing is drawn on
42    /// the bars around it. Corners snap to whole UI units, so its pixels
43    /// line up as the world's do. The default, `Pixel(1)`, is the virtual
44    /// image's own pixels.
45    Pixel(u32),
46    /// A free scale: output pixels per UI unit, from the output's top-left
47    /// corner, over all of it, bars included: the settings' UI scale.
48    ///
49    /// The pixels are the output's, which are physical: where the desktop
50    /// doubles its pixels, 2 is the size its 1 looks. Corners snap to whole
51    /// output pixels. A scale that is not whole puts some texels on more
52    /// pixels than others, and a texel's edge on the middle of a pixel,
53    /// which GPUs may sample differently. Below 1/8 (0 and negatives too)
54    /// is 1/8, above 64 is 64, and NaN is 1.
55    Free(f32),
56}
57
58impl Default for UiScale {
59    fn default() -> Self {
60        Self::Pixel(1)
61    }
62}
63
64impl UiScale {
65    /// The scale drawn: a multiple of 0 is 1, and a free scale held
66    /// between 1/8 and 64, NaN 1, so that views of one scale are equal.
67    fn held(self) -> Self {
68        match self {
69            Self::Pixel(multiple) => Self::Pixel(multiple.max(1)),
70            Self::Free(scale) if scale.is_nan() => Self::Free(1.0),
71            Self::Free(scale) => Self::Free(scale.clamp(MIN_FREE_SCALE, MAX_FREE_SCALE)),
72        }
73    }
74}
75
76/// The scale and the clip of the UI's sprites and texts:
77/// [`UiList::set_view`] sets the view of those pushed after it.
78#[derive(Clone, Copy, Debug, Default, PartialEq)]
79pub struct UiView {
80    scale: UiScale,
81    clip: Option<Rect>,
82}
83
84impl UiView {
85    /// A view at `scale`, cut only to its space's edges
86    /// ([`UiSpace::rect`]). Its scale is the one drawn: `Pixel(0)` is
87    /// `Pixel(1)`, and a free scale is held as [`UiScale::Free`] says.
88    pub fn new(scale: UiScale) -> Self {
89        Self {
90            scale: scale.held(),
91            clip: None,
92        }
93    }
94
95    /// This view cut to `rect` too, in its UI units: its clip becomes the
96    /// part of `rect` inside the clip it had, so that a clip inside a clip
97    /// (a scrolled list in a window) is cut by both. A `rect` that does
98    /// not overlap the clip, has no area, or has an edge that is NaN cuts
99    /// everything: nothing in the view is drawn. Its edges may be
100    /// infinite.
101    pub fn clipped(self, rect: Rect) -> Self {
102        let nan = rect.min.x.is_nan()
103            || rect.min.y.is_nan()
104            || rect.max.x.is_nan()
105            || rect.max.y.is_nan();
106        let inside = match self.clip {
107            _ if nan => None,
108            None => Some(rect).filter(|rect| !rect.is_empty()),
109            Some(clip) => clip.intersection(rect),
110        };
111        Self {
112            clip: Some(inside.unwrap_or(Rect::new(Vec2::ZERO, Vec2::ZERO))),
113            ..self
114        }
115    }
116
117    /// Its scale.
118    pub fn scale(&self) -> UiScale {
119        self.scale
120    }
121
122    /// Its clip, in its UI units: `None` when it is not clipped, and a rect
123    /// with no area when it cuts everything.
124    pub fn clip(&self) -> Option<Rect> {
125        self.clip
126    }
127}
128
129/// Where a [`UiScale`] puts the UI in an output: for drawing, and for
130/// finding what is under the pointer, whose position
131/// (`nadir_input::Input::pointer`) is in the output's pixels.
132#[derive(Clone, Copy, Debug, PartialEq)]
133pub struct UiSpace {
134    /// Output pixels per UI unit.
135    pub scale: f32,
136    /// The output pixel at UI point (0, 0), from the output's top left.
137    pub origin: IVec2,
138    /// The UI units from (0, 0) to the far corner of the space: the virtual
139    /// resolution over the pixel UI's multiple, or the output's size over
140    /// the free scale.
141    pub size: Vec2,
142    /// The output pixels the UI is drawn in, inside the output: the
143    /// upscaled image for pixel UI, all of the output for a free scale.
144    pub rect: IRect,
145    /// Whether corners snap to whole UI units (pixel UI), or to whole
146    /// output pixels.
147    whole_units: bool,
148}
149
150impl UiSpace {
151    /// Where `scale` puts the UI in an output of `output_size` pixels, when
152    /// the world's virtual image is `virtual_resolution` (as
153    /// [`Renderer::ui_space`](crate::Renderer::ui_space) does with its
154    /// own).
155    pub fn new(scale: UiScale, virtual_resolution: UVec2, output_size: UVec2) -> Self {
156        let output = IRect::new(
157            IVec2::ZERO,
158            IVec2::new(
159                i32::try_from(output_size.x).unwrap_or(i32::MAX),
160                i32::try_from(output_size.y).unwrap_or(i32::MAX),
161            ),
162        );
163        let inside = |rect: IRect| rect.intersection(output).unwrap_or_default();
164        match scale.held() {
165            UiScale::Pixel(multiple) => {
166                let multiple = multiple as f32;
167                let virtual_size = virtual_resolution.max(UVec2::ONE);
168                let upscale = Upscale::new(virtual_size, output_size);
169                Self {
170                    scale: upscale.factor as f32 * multiple,
171                    origin: upscale.rect.min,
172                    size: virtual_size.as_vec2() / multiple,
173                    rect: inside(upscale.rect),
174                    whole_units: true,
175                }
176            }
177            UiScale::Free(scale) => Self {
178                scale,
179                origin: IVec2::ZERO,
180                size: output_size.as_vec2() / scale,
181                rect: inside(output),
182                whole_units: false,
183            },
184        }
185    }
186
187    /// The UI point at `screen`, in pixels from the output's top left: the
188    /// pointer, in UI units.
189    pub fn to_ui(&self, screen: Vec2) -> Vec2 {
190        (screen - self.origin.as_vec2()) / self.scale
191    }
192
193    /// Where the UI point `ui` is on the output, in pixels from its top
194    /// left. A corner there is drawn at the pixel it snaps to: for pixel
195    /// UI, `ui` rounded to whole units, halves up; for a free scale, this
196    /// point rounded to a whole pixel, halves up.
197    pub fn to_screen(&self, ui: Vec2) -> Vec2 {
198        self.origin.as_vec2() + ui * self.scale
199    }
200
201    /// The output pixel a corner at the UI point `ui` is drawn at: a whole
202    /// number, or infinite.
203    fn corner(&self, ui: Vec2) -> Vec2 {
204        let origin = self.origin.as_vec2();
205        if self.whole_units {
206            origin + snap(ui) * self.scale
207        } else {
208            snap(origin + ui * self.scale)
209        }
210    }
211
212    /// The output pixels a view whose clip is `clip` draws in, or `None`
213    /// when it draws nowhere. Its edges snap as corners do.
214    fn scissor(&self, clip: Option<Rect>) -> Option<IRect> {
215        let Some(clip) = clip else {
216            return Some(self.rect).filter(|rect| !rect.is_empty());
217        };
218        pixels(self.corner(clip.min), self.corner(clip.max)).intersection(self.rect)
219    }
220}
221
222/// The pixels from `a` to `b`, corners in either order, whole numbers or
223/// infinite: those past `i32` saturate.
224fn pixels(a: Vec2, b: Vec2) -> IRect {
225    let (min, max) = (a.min(b), a.max(b));
226    IRect::new(
227        IVec2::new(min.x as i32, min.y as i32),
228        IVec2::new(max.x as i32, max.y as i32),
229    )
230}
231
232/// What one entry of a [`UiList`] is.
233#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234enum Kind {
235    Sprite,
236    Text,
237}
238
239/// One entry of a [`UiList`], in the order pushed.
240#[derive(Clone, Copy, Debug, PartialEq, Eq)]
241struct Item {
242    kind: Kind,
243    /// Its index among the list's sprites, or its texts.
244    index: u32,
245    /// Its view, in the list's views.
246    view: u32,
247}
248
249/// One entry of a [`UiList`], as [`UiList::iter`] gives it.
250#[non_exhaustive]
251#[derive(Clone, Copy, Debug, PartialEq)]
252pub enum UiDraw<'a> {
253    /// A sprite: its position and size in UI units.
254    Sprite(&'a SpriteDraw),
255    /// A text, with its draw: its position in UI units, a UI unit a pixel
256    /// of its font.
257    Text(&'a TextDraw, &'a str),
258}
259
260/// The UI of a frame ([`RenderFrame::ui`](crate::RenderFrame::ui)): sprites
261/// and texts in UI units, each drawn in the [`UiView`] set when it was
262/// pushed, after the world, at the output's resolution.
263///
264/// **Order.** They are drawn by layer, then by depth, then in the order
265/// they were pushed, sprites and texts alike: a window's panel, then its
266/// labels, then the next window over them. Higher layers are in front of
267/// lower ones; at one layer, a [`SortMode::Fixed`] depth orders them, and
268/// [`SortMode::YSort`] is depth 0: nothing is sorted by its y on screen.
269/// A text's glyphs keep their text's place, grouped by page.
270///
271/// **Views.** [`UiList::set_view`] sets the scale and the clip of what is
272/// pushed after it. It holds until the next call, across the systems that
273/// push, so a system that draws UI sets its own view first. The view
274/// before the first call is [`UiView::default`]: pixel UI, unclipped. A
275/// view changes nothing of the order: a clip only cuts.
276///
277/// **Cost.** Runs of one texture, one program and one view, in that order,
278/// are one draw each: a panel then a label then a panel are three. A
279/// quad wholly outside its view's clip, or with no pixels, is not drawn,
280/// though a text is laid out whole. The list keeps its buffers when
281/// cleared, so a frame that pushes what the last did allocates nothing.
282#[derive(Clone, Debug, Default, PartialEq)]
283pub struct UiList {
284    items: Vec<Item>,
285    sprites: Vec<SpriteDraw>,
286    texts: TextList,
287    /// Each text's place in `items`.
288    text_items: Vec<u32>,
289    views: Vec<UiView>,
290}
291
292impl UiList {
293    /// An empty list, in the default view.
294    pub fn new() -> Self {
295        Self::default()
296    }
297
298    /// Draws what is pushed from now on in `view`, until the next call.
299    pub fn set_view(&mut self, view: UiView) {
300        // A view nothing was pushed in yet goes. The entries' views only
301        // grow, so the last entry tells whether any is in the last view.
302        let used = self
303            .items
304            .last()
305            .is_some_and(|item| item.view as usize + 1 == self.views.len());
306        if !used {
307            self.views.pop();
308        }
309        if self.views.last() != Some(&view) {
310            self.views.push(view);
311        }
312    }
313
314    /// The view of what is pushed now.
315    pub fn view(&self) -> UiView {
316        self.views.last().copied().unwrap_or_default()
317    }
318
319    /// Adds `sprite`, its position and size in UI units.
320    pub fn sprite(&mut self, sprite: SpriteDraw) {
321        let Some((index, view)) = self.place(self.sprites.len()) else {
322            return;
323        };
324        self.sprites.push(sprite);
325        self.items.push(Item {
326            kind: Kind::Sprite,
327            index,
328            view,
329        });
330    }
331
332    /// Adds `text`, drawn as `draw` says, its position in UI units.
333    pub fn text(&mut self, draw: TextDraw, text: &str) {
334        let before = self.texts.len();
335        if let Some((index, view)) = self.place(before) {
336            self.texts.push(draw, text);
337            self.push_text(index, view);
338        }
339    }
340
341    /// Adds the text `args` formats, as [`TextList::write`] does: with no
342    /// allocation once the list has held as much. A text whose formatting
343    /// fails is left out.
344    pub fn write(&mut self, draw: TextDraw, args: fmt::Arguments<'_>) {
345        let before = self.texts.len();
346        if let Some((index, view)) = self.place(before) {
347            self.texts.write(draw, args);
348            if self.texts.len() > before {
349                self.push_text(index, view);
350            }
351        }
352    }
353
354    /// How many sprites and texts there are.
355    pub fn len(&self) -> usize {
356        self.items.len()
357    }
358
359    /// Whether there are none.
360    pub fn is_empty(&self) -> bool {
361        self.items.is_empty()
362    }
363
364    /// Empties the list, keeping its capacity, and puts the view back to
365    /// the default.
366    pub fn clear(&mut self) {
367        self.items.clear();
368        self.sprites.clear();
369        self.texts.clear();
370        self.text_items.clear();
371        self.views.clear();
372    }
373
374    /// The sprites and texts, in the order they were pushed, each with its
375    /// view: for checking what a UI drew without drawing it.
376    pub fn iter(&self) -> impl ExactSizeIterator<Item = (UiDraw<'_>, UiView)> + '_ {
377        self.items.iter().map(|item| {
378            let draw = match item.kind {
379                Kind::Sprite => UiDraw::Sprite(&self.sprites[item.index as usize]),
380                Kind::Text => {
381                    let (draw, text) = self.texts.at(item.index as usize);
382                    UiDraw::Text(draw, text)
383                }
384            };
385            (draw, self.views[item.view as usize])
386        })
387    }
388
389    /// The texts, for laying out.
390    pub(crate) fn texts(&self) -> &TextList {
391        &self.texts
392    }
393
394    /// The index of the next sprite or text, the `count`th of its kind, and
395    /// its view; `None` from `u32::MAX` entries on, which are left out, so
396    /// that every place and index is below `u32::MAX`.
397    fn place(&mut self, count: usize) -> Option<(u32, u32)> {
398        let below = |n: usize| u32::try_from(n).ok().filter(|&n| n < u32::MAX);
399        below(self.items.len())?;
400        let index = below(count)?;
401        if self.views.is_empty() {
402            self.views.push(UiView::default());
403        }
404        // There are no more views than entries, and one.
405        Some((index, (self.views.len() - 1) as u32))
406    }
407
408    fn push_text(&mut self, index: u32, view: u32) {
409        // `place` checked that the entries fit a u32.
410        self.text_items.push(self.items.len() as u32);
411        self.items.push(Item {
412            kind: Kind::Text,
413            index,
414            view,
415        });
416    }
417}
418
419/// The depth of a sprite or text in the UI: nothing is sorted by its y.
420fn depth(sort: SortMode) -> u32 {
421    match sort {
422        SortMode::Fixed(depth) => depth,
423        SortMode::YSort => 0,
424    }
425}
426
427/// A quad of the UI to draw: its texture and program, its view, whether it
428/// is a glyph, and its instance in output pixels.
429#[derive(Clone, Copy, Debug)]
430struct Quad<K> {
431    texture: (K, Pipe),
432    view: u32,
433    glyph: bool,
434    instance: [f32; SPRITE_INSTANCE_FLOATS],
435}
436
437/// A run of the UI's quads drawn with one texture, one program and one
438/// view.
439#[derive(Clone, Copy, Debug, PartialEq, Eq)]
440pub(crate) struct UiBatch<K> {
441    pub(crate) texture: (K, Pipe),
442    pub(crate) view: u32,
443    /// Where the run starts in the packed instances, counted in instances.
444    pub(crate) start: u32,
445    pub(crate) count: u32,
446}
447
448/// The UI of a frame, planned and packed: what the renderer draws on the
449/// output after the blit. Its lists are reused from frame to frame. `K`
450/// is a texture: the renderer's GPU texture, or a test's number.
451#[derive(Debug)]
452pub(crate) struct UiPass<K> {
453    /// Each view's space, and the pixels it draws in (`None`: nowhere).
454    views: Vec<(UiSpace, Option<IRect>)>,
455    /// (layer, depth, place, page, quad) of each quad drawn.
456    keys: Vec<(u8, u32, u32, u32, u32)>,
457    quads: Vec<Quad<K>>,
458    pub(crate) batches: Vec<UiBatch<K>>,
459    /// The instances, in draw order, in output pixels.
460    pub(crate) packed: Vec<f32>,
461    /// The sprites and glyphs drawn.
462    pub(crate) sprites: u32,
463    pub(crate) glyphs: u32,
464    /// The sprites not drawn because their texture is not ready.
465    pub(crate) skipped: u32,
466}
467
468impl<K: Copy + Eq> UiPass<K> {
469    pub(crate) fn new() -> Self {
470        Self {
471            views: Vec::new(),
472            keys: Vec::new(),
473            quads: Vec::new(),
474            batches: Vec::new(),
475            packed: Vec::new(),
476            sprites: 0,
477            glyphs: 0,
478            skipped: 0,
479        }
480    }
481
482    /// Plans and packs `list`, whose texts' glyphs are `glyphs`, laid out
483    /// from its texts, for an output of `output` pixels with the world's
484    /// image of `virtual_size`. `texture` finds a sprite's texture as the
485    /// world's does: `None` while it is not ready, else the texture and
486    /// whether it shows that texture's placeholder.
487    pub(crate) fn build(
488        &mut self,
489        list: &UiList,
490        glyphs: &[GlyphQuad<(K, Pipe)>],
491        virtual_size: UVec2,
492        output: UVec2,
493        mut texture: impl FnMut(&SpriteDraw) -> Option<(K, bool)>,
494    ) {
495        self.views.clear();
496        self.keys.clear();
497        self.quads.clear();
498        self.batches.clear();
499        self.packed.clear();
500        self.sprites = 0;
501        self.glyphs = 0;
502        self.skipped = 0;
503
504        for view in &list.views {
505            let space = UiSpace::new(view.scale, virtual_size, output);
506            self.views.push((space, space.scissor(view.clip)));
507        }
508        // The list holds fewer than u32::MAX entries.
509        for (place, item) in (0u32..).zip(&list.items) {
510            if item.kind != Kind::Sprite {
511                continue;
512            }
513            let sprite = &list.sprites[item.index as usize];
514            // What is not ready is skipped, cut or not, as a glyph is.
515            let Some((texture, placeholder)) = texture(sprite) else {
516                self.skipped += 1;
517                continue;
518            };
519            let (space, Some(scissor)) = self.views[item.view as usize] else {
520                continue;
521            };
522            let Some(instance) = pack_sprite(sprite, placeholder, &space, scissor) else {
523                continue;
524            };
525            let key = (sprite.layer, depth(sprite.sort), place, 0);
526            self.push(key, (texture, Pipe::Sprite), item.view, false, instance);
527        }
528        for glyph in glyphs {
529            let Some(&place) = list.text_items.get(glyph.text as usize) else {
530                continue;
531            };
532            let item = list.items[place as usize];
533            let (draw, _) = list.texts.at(item.index as usize);
534            let (space, Some(scissor)) = self.views[item.view as usize] else {
535                continue;
536            };
537            let Some(instance) = pack_glyph(&glyph.sprite, glyph.placeholder, &space, scissor)
538            else {
539                continue;
540            };
541            let page = glyph.sprite.texture.id().index();
542            let key = (draw.layer, depth(draw.sort), place, page);
543            self.push(key, glyph.texture, item.view, true, instance);
544        }
545
546        self.keys.sort_unstable();
547        for &(.., quad) in &self.keys {
548            let quad = &self.quads[quad as usize];
549            // Fewer quads than u32::MAX: one for each sprite or glyph.
550            let position = (self.packed.len() / SPRITE_INSTANCE_FLOATS) as u32;
551            self.packed.extend_from_slice(&quad.instance);
552            if quad.glyph {
553                self.glyphs += 1;
554            } else {
555                self.sprites += 1;
556            }
557            match self.batches.last_mut() {
558                Some(batch) if batch.texture == quad.texture && batch.view == quad.view => {
559                    batch.count += 1;
560                }
561                _ => self.batches.push(UiBatch {
562                    texture: quad.texture,
563                    view: quad.view,
564                    start: position,
565                    count: 1,
566                }),
567            }
568        }
569    }
570
571    /// The pixels the `view`th view draws in: one that draws, as every
572    /// batch's does.
573    pub(crate) fn scissor(&self, view: u32) -> Option<IRect> {
574        self.views
575            .get(view as usize)
576            .and_then(|&(_, scissor)| scissor)
577    }
578
579    fn push(
580        &mut self,
581        (layer, depth, place, page): (u8, u32, u32, u32),
582        texture: (K, Pipe),
583        view: u32,
584        glyph: bool,
585        instance: [f32; SPRITE_INSTANCE_FLOATS],
586    ) {
587        // A quad for each sprite or glyph, fewer than u32::MAX of them.
588        let Some(index) = u32::try_from(self.quads.len())
589            .ok()
590            .filter(|&index| index < u32::MAX)
591        else {
592            return;
593        };
594        self.quads.push(Quad {
595            texture,
596            view,
597            glyph,
598            instance,
599        });
600        self.keys.push((layer, depth, place, page, index));
601    }
602}
603
604/// The instance of a UI sprite in output pixels, or `None` when it has no
605/// pixels or none inside `scissor`.
606///
607/// Unrotated, both of its corners snap ([`UiSpace::corner`]), so that two
608/// sprites that share an edge in UI units share it on the output at any
609/// scale, and its size is what is between them. Rotated, it is scaled and
610/// not moved, and culled by the box around its corners.
611fn pack_sprite(
612    sprite: &SpriteDraw,
613    placeholder: bool,
614    space: &UiSpace,
615    scissor: IRect,
616) -> Option<[f32; SPRITE_INSTANCE_FLOATS]> {
617    let (uv, pivot) = uv_and_pivot(sprite, placeholder);
618    if sprite.rotation != 0.0 {
619        let position = space.origin.as_vec2() + sprite.position * space.scale;
620        let size = sprite.size * space.scale;
621        // The corners as the shader turns them, clockwise about the pivot.
622        let (sin, cos) = sprite.rotation.sin_cos();
623        let mut min = Vec2::splat(f32::INFINITY);
624        let mut max = Vec2::splat(f32::NEG_INFINITY);
625        for corner in [Vec2::ZERO, Vec2::X, Vec2::Y, Vec2::ONE] {
626            let local = (corner - pivot) * size;
627            let turned = Vec2::new(local.x * cos - local.y * sin, local.x * sin + local.y * cos);
628            min = min.min(position + turned);
629            max = max.max(position + turned);
630        }
631        let finite = [min.x, min.y, max.x, max.y].iter().all(|v| v.is_finite());
632        if !finite
633            || pixels(min.floor(), max.ceil())
634                .intersection(scissor)
635                .is_none()
636        {
637            return None;
638        }
639        return Some(instance(position, size, pivot, uv, sprite, sprite.rotation));
640    }
641    let near = sprite.position - pivot_offset(pivot, sprite.size);
642    let a = space.corner(near);
643    let b = space.corner(near + sprite.size);
644    pixels(a, b).intersection(scissor)?;
645    Some(instance(a, b - a, Vec2::ZERO, uv, sprite, 0.0))
646}
647
648/// The instance of a glyph's quad in output pixels, or `None` when it has
649/// no pixels inside `scissor`. Its corner snaps as a sprite's, and its size
650/// is its own scaled, rounded to whole pixels for a free scale, so that a
651/// character is as wide wherever it lands.
652fn pack_glyph(
653    sprite: &SpriteDraw,
654    placeholder: bool,
655    space: &UiSpace,
656    scissor: IRect,
657) -> Option<[f32; SPRITE_INSTANCE_FLOATS]> {
658    let (uv, _) = uv_and_pivot(sprite, placeholder);
659    let a = space.corner(sprite.position);
660    let size = if space.whole_units {
661        sprite.size * space.scale
662    } else {
663        snap(sprite.size * space.scale)
664    };
665    pixels(a, a + size).intersection(scissor)?;
666    Some(instance(a, size, Vec2::ZERO, uv, sprite, 0.0))
667}
668
669#[cfg(test)]
670mod tests {
671    use std::num::NonZeroU32;
672
673    use nadir_assets::Handle;
674    use nadir_core::{Color, GenIndex};
675
676    use super::*;
677    use crate::Flip;
678
679    fn handle<T>(index: u32) -> Handle<T> {
680        Handle::new(GenIndex::new(index, NonZeroU32::MIN))
681    }
682
683    /// A sprite of the texture `texture`, its top-left corner at `(x, y)`,
684    /// `w` × `h`.
685    fn rect(texture: u32, x: f32, y: f32, w: f32, h: f32) -> SpriteDraw {
686        let mut sprite = SpriteDraw::new(handle(texture), Vec2::new(x, y), Vec2::new(w, h));
687        sprite.pivot = Vec2::ZERO;
688        sprite
689    }
690
691    fn irect(x0: i32, y0: i32, x1: i32, y1: i32) -> IRect {
692        IRect::new(IVec2::new(x0, y0), IVec2::new(x1, y1))
693    }
694
695    /// 64 × 36 into 151 × 91: a factor of 2, the image at (11, 9) to
696    /// (139, 81), with bars of 11 and 12, and 9 and 10.
697    const VIRTUAL: UVec2 = UVec2::new(64, 36);
698    const OUTPUT: UVec2 = UVec2::new(151, 91);
699
700    fn space(scale: UiScale) -> UiSpace {
701        UiSpace::new(scale, VIRTUAL, OUTPUT)
702    }
703
704    #[test]
705    fn pixel_ui_is_the_upscaled_image_and_a_free_scale_all_of_the_output() {
706        let pixel = space(UiScale::Pixel(1));
707        assert_eq!(
708            (pixel.scale, pixel.origin, pixel.size, pixel.rect),
709            (
710                2.0,
711                IVec2::new(11, 9),
712                Vec2::new(64.0, 36.0),
713                irect(11, 9, 139, 81)
714            )
715        );
716        // Two virtual pixels a unit: half as many units, as large.
717        let double = space(UiScale::Pixel(2));
718        assert_eq!((double.scale, double.size), (4.0, Vec2::new(32.0, 18.0)));
719        assert_eq!((double.origin, double.rect), (pixel.origin, pixel.rect));
720        assert_eq!(space(UiScale::Pixel(0)), pixel, "0 is 1");
721        assert_eq!(space(UiScale::default()), pixel);
722
723        let free = space(UiScale::Free(1.5));
724        assert_eq!(
725            (free.scale, free.origin, free.rect),
726            (1.5, IVec2::ZERO, irect(0, 0, 151, 91))
727        );
728        assert_eq!(free.size, Vec2::new(151.0 / 1.5, 91.0 / 1.5));
729
730        // An output smaller than the image crops it: the pixel UI's origin
731        // is off the output, and it draws on all of the output.
732        let cropped = UiSpace::new(UiScale::Pixel(1), VIRTUAL, UVec2::new(50, 30));
733        assert_eq!(
734            (cropped.scale, cropped.origin, cropped.rect),
735            (1.0, IVec2::new(-7, -3), irect(0, 0, 50, 30))
736        );
737        // No output, no pixels.
738        for scale in [UiScale::Pixel(1), UiScale::Free(1.0)] {
739            assert!(UiSpace::new(scale, VIRTUAL, UVec2::ZERO).rect.is_empty());
740        }
741    }
742
743    #[test]
744    fn a_free_scale_is_held_between_an_eighth_and_64() {
745        let scales = [0.0, -2.0, 0.1, 1.0, 64.5, f32::INFINITY, f32::NAN];
746        let held = scales.map(|scale| space(UiScale::Free(scale)).scale);
747        assert_eq!(held, [0.125, 0.125, 0.125, 1.0, 64.0, 64.0, 1.0]);
748    }
749
750    #[test]
751    fn the_pointer_maps_to_ui_units_and_back() {
752        let pixel = space(UiScale::Pixel(1));
753        assert_eq!(pixel.to_ui(Vec2::new(11.0, 9.0)), Vec2::ZERO);
754        assert_eq!(pixel.to_ui(Vec2::new(12.5, 10.0)), Vec2::new(0.75, 0.5));
755        assert_eq!(pixel.to_ui(Vec2::new(0.0, 0.0)), Vec2::new(-5.5, -4.5));
756        assert_eq!(
757            pixel.to_screen(Vec2::new(63.5, 36.0)),
758            Vec2::new(138.0, 81.0)
759        );
760        let free = space(UiScale::Free(2.0));
761        assert_eq!(free.to_ui(Vec2::new(11.0, 9.0)), Vec2::new(5.5, 4.5));
762        assert_eq!(free.to_screen(Vec2::new(5.5, 4.5)), Vec2::new(11.0, 9.0));
763    }
764
765    #[test]
766    fn a_clip_inside_a_clip_is_cut_by_both_and_one_outside_cuts_everything() {
767        let window = Rect::new(Vec2::new(0.0, 0.0), Vec2::new(20.0, 20.0));
768        let list = Rect::new(Vec2::new(10.0, 5.0), Vec2::new(40.0, 15.0));
769        let view = UiView::default().clipped(window).clipped(list);
770        assert_eq!(
771            view.clip(),
772            Some(Rect::new(Vec2::new(10.0, 5.0), Vec2::new(20.0, 15.0)))
773        );
774        assert_eq!(UiView::default().clip(), None);
775
776        // Scrolled out of its window: nothing, never no clip.
777        let away = Rect::new(Vec2::new(30.0, 0.0), Vec2::new(40.0, 10.0));
778        let gone = UiView::default().clipped(window).clipped(away);
779        let empty = gone.clip().expect("a clip");
780        assert!(empty.is_empty());
781        let nan = UiView::default().clipped(Rect::new(Vec2::new(f32::NAN, 0.0), Vec2::ONE));
782        assert!(nan.clip().expect("a clip").is_empty());
783        let flat = UiView::default().clipped(Rect::new(Vec2::ONE, Vec2::new(5.0, 1.0)));
784        assert!(flat.clip().expect("a clip").is_empty());
785        // Inside out: not the rect between its corners.
786        let inverted = UiView::default().clipped(Rect::new(Vec2::splat(5.0), Vec2::splat(2.0)));
787        assert!(inverted.clip().expect("a clip").is_empty());
788        let pixel = space(UiScale::Pixel(1));
789        for view in [gone, nan, flat, inverted] {
790            assert_eq!(pixel.scissor(view.clip()), None);
791        }
792        assert_eq!(view.scale(), UiScale::Pixel(1));
793    }
794
795    #[test]
796    fn a_clip_s_edges_snap_as_corners_do_and_stay_in_the_space() {
797        let clip = Some(Rect::new(Vec2::new(0.4, 0.6), Vec2::new(10.5, 10.5)));
798        // Pixel UI: to whole units, halves up, then 2 pixels a unit.
799        assert_eq!(
800            space(UiScale::Pixel(1)).scissor(clip),
801            Some(irect(11, 11, 33, 31))
802        );
803        // A free scale: to whole pixels. 0.4 × 1.5 is 0.6, which is 1.
804        assert_eq!(
805            space(UiScale::Free(1.5)).scissor(clip),
806            Some(irect(1, 1, 16, 16))
807        );
808        // Unclipped, or infinite: the space's own pixels.
809        let pixel = space(UiScale::Pixel(1));
810        assert_eq!(pixel.scissor(None), Some(pixel.rect));
811        let all = Rect::new(Vec2::splat(f32::NEG_INFINITY), Vec2::splat(f32::INFINITY));
812        assert_eq!(pixel.scissor(Some(all)), Some(pixel.rect));
813        // Off the image: nowhere.
814        let off = Rect::new(Vec2::new(-10.0, 0.0), Vec2::new(-1.0, 5.0));
815        assert_eq!(pixel.scissor(Some(off)), None);
816        assert_eq!(
817            space(UiScale::Free(1.0)).scissor(Some(off)),
818            None,
819            "left of the output"
820        );
821    }
822
823    #[test]
824    fn a_list_keeps_its_order_across_sprites_and_texts_each_with_its_view() {
825        let font = handle(9);
826        let mut list = UiList::new();
827        assert!(list.is_empty());
828        assert_eq!(list.view(), UiView::default());
829        list.sprite(rect(1, 0.0, 0.0, 4.0, 4.0));
830        list.text(TextDraw::new(font, Vec2::ZERO), "a");
831        let free = UiView::new(UiScale::Free(2.0));
832        list.set_view(free);
833        assert_eq!(list.view(), free);
834        list.write(TextDraw::new(font, Vec2::ZERO), format_args!("b{}", 2));
835        list.sprite(rect(2, 0.0, 0.0, 4.0, 4.0));
836        let all: Vec<(String, UiView)> = list
837            .iter()
838            .map(|(draw, view)| {
839                let what = match draw {
840                    UiDraw::Sprite(sprite) => format!("sprite {}", sprite.texture.id().index()),
841                    UiDraw::Text(_, text) => format!("text {text}"),
842                };
843                (what, view)
844            })
845            .collect();
846        let pixel = UiView::default();
847        assert_eq!(
848            all,
849            [
850                ("sprite 1".to_string(), pixel),
851                ("text a".to_string(), pixel),
852                ("text b2".to_string(), free),
853                ("sprite 2".to_string(), free),
854            ]
855        );
856        assert_eq!(list.len(), 4);
857    }
858
859    #[test]
860    fn a_view_set_twice_before_anything_is_pushed_is_one_view() {
861        let mut list = UiList::new();
862        list.set_view(UiView::new(UiScale::Free(3.0)));
863        list.set_view(UiView::new(UiScale::Free(2.0)));
864        list.sprite(rect(1, 0.0, 0.0, 1.0, 1.0));
865        list.set_view(UiView::new(UiScale::Free(2.0)));
866        list.sprite(rect(1, 0.0, 0.0, 1.0, 1.0));
867        assert_eq!(list.views, [UiView::new(UiScale::Free(2.0))]);
868        list.set_view(UiView::default());
869        list.set_view(UiView::new(UiScale::Free(2.0)));
870        list.sprite(rect(1, 0.0, 0.0, 1.0, 1.0));
871        assert_eq!(list.views.len(), 1, "set back before anything used it");
872    }
873
874    #[test]
875    fn a_view_s_scale_is_the_one_drawn_so_views_of_one_scale_are_equal() {
876        assert_eq!(UiView::new(UiScale::Pixel(0)).scale(), UiScale::Pixel(1));
877        assert_eq!(
878            UiView::new(UiScale::Free(f32::NAN)).scale(),
879            UiScale::Free(1.0)
880        );
881        assert_eq!(
882            UiView::new(UiScale::Free(100.0)).scale(),
883            UiScale::Free(64.0)
884        );
885        let mut list = UiList::new();
886        for _ in 0..3 {
887            list.set_view(UiView::new(UiScale::Free(f32::NAN)));
888            list.sprite(rect(1, 0.0, 0.0, 1.0, 1.0));
889        }
890        assert_eq!(list.views.len(), 1);
891        assert_eq!(build(&list, &[]).batches.len(), 1);
892    }
893
894    #[test]
895    fn a_text_whose_formatting_fails_is_left_out_of_the_ui() {
896        struct Fails;
897        impl fmt::Display for Fails {
898            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
899                f.write_str("half")?;
900                Err(fmt::Error)
901            }
902        }
903        let mut list = UiList::new();
904        list.write(
905            TextDraw::new(handle(1), Vec2::ZERO),
906            format_args!("{Fails}"),
907        );
908        list.text(TextDraw::new(handle(1), Vec2::ZERO), "kept");
909        assert_eq!(list.len(), 1);
910        assert_eq!(list.text_items, [0]);
911        assert!(matches!(
912            list.iter().next(),
913            Some((UiDraw::Text(_, "kept"), _))
914        ));
915    }
916
917    #[test]
918    fn a_cleared_list_keeps_its_buffers_and_goes_back_to_the_default_view() {
919        let mut list = UiList::new();
920        let fill = |list: &mut UiList| {
921            list.set_view(UiView::new(UiScale::Free(2.0)));
922            for i in 0..20 {
923                list.sprite(rect(1, i as f32, 0.0, 1.0, 1.0));
924                list.write(
925                    TextDraw::new(handle(1), Vec2::ZERO),
926                    format_args!("row {i}"),
927                );
928            }
929        };
930        fill(&mut list);
931        let capacity = (
932            list.items.capacity(),
933            list.sprites.capacity(),
934            list.text_items.capacity(),
935        );
936        list.clear();
937        assert!(list.is_empty());
938        assert_eq!(list.view(), UiView::default());
939        fill(&mut list);
940        assert_eq!(
941            (
942                list.items.capacity(),
943                list.sprites.capacity(),
944                list.text_items.capacity()
945            ),
946            capacity
947        );
948    }
949
950    /// A glyph quad of the `text`th text, on the page `page`, at `(x, y)`.
951    fn glyph(text: u32, page: u32, x: f32, y: f32) -> GlyphQuad<(u32, Pipe)> {
952        GlyphQuad {
953            sprite: rect(page, x, y, 3.0, 5.0),
954            text,
955            texture: (page, Pipe::Text),
956            placeholder: false,
957        }
958    }
959
960    /// Builds `list` and `glyphs` into 151 × 91, each sprite's texture its
961    /// handle's index, ready.
962    fn build(list: &UiList, glyphs: &[GlyphQuad<(u32, Pipe)>]) -> UiPass<u32> {
963        let mut pass = UiPass::new();
964        pass.build(list, glyphs, VIRTUAL, OUTPUT, |sprite| {
965            Some((sprite.texture.id().index(), false))
966        });
967        pass
968    }
969
970    /// The instances' (position, size), in draw order.
971    fn quads(pass: &UiPass<u32>) -> Vec<(Vec2, Vec2)> {
972        pass.packed
973            .chunks(SPRITE_INSTANCE_FLOATS)
974            .map(|f| (Vec2::new(f[0], f[1]), Vec2::new(f[2], f[3])))
975            .collect()
976    }
977
978    fn batches(pass: &UiPass<u32>) -> Vec<(u32, Pipe, u32, u32, u32)> {
979        pass.batches
980            .iter()
981            .map(|b| (b.texture.0, b.texture.1, b.view, b.start, b.count))
982            .collect()
983    }
984
985    #[test]
986    fn windows_draw_in_the_order_pushed_sprites_and_texts_alike() {
987        // Two windows that overlap, each a panel and its label, and a caret
988        // after the second label: nothing of the first window shows
989        // through the second.
990        let font = handle(9);
991        let mut list = UiList::new();
992        list.sprite(rect(2, 0.0, 0.0, 20.0, 10.0));
993        list.text(TextDraw::new(font, Vec2::new(1.0, 1.0)), "a");
994        list.sprite(rect(2, 5.0, 5.0, 20.0, 10.0));
995        list.text(TextDraw::new(font, Vec2::new(6.0, 6.0)), "b");
996        list.sprite(rect(3, 9.0, 6.0, 1.0, 5.0));
997        let glyphs = [glyph(0, 5, 1.0, 1.0), glyph(1, 5, 6.0, 6.0)];
998        let pass = build(&list, &glyphs);
999        assert_eq!(
1000            batches(&pass),
1001            [
1002                (2, Pipe::Sprite, 0, 0, 1),
1003                (5, Pipe::Text, 0, 1, 1),
1004                (2, Pipe::Sprite, 0, 2, 1),
1005                (5, Pipe::Text, 0, 3, 1),
1006                (3, Pipe::Sprite, 0, 4, 1),
1007            ]
1008        );
1009        assert_eq!((pass.sprites, pass.glyphs, pass.skipped), (3, 2, 0));
1010    }
1011
1012    #[test]
1013    fn layers_and_fixed_depths_order_before_the_push_and_ysort_is_depth_0() {
1014        let mut list = UiList::new();
1015        let mut top = rect(1, 0.0, 0.0, 1.0, 1.0);
1016        top.layer = 1;
1017        list.sprite(top);
1018        let mut raised = rect(2, 0.0, 0.0, 1.0, 1.0);
1019        raised.sort = SortMode::Fixed(5);
1020        list.sprite(raised);
1021        // Y-sorted, by their feet at 30 and then 10: in the order pushed.
1022        let mut low = SpriteDraw::new(handle(3), Vec2::new(0.0, 30.0), Vec2::ONE);
1023        list.sprite(low);
1024        low.position.y = 10.0;
1025        low.texture = handle(4);
1026        list.sprite(low);
1027        let order: Vec<u32> = build(&list, &[])
1028            .batches
1029            .iter()
1030            .map(|b| b.texture.0)
1031            .collect();
1032        assert_eq!(order, [3, 4, 2, 1]);
1033
1034        // A text's layer and depth are its draw's: pushed first, in front.
1035        let mut list = UiList::new();
1036        let mut label = TextDraw::new(handle(9), Vec2::ZERO);
1037        label.layer = 1;
1038        list.text(label, "a");
1039        let mut raised = TextDraw::new(handle(9), Vec2::ZERO);
1040        raised.sort = SortMode::Fixed(1);
1041        list.text(raised, "b");
1042        list.sprite(rect(2, 0.0, 0.0, 4.0, 4.0));
1043        let glyphs = [glyph(0, 5, 0.0, 0.0), glyph(1, 6, 0.0, 0.0)];
1044        let order: Vec<u32> = build(&list, &glyphs)
1045            .batches
1046            .iter()
1047            .map(|b| b.texture.0)
1048            .collect();
1049        assert_eq!(order, [2, 6, 5]);
1050    }
1051
1052    #[test]
1053    fn a_text_s_glyphs_keep_its_place_grouped_by_page() {
1054        let font = handle(9);
1055        let mut list = UiList::new();
1056        list.text(TextDraw::new(font, Vec2::ZERO), "ab");
1057        list.sprite(rect(2, 0.0, 0.0, 4.0, 4.0));
1058        let mut raised = TextDraw::new(font, Vec2::ZERO);
1059        raised.layer = 1;
1060        list.text(raised, "c");
1061        // The first text's glyphs on pages 6, 5, 6: by page, in their order.
1062        let glyphs = [
1063            glyph(0, 6, 0.0, 0.0),
1064            glyph(0, 5, 4.0, 0.0),
1065            glyph(0, 6, 8.0, 0.0),
1066            glyph(1, 5, 0.0, 9.0),
1067        ];
1068        let pass = build(&list, &glyphs);
1069        assert_eq!(
1070            batches(&pass),
1071            [
1072                (5, Pipe::Text, 0, 0, 1),
1073                (6, Pipe::Text, 0, 1, 2),
1074                (2, Pipe::Sprite, 0, 3, 1),
1075                (5, Pipe::Text, 0, 4, 1),
1076            ]
1077        );
1078        let xs: Vec<f32> = quads(&pass)[1..3].iter().map(|(p, _)| p.x).collect();
1079        // At factor 2 from x 11: 0 and 8 units.
1080        assert_eq!(xs, [11.0, 27.0]);
1081
1082        // Pages whose handles share their low 16 bits are two pages.
1083        let mut list = UiList::new();
1084        list.text(TextDraw::new(font, Vec2::ZERO), "abc");
1085        let far = 3 + (1 << 16);
1086        let glyphs = [
1087            glyph(0, 3, 0.0, 0.0),
1088            glyph(0, far, 4.0, 0.0),
1089            glyph(0, 3, 8.0, 0.0),
1090        ];
1091        assert_eq!(
1092            batches(&build(&list, &glyphs)),
1093            [(3, Pipe::Text, 0, 0, 2), (far, Pipe::Text, 0, 2, 1)]
1094        );
1095    }
1096
1097    #[test]
1098    fn a_batch_is_one_texture_one_program_and_one_view() {
1099        let mut list = UiList::new();
1100        list.sprite(rect(1, 0.0, 0.0, 1.0, 1.0));
1101        list.sprite(rect(1, 2.0, 0.0, 1.0, 1.0));
1102        list.set_view(UiView::default().clipped(Rect::new(Vec2::ZERO, Vec2::splat(50.0))));
1103        list.sprite(rect(1, 4.0, 0.0, 1.0, 1.0));
1104        let pass = build(&list, &[]);
1105        assert_eq!(
1106            batches(&pass),
1107            [(1, Pipe::Sprite, 0, 0, 2), (1, Pipe::Sprite, 1, 2, 1)]
1108        );
1109        assert_eq!(pass.scissor(0), Some(irect(11, 9, 139, 81)));
1110        assert_eq!(pass.scissor(1), Some(irect(11, 9, 111, 81)));
1111    }
1112
1113    #[test]
1114    fn what_is_outside_its_clip_or_has_no_pixels_is_not_drawn_nor_counted() {
1115        let font = handle(9);
1116        let mut list = UiList::new();
1117        list.set_view(UiView::default().clipped(Rect::new(Vec2::ZERO, Vec2::splat(10.0))));
1118        list.sprite(rect(1, 2.0, 2.0, 4.0, 4.0));
1119        list.sprite(rect(1, 12.0, 2.0, 4.0, 4.0));
1120        list.sprite(rect(1, 2.0, 2.0, 0.0, 4.0));
1121        // Half a unit: to whole units, nothing.
1122        list.sprite(rect(1, 3.6, 2.0, 0.3, 4.0));
1123        list.text(TextDraw::new(font, Vec2::ZERO), "ab");
1124        // Rotated: outside by the box around its corners, of no size, or
1125        // turned by NaN.
1126        let mut turned = rect(1, 30.0, 2.0, 4.0, 4.0);
1127        turned.rotation = 0.5;
1128        list.sprite(turned);
1129        turned.position = Vec2::new(4.0, 4.0);
1130        turned.size = Vec2::ZERO;
1131        list.sprite(turned);
1132        turned.size = Vec2::splat(4.0);
1133        turned.rotation = f32::NAN;
1134        list.sprite(turned);
1135        // Inside, turned: drawn.
1136        turned.rotation = 0.5;
1137        list.sprite(turned);
1138        // A view that cuts everything draws nothing of its own; what is not
1139        // ready there is skipped still, as its glyphs would be.
1140        list.set_view(UiView::default().clipped(Rect::new(Vec2::splat(50.0), Vec2::splat(40.0))));
1141        list.sprite(rect(1, 2.0, 2.0, 4.0, 4.0));
1142        list.sprite(rect(7, 2.0, 2.0, 4.0, 4.0));
1143        list.text(TextDraw::new(font, Vec2::ZERO), "c");
1144        let glyphs = [
1145            glyph(0, 5, 1.0, 1.0),
1146            glyph(0, 5, 11.0, 1.0),
1147            glyph(1, 5, 1.0, 1.0),
1148        ];
1149        let mut pass = UiPass::new();
1150        pass.build(&list, &glyphs, VIRTUAL, OUTPUT, |sprite| {
1151            match sprite.texture.id().index() {
1152                7 => None,
1153                texture => Some((texture, false)),
1154            }
1155        });
1156        assert_eq!((pass.sprites, pass.glyphs, pass.skipped), (2, 1, 1));
1157        assert_eq!(pass.packed.len(), 3 * SPRITE_INSTANCE_FLOATS);
1158        assert_eq!(pass.packed[2 * SPRITE_INSTANCE_FLOATS + 14], 0.5, "turned");
1159    }
1160
1161    #[test]
1162    fn a_sprite_not_ready_is_skipped_and_a_failed_one_shows_its_placeholder() {
1163        let mut list = UiList::new();
1164        let mut sprite = rect(1, 0.0, 0.0, 4.0, 4.0);
1165        sprite.uv = Rect::new(Vec2::new(0.5, 0.5), Vec2::ONE);
1166        list.sprite(sprite);
1167        sprite.texture = handle(2);
1168        list.sprite(sprite);
1169        let mut pass = UiPass::new();
1170        pass.build(&list, &[], VIRTUAL, OUTPUT, |sprite| {
1171            match sprite.texture.id().index() {
1172                1 => None,
1173                texture => Some((texture, true)),
1174            }
1175        });
1176        assert_eq!((pass.sprites, pass.skipped), (1, 1));
1177        assert_eq!(pass.packed[6..10], [0.0, 0.0, 1.0, 1.0]);
1178        assert_eq!(pass.batches[0].texture, (2, Pipe::Sprite));
1179    }
1180
1181    /// Packs `sprite` in `space`, unclipped.
1182    fn pack(sprite: &SpriteDraw, space: &UiSpace) -> [f32; SPRITE_INSTANCE_FLOATS] {
1183        pack_sprite(sprite, false, space, space.rect).expect("drawn")
1184    }
1185
1186    #[test]
1187    fn at_a_free_scale_sprites_that_share_an_edge_share_it_in_pixels() {
1188        // At 1.5, a title bar 3 high and the body below it: the bar's
1189        // bottom is 4.5 pixels down, and the body's top too, both 5.
1190        let free = space(UiScale::Free(1.5));
1191        let bar = pack(&rect(1, 0.0, 0.0, 3.0, 3.0), &free);
1192        let body = pack(&rect(1, 0.0, 3.0, 3.0, 3.0), &free);
1193        assert_eq!(bar[0..4], [0.0, 0.0, 5.0, 5.0]);
1194        assert_eq!(body[0..4], [0.0, 5.0, 5.0, 4.0]);
1195        // Placed by its corner: the pivot is 0, unrotated.
1196        assert_eq!(bar[4..6], [0.0, 0.0]);
1197        assert_eq!(bar[14], 0.0);
1198    }
1199
1200    #[test]
1201    fn a_ui_sprite_snaps_by_its_pivot_rounded_and_mirrors_about_it() {
1202        // 13 wide, its pivot 7 pixels in at x 7.5: its corner at 0.5 goes
1203        // up to 1, which an unrounded 7/13 × 13 would take down to 0.
1204        let pixel = space(UiScale::Pixel(1));
1205        let mut sprite = rect(1, 7.5, 0.0, 13.0, 2.0);
1206        sprite.pivot = Vec2::new(7.0 / 13.0, 0.0);
1207        let floats = pack(&sprite, &pixel);
1208        assert_eq!(floats[0..4], [11.0 + 2.0, 9.0, 26.0, 4.0]);
1209        // Mirrored: the pivot is 6 in from the left, the corner at 1.5,
1210        // which goes up to 2; the uv swapped.
1211        sprite.flip = Flip { x: true, y: false };
1212        sprite.uv = Rect::new(Vec2::new(0.25, 0.0), Vec2::new(0.75, 1.0));
1213        let floats = pack(&sprite, &pixel);
1214        assert_eq!(floats[0..4], [11.0 + 4.0, 9.0, 26.0, 4.0]);
1215        assert_eq!(floats[6..10], [0.75, 0.0, 0.25, 1.0]);
1216        // Two virtual pixels a unit: 2 units of 4 pixels, from 11.
1217        let mut small = rect(1, 2.25, 1.0, 1.0, 1.0);
1218        small.color = Color::rgb(255, 0, 0);
1219        let floats = pack(&small, &space(UiScale::Pixel(2)));
1220        assert_eq!(floats[0..4], [19.0, 13.0, 4.0, 4.0]);
1221        assert_eq!(floats[10..14], [1.0, 0.0, 0.0, 1.0]);
1222    }
1223
1224    #[test]
1225    fn a_rotated_ui_sprite_is_scaled_about_its_pivot_and_not_moved() {
1226        let mut sprite = rect(1, 2.25, 1.0, 4.0, 2.0);
1227        sprite.pivot = Vec2::new(0.5, 0.5);
1228        sprite.rotation = 0.5;
1229        let floats = pack(&sprite, &space(UiScale::Pixel(1)));
1230        assert_eq!(floats[0..6], [15.5, 11.0, 8.0, 4.0, 0.5, 0.5]);
1231        assert_eq!(floats[14], 0.5);
1232    }
1233
1234    #[test]
1235    fn a_glyph_is_as_wide_wherever_it_lands() {
1236        // 3 × 5 at 1.5 is 4.5 × 7.5, which is 5 × 8 at x 0 and at x 1; a
1237        // sprite there would be 5, then 4.
1238        let free = space(UiScale::Free(1.5));
1239        let widths: Vec<[f32; 4]> = [0.0, 1.0]
1240            .map(|x| {
1241                let floats =
1242                    pack_glyph(&rect(1, x, 0.0, 3.0, 5.0), false, &free, free.rect).expect("drawn");
1243                [floats[0], floats[1], floats[2], floats[3]]
1244            })
1245            .to_vec();
1246        assert_eq!(widths, [[0.0, 0.0, 5.0, 8.0], [2.0, 0.0, 5.0, 8.0]]);
1247        let sprite = pack(&rect(1, 1.0, 0.0, 3.0, 5.0), &free);
1248        assert_eq!(sprite[2], 4.0);
1249        // Pixel UI: whole units, so whole pixels.
1250        let pixel = space(UiScale::Pixel(1));
1251        let mut glyph = rect(1, 1.0, 2.0, 3.0, 5.0);
1252        glyph.uv = Rect::new(Vec2::new(0.25, 0.5), Vec2::new(0.5, 1.0));
1253        let floats = pack_glyph(&glyph, false, &pixel, pixel.rect).expect("drawn");
1254        assert_eq!(floats[0..4], [13.0, 13.0, 6.0, 10.0]);
1255        assert_eq!(floats[6..10], [0.25, 0.5, 0.5, 1.0]);
1256        // On a page that failed: all of its placeholder.
1257        let floats = pack_glyph(&glyph, true, &pixel, pixel.rect).expect("drawn");
1258        assert_eq!(floats[6..10], [0.0, 0.0, 1.0, 1.0]);
1259    }
1260}