Skip to main content

crcbl_render/
nine_slice.rs

1//! Nine-slice: one frame drawn at any size with its corners left alone.
2//!
3//! ```text
4//!   source frame (texels)              target (world units)
5//!   ┌──┬────────┬──┐                   ┌──┬──────────────────┬──┐
6//!   │TL│  top   │TR│   left/right      │TL│       top        │TR│
7//!   ├──┼────────┼──┤   stretch on Y    ├──┼──────────────────┼──┤
8//!   │L │ centre │R │   top/bottom      │L │                  │R │
9//!   ├──┼────────┼──┤   stretch on X    │  │      centre      │  │
10//!   │BL│ bottom │BR│   centre on both  ├──┼──────────────────┼──┤
11//!   └──┴────────┴──┘                   │BL│      bottom      │BR│
12//!                                      └──┴──────────────────┴──┘
13//! ```
14//!
15//! # Why this is in `crcbl-render` and not in `crcbl-sprite`
16//!
17//! [`crcbl_sprite`] owns [`NineSlice`] and validates it, and the arithmetic here
18//! is pure maths over rectangles with no device in it — so the crate that owns
19//! the insets is the obvious first guess. It is the wrong one, for a reason that
20//! crate states in its own first paragraph: *"Pixels are the unit … every
21//! rectangle here is in texels of the sheet image, as unsigned integers"*, and
22//! *"turning a description into pixels belongs to `crcbl-render`"*.
23//!
24//! A target rectangle is neither: it is **world units, as floats**, and it comes
25//! from a game's simulation rather than from anything a sheet knows. Putting it
26//! in `crcbl-sprite` would put a second unit system into a crate whose whole
27//! discipline is having one, and would give a `build.rs` that only wants to
28//! convert art a type it has no use for. `crcbl-render` already depends on
29//! `crcbl-sprite`, so this side can read [`NineSlice`], [`Rect`] and the sheet's
30//! size; the reverse dependency does not exist and must not.
31//!
32//! Nothing is lost by the move. This module has no device, no GPU type and no
33//! I/O — every test below runs with no backend at all, which is the property
34//! that made `crcbl-sprite` attractive in the first place.
35//!
36//! `docs/specs/crcbl/pix.md` §9 already draws the line the same way: *"how
37//! nine-slice insets become geometry"* is listed under **Not specified here**,
38//! alongside rendering.
39//!
40//! # Stretch, never tile
41//!
42//! The edges and the centre are **stretched**, and there is deliberately no
43//! tiling mode. Two reasons, both concrete:
44//!
45//! * A tiled band is `ceil(extent / inset)` quads rather than one, so the
46//!   instance count stops being bounded by nine and starts depending on how big
47//!   the thing was drawn — a pipe stretched to a tall gap would quietly become
48//!   hundreds of instances.
49//! * Doing it with UVs instead, by letting `u1` run past 1, needs a repeating
50//!   sampler; [`SpriteRenderer`](crate::SpriteRenderer) has exactly **one**
51//!   sampler, `ClampToEdge`, shared by every sheet, and a second address mode
52//!   would be a second bind group layout for a feature nothing has asked for.
53//!
54//! If tiling is ever wanted it is a new mode with its own quad emitter, not a
55//! flag on this one.
56
57use core::ops::Deref;
58
59use crcbl_sprite::{NineSlice, Rect, Sheet};
60use crcbl_ui::image::{slice_bands, slice_cuts};
61
62use crate::sprite_pass::{SheetId, Sprite};
63
64/// One quad of an expanded nine-slice: where to draw, and what to sample.
65///
66/// The same two rectangles a [`Sprite`] carries, and in the same layouts, so
67/// [`NineQuads::sprites`] is a field copy rather than a conversion.
68#[derive(Clone, Copy, Debug, Default, PartialEq)]
69pub struct SliceQuad {
70    /// World-space rectangle: `[x, y, w, h]`, minimum corner first, Y **up** —
71    /// [`Sprite::rect`]'s layout.
72    pub rect: [f32; 4],
73    /// Normalised sheet UVs: `[u0, v0, u1, v1]`, top-left corner first, in image
74    /// order — [`Sprite::uv`]'s layout.
75    pub uv: [f32; 4],
76}
77
78/// The quads an expansion produced: at most nine, and never a heap allocation.
79///
80/// **Fewer than nine is the normal case, not an edge case.** A three-slice
81/// (`top == bottom == 0`, the shape of a horizontal bar) emits three, and a
82/// frame with no insets at all emits one. Emitting nine unconditionally would
83/// cost a full instance for each empty band, and hand the shader a UV rectangle
84/// of zero extent — see [`NineSliceSource::expand`].
85#[derive(Clone, Copy, Debug, Default, PartialEq)]
86pub struct NineQuads {
87    quads: [SliceQuad; 9],
88    len: usize,
89}
90
91impl NineQuads {
92    /// The quads, in image order: top row left to right, then middle, then
93    /// bottom.
94    #[must_use]
95    pub fn as_slice(&self) -> &[SliceQuad] {
96        &self.quads[..self.len]
97    }
98
99    /// One [`Sprite`] per quad, all naming `sheet` and carrying `tint`.
100    ///
101    /// An iterator rather than a `Vec`: the caller already has somewhere to put
102    /// them — a frame's sprite list, or one layer of a
103    /// [`LayerStack`](crate::layers::LayerStack) — and a nine-slice that
104    /// allocated once per pipe per frame would be a strange thing to have built
105    /// on top of a renderer that reuses its instance ring.
106    pub fn sprites(
107        &self,
108        sheet: SheetId,
109        tint: [f32; 4],
110    ) -> impl Iterator<Item = Sprite> + Clone + '_ {
111        // **Unrotated, and there is no overload that is not.** The nine quads
112        // of a slice are stretched against each other on two axes; turning them
113        // individually about their own centres would open a gap at every band
114        // boundary, and turning the frame as a whole needs one pivot shared by
115        // all nine, which is a different feature from `Sprite::rotation`. A
116        // rotated panel is not in this slice — see `docs/backlog.md`.
117        self.as_slice()
118            .iter()
119            .map(move |quad| Sprite::new(sheet, quad.rect, quad.uv).with_tint(tint))
120    }
121
122    /// Appends one quad, ignoring an empty one.
123    fn push(&mut self, quad: SliceQuad) {
124        // `len` cannot reach 9 before the loop that fills it ends, so this is a
125        // guard against a future caller rather than a live branch.
126        if self.len < self.quads.len() {
127            self.quads[self.len] = quad;
128            self.len += 1;
129        }
130    }
131}
132
133impl Deref for NineQuads {
134    type Target = [SliceQuad];
135
136    fn deref(&self) -> &[SliceQuad] {
137        self.as_slice()
138    }
139}
140
141/// The art a nine-slice is expanded from: the insets, the frame they inset, and
142/// the sheet the frame sits in.
143///
144/// The sheet's size is here because it is the UV divisor — the one number a
145/// [`Rect`] on its own does not know, for exactly the reason
146/// [`Sheet::uv`] lives on the sheet rather than on the rect.
147///
148/// No `Eq`: [`texels_per_unit`](Self::texels_per_unit) is an `f32`, and `f32`
149/// is not `Eq`.
150#[derive(Clone, Copy, Debug, PartialEq)]
151pub struct NineSliceSource {
152    /// The insets that stay fixed, in texels.
153    pub nine: NineSlice,
154    /// Where the frame sits in the sheet image, in texels.
155    pub frame: Rect,
156    /// The sheet image's width in texels.
157    pub sheet_width: u32,
158    /// The sheet image's height in texels.
159    pub sheet_height: u32,
160    /// How many texels of art one caller unit is.
161    ///
162    /// The fixed bands [`expand`](Self::expand) emits and
163    /// [`minimum_size`](Self::minimum_size) come back divided by this, so a
164    /// source whose caller's world is not one unit per texel does not have to
165    /// scale its camera to compensate. [`from_sheet`](Self::from_sheet) defaults
166    /// it to 1 — one caller unit per texel, which is the behaviour this type
167    /// always had — and [`with_texels_per_unit`](Self::with_texels_per_unit) is
168    /// the way a caller changes it.
169    pub texels_per_unit: f32,
170}
171
172impl NineSliceSource {
173    /// The source for frame `index` of `sheet`.
174    ///
175    /// `None` when the sheet declares no nine-slice, when it has no frame at
176    /// that index, or when it has no size at all — the last because the UV
177    /// divisor would be zero and every quad would carry a `NaN` into a vertex
178    /// buffer, which draws nothing and gets blamed on the shader.
179    /// [`Sheet::uv`] refuses the same case for the same reason.
180    #[must_use]
181    pub fn from_sheet(sheet: &Sheet, index: usize) -> Option<Self> {
182        if sheet.width == 0 || sheet.height == 0 {
183            return None;
184        }
185        Some(Self {
186            nine: sheet.nine?,
187            frame: sheet.frames.get(index)?.rect,
188            sheet_width: sheet.width,
189            sheet_height: sheet.height,
190            // One caller unit per texel: the behaviour this type always had.
191            // A caller whose world is not one unit per texel changes it with
192            // [`with_texels_per_unit`](Self::with_texels_per_unit).
193            texels_per_unit: 1.0,
194        })
195    }
196
197    /// The source, with its texels-per-unit scale set.
198    ///
199    /// The fixed bands [`expand`](Self::expand) emits and
200    /// [`minimum_size`](Self::minimum_size) come back divided by
201    /// `texels_per_unit`. Any value is accepted: [`expand`](Self::expand) draws
202    /// nothing when the scale is not a positive finite number, the same way it
203    /// draws nothing for a nonsense target.
204    #[must_use]
205    pub fn with_texels_per_unit(mut self, texels_per_unit: f32) -> Self {
206        self.texels_per_unit = texels_per_unit;
207        self
208    }
209
210    /// The insets this source actually expands with, in texels.
211    ///
212    /// [`NineSliceSource::nine`] as given, trimmed so it cannot exceed the frame
213    /// — the same trimming [`NineSliceSource::expand`] applies, exposed because a
214    /// caller laying out *around* the fixed bands (a button sizing itself to its
215    /// corners) has to agree with the geometry rather than with the request.
216    #[must_use]
217    pub fn insets(&self) -> NineSlice {
218        self.clamped()
219    }
220
221    /// The smallest target this source draws at its natural corner size, in
222    /// world units — [`NineSlice::minimum_size`] as floats, divided by
223    /// [`texels_per_unit`](Self::texels_per_unit) so it is in the same caller
224    /// units as the bands [`expand`](Self::expand) emits.
225    #[must_use]
226    pub fn minimum_size(&self) -> (f32, f32) {
227        let (width, height) = self.clamped().minimum_size();
228        (
229            width as f32 / self.texels_per_unit,
230            height as f32 / self.texels_per_unit,
231        )
232    }
233
234    /// The quads that draw this frame stretched to `target`.
235    ///
236    /// `target` is `[x, y, w, h]` in world units, minimum corner first and Y
237    /// **up** — [`Sprite::rect`]'s layout, because that is what the quads become.
238    ///
239    /// # What comes back
240    ///
241    /// Between zero and nine quads, in image order (top row left to right, then
242    /// middle, then bottom). Corners are `left`/`right` wide and `top`/`bottom`
243    /// tall in world units — `inset / texels_per_unit` each, so at the default
244    /// of one caller unit per texel a target the size of the frame reproduces
245    /// the single sprite exactly. Edges stretch on one axis and the centre on
246    /// both.
247    ///
248    /// **Empty bands are not emitted.** A band whose extent is zero in texels or
249    /// zero in world units is skipped, so a three-slice (`top == bottom == 0`)
250    /// comes back as three quads and a frame with no insets as one. A zero-area
251    /// quad is invisible and still costs a whole instance, and a UV rectangle of
252    /// zero extent is a division waiting to happen in anything that later wants
253    /// a texel-per-world-unit ratio.
254    ///
255    /// **The seams cannot bleed.** The four cut lines on each axis are computed
256    /// once, and every quad indexes into them — so two adjacent quads share an
257    /// edge as the *same* `f32`, in world space and in UV space, rather than as
258    /// two numbers that happen to have been rounded the same way. A one-texel
259    /// seam between bands is exactly what independent per-quad arithmetic
260    /// produces.
261    ///
262    /// # A target smaller than the corners
263    ///
264    /// **The fixed bands shrink in proportion and the stretched band vanishes.**
265    /// A target 6 units wide on a slice with `left = 4, right = 8` (at the
266    /// default scale of one caller unit per texel) draws a 2-unit left cap and a
267    /// 4-unit right cap and no centre at all.
268    ///
269    /// The alternatives were both worse. *Refusing* — no quads, or a clamp of
270    /// the target up to the minimum — makes a pipe squeezed below its two caps
271    /// either vanish or spill outside the rectangle it was given; a sprite that
272    /// disappears at one size and not another is the failure
273    /// [`NineSlice::fits_in`] already exists to prevent. *Letting the corners
274    /// overlap* inverts the middle band, which with no backface culling
275    /// rasterises a mirrored quad rather than nothing, and double-blends the
276    /// overlap.
277    ///
278    /// Shrinking keeps three properties that matter more than the corners
279    /// staying literally fixed at a size where they cannot: the quads still tile
280    /// `target` exactly, nothing is drawn outside it, and the picture is
281    /// continuous — at exactly the minimum size this and the ordinary path agree,
282    /// so a pipe closing to nothing does not jump. The corners are squashed,
283    /// which is visible and is the honest thing for a size where "corners at
284    /// their natural size" is arithmetically impossible.
285    ///
286    /// Each axis decides independently: a target narrower than `left + right`
287    /// but taller than `top + bottom` shrinks only horizontally.
288    #[must_use]
289    pub fn expand(&self, target: [f32; 4]) -> NineQuads {
290        let mut out = NineQuads::default();
291        if self.sheet_width == 0
292            || self.sheet_height == 0
293            || !target.iter().all(|v| v.is_finite())
294            || !self.texels_per_unit.is_finite()
295            || self.texels_per_unit <= 0.0
296        {
297            return out;
298        }
299        let nine = self.clamped();
300        let (width, height) = (self.frame.w, self.frame.h);
301
302        // --- the cut lines, computed once ---------------------------------
303        //
304        // Texel cuts run in image order on both axes, so `v` descends the image
305        // and `top` is the first band. World cuts ascend on both axes, so on Y
306        // the *last* band is the one `top` sampled — see the pairing below.
307        let texel_x = [
308            self.frame.x,
309            self.frame.x + nine.left,
310            self.frame.x + width - nine.right,
311            self.frame.x + width,
312        ];
313        let texel_y = [
314            self.frame.y,
315            self.frame.y + nine.top,
316            self.frame.y + height - nine.bottom,
317            self.frame.y + height,
318        ];
319        let us = texel_x.map(|x| x as f32 / self.sheet_width as f32);
320        let vs = texel_y.map(|y| y as f32 / self.sheet_height as f32);
321        // The fixed bands come back in the caller's units: the texel insets
322        // divided by the scale, so a six-texel cap at twenty texels per unit is
323        // a 0.3-unit cap.
324        let xs = slice_cuts(
325            target[0],
326            slice_bands(
327                nine.left as f32 / self.texels_per_unit,
328                nine.right as f32 / self.texels_per_unit,
329                target[2],
330            ),
331            target[2],
332        );
333        // World Y is up and the frame's `top` inset is the top of the *image*,
334        // so the low world band is `bottom` and the high one is `top`.
335        let ys = slice_cuts(
336            target[1],
337            slice_bands(
338                nine.bottom as f32 / self.texels_per_unit,
339                nine.top as f32 / self.texels_per_unit,
340                target[3],
341            ),
342            target[3],
343        );
344
345        // --- one quad per non-empty band pair -----------------------------
346        for row in 0..3 {
347            // Image row 0 is the top of the image, which is the *highest* world
348            // band; row 2 is the bottom, which is the lowest.
349            let world_row = 2 - row;
350            let (y, h) = (ys[world_row], ys[world_row + 1] - ys[world_row]);
351            if texel_y[row] == texel_y[row + 1] || h <= 0.0 {
352                continue;
353            }
354            for column in 0..3 {
355                let (x, w) = (xs[column], xs[column + 1] - xs[column]);
356                if texel_x[column] == texel_x[column + 1] || w <= 0.0 {
357                    continue;
358                }
359                out.push(SliceQuad {
360                    rect: [x, y, w, h],
361                    uv: [us[column], vs[row], us[column + 1], vs[row + 1]],
362                });
363            }
364        }
365        out
366    }
367
368    /// The insets, trimmed so they cannot exceed the frame.
369    ///
370    /// [`Sheet::validate`] refuses a sheet whose insets overlap, but this type
371    /// can be built by hand from any [`NineSlice`], and insets past the frame's
372    /// edge would make the cut lines run backwards — which is inside-out quads
373    /// rather than a visible error.
374    fn clamped(&self) -> NineSlice {
375        let left = self.nine.left.min(self.frame.w);
376        let top = self.nine.top.min(self.frame.h);
377        NineSlice {
378            left,
379            right: self.nine.right.min(self.frame.w - left),
380            top,
381            bottom: self.nine.bottom.min(self.frame.h - top),
382        }
383    }
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389    use crcbl_sprite::{Frame, SampleMode};
390
391    /// A 32×16 sheet with the frame **not** at the origin and **not** filling
392    /// it: an expansion that ignored `frame.x`/`frame.y`, or that divided by the
393    /// frame's size instead of the sheet's, lands on plausible-looking UVs on a
394    /// sheet where the frame is the whole image.
395    const FRAME: Rect = Rect::new(8, 4, 16, 8);
396
397    /// Insets that are **all different**, so a transposed or rotated pair cannot
398    /// compare equal by accident. Centre is 8 × 5 texels.
399    const NINE: NineSlice = NineSlice::new(3, 5, 2, 1);
400
401    fn source() -> NineSliceSource {
402        NineSliceSource {
403            nine: NINE,
404            frame: FRAME,
405            sheet_width: 32,
406            sheet_height: 16,
407            texels_per_unit: 1.0,
408        }
409    }
410
411    /// The `us`/`vs` the tests are written against, spelled out rather than
412    /// recomputed: `8/32, 11/32, 19/32, 24/32` and `4/16, 6/16, 11/16, 12/16`.
413    const US: [f32; 4] = [0.25, 0.343_75, 0.593_75, 0.75];
414    const VS: [f32; 4] = [0.25, 0.375, 0.687_5, 0.75];
415
416    fn quad(rect: [f32; 4], uv: [f32; 4]) -> SliceQuad {
417        SliceQuad { rect, uv }
418    }
419
420    // -----------------------------------------------------------------------
421    // Exact geometry
422    // -----------------------------------------------------------------------
423
424    /// **The identity case.** A target the size of the source must reproduce the
425    /// original single sprite exactly: nine quads that tile the frame's own
426    /// rectangle at one world unit per texel, with the frame's own UVs.
427    ///
428    /// Written out in full rather than checked as a property, because a property
429    /// ("the union is the target") is satisfied by nine quads with the *wrong*
430    /// UVs in them.
431    #[test]
432    fn a_target_the_size_of_the_source_reproduces_the_original_sprite() {
433        // World X cuts 100, 103, 111, 116; world Y cuts (ascending, so bottom
434        // first) 200, 201, 206, 208.
435        let quads = source().expand([100.0, 200.0, 16.0, 8.0]);
436        assert_eq!(
437            quads.as_slice(),
438            [
439                // Top row of the image: the highest world band, `top` = 2 tall.
440                quad([100.0, 206.0, 3.0, 2.0], [US[0], VS[0], US[1], VS[1]]),
441                quad([103.0, 206.0, 8.0, 2.0], [US[1], VS[0], US[2], VS[1]]),
442                quad([111.0, 206.0, 5.0, 2.0], [US[2], VS[0], US[3], VS[1]]),
443                // Middle row: the centre band, 5 tall.
444                quad([100.0, 201.0, 3.0, 5.0], [US[0], VS[1], US[1], VS[2]]),
445                quad([103.0, 201.0, 8.0, 5.0], [US[1], VS[1], US[2], VS[2]]),
446                quad([111.0, 201.0, 5.0, 5.0], [US[2], VS[1], US[3], VS[2]]),
447                // Bottom row of the image: the lowest world band, `bottom` = 1.
448                quad([100.0, 200.0, 3.0, 1.0], [US[0], VS[2], US[1], VS[3]]),
449                quad([103.0, 200.0, 8.0, 1.0], [US[1], VS[2], US[2], VS[3]]),
450                quad([111.0, 200.0, 5.0, 1.0], [US[2], VS[2], US[3], VS[3]]),
451            ]
452        );
453
454        // And the claim those numbers encode, said directly: every quad is at
455        // exactly one world unit per texel, which is what "reproduces the
456        // original" means and what a stretched identity case would break.
457        let source = source();
458        for quad in quads.as_slice() {
459            let texels_wide = (quad.uv[2] - quad.uv[0]) * source.sheet_width as f32;
460            let texels_tall = (quad.uv[3] - quad.uv[1]) * source.sheet_height as f32;
461            assert!(
462                (quad.rect[2] - texels_wide).abs() < 1e-4
463                    && (quad.rect[3] - texels_tall).abs() < 1e-4,
464                "{quad:?} covers {texels_wide}x{texels_tall} texels in \
465                 {}x{} world units",
466                quad.rect[2],
467                quad.rect[3]
468            );
469        }
470    }
471
472    /// Stretched on **one** axis only: the corners keep their width *and* their
473    /// height, the left and right edges take all of the extra height, and the
474    /// top and bottom edges are untouched.
475    #[test]
476    fn a_vertical_stretch_grows_only_the_bands_that_stretch_vertically() {
477        // Height 40 rather than 8: the centre band goes 5 → 37 and nothing else
478        // changes. World Y cuts 200, 201, 238, 240.
479        let quads = source().expand([100.0, 200.0, 16.0, 40.0]);
480        assert_eq!(
481            quads.as_slice(),
482            [
483                quad([100.0, 238.0, 3.0, 2.0], [US[0], VS[0], US[1], VS[1]]),
484                quad([103.0, 238.0, 8.0, 2.0], [US[1], VS[0], US[2], VS[1]]),
485                quad([111.0, 238.0, 5.0, 2.0], [US[2], VS[0], US[3], VS[1]]),
486                quad([100.0, 201.0, 3.0, 37.0], [US[0], VS[1], US[1], VS[2]]),
487                quad([103.0, 201.0, 8.0, 37.0], [US[1], VS[1], US[2], VS[2]]),
488                quad([111.0, 201.0, 5.0, 37.0], [US[2], VS[1], US[3], VS[2]]),
489                quad([100.0, 200.0, 3.0, 1.0], [US[0], VS[2], US[1], VS[3]]),
490                quad([103.0, 200.0, 8.0, 1.0], [US[1], VS[2], US[2], VS[3]]),
491                quad([111.0, 200.0, 5.0, 1.0], [US[2], VS[2], US[3], VS[3]]),
492            ],
493            "only the three quads of the middle image row may have changed height"
494        );
495    }
496
497    /// Stretched both ways, and by different factors on each axis — a square
498    /// target on a non-square frame is the one that cannot tell an axis swap.
499    #[test]
500    fn a_stretch_on_both_axes_grows_the_centre_on_both() {
501        // 48 × 40: world X cuts 100, 103, 143, 148; Y cuts 200, 201, 238, 240.
502        let quads = source().expand([100.0, 200.0, 48.0, 40.0]);
503        assert_eq!(
504            quads.as_slice(),
505            [
506                quad([100.0, 238.0, 3.0, 2.0], [US[0], VS[0], US[1], VS[1]]),
507                quad([103.0, 238.0, 40.0, 2.0], [US[1], VS[0], US[2], VS[1]]),
508                quad([143.0, 238.0, 5.0, 2.0], [US[2], VS[0], US[3], VS[1]]),
509                quad([100.0, 201.0, 3.0, 37.0], [US[0], VS[1], US[1], VS[2]]),
510                quad([103.0, 201.0, 40.0, 37.0], [US[1], VS[1], US[2], VS[2]]),
511                quad([143.0, 201.0, 5.0, 37.0], [US[2], VS[1], US[3], VS[2]]),
512                quad([100.0, 200.0, 3.0, 1.0], [US[0], VS[2], US[1], VS[3]]),
513                quad([103.0, 200.0, 40.0, 1.0], [US[1], VS[2], US[2], VS[3]]),
514                quad([143.0, 200.0, 5.0, 1.0], [US[2], VS[2], US[3], VS[3]]),
515            ]
516        );
517
518        // The four corners kept their natural size, which is the whole point.
519        for corner in [0usize, 2, 6, 8] {
520            let rect = quads.as_slice()[corner].rect;
521            assert!(
522                (rect[2] == 3.0 || rect[2] == 5.0) && (rect[3] == 2.0 || rect[3] == 1.0),
523                "corner {corner} is {}x{}, not an inset-sized block",
524                rect[2],
525                rect[3]
526            );
527        }
528    }
529
530    // -----------------------------------------------------------------------
531    // Seams
532    // -----------------------------------------------------------------------
533
534    /// **The seam property, stated as one.** Adjacent quads must share their
535    /// edge as the *same float*, in world space and in UV space. Anything less
536    /// is a one-texel seam that shows up between bands at some sizes and not
537    /// others.
538    ///
539    /// `assert_eq!` on `f32` and not a tolerance, deliberately: a tolerance is
540    /// exactly what "rounded slightly differently" passes.
541    #[test]
542    fn adjacent_quads_share_their_edges_exactly_in_world_and_uv_space() {
543        let source = source();
544        for target in [
545            [100.0f32, 200.0, 16.0, 8.0],
546            [100.0, 200.0, 16.0, 40.0],
547            [100.0, 200.0, 48.0, 40.0],
548            // Awkward on purpose: fractional origin and fractional extents, so
549            // the cuts are not exactly representable sums.
550            [-13.7, 4.3, 91.1, 250.9],
551            [0.1, 0.2, 8.3, 3.7],
552        ] {
553            let quads = source.expand(target);
554            assert_eq!(quads.len(), 9, "{target:?} should be a full nine");
555            // Image order is row-major over three rows of three.
556            for row in 0..3 {
557                for column in 0..2 {
558                    let left = quads[row * 3 + column];
559                    let right = quads[row * 3 + column + 1];
560                    assert_eq!(
561                        left.rect[0] + left.rect[2],
562                        right.rect[0],
563                        "world gap between columns {column} and {} of row {row} at {target:?}",
564                        column + 1
565                    );
566                    assert_eq!(
567                        left.uv[2],
568                        right.uv[0],
569                        "UV gap between columns {column} and {} of row {row} at {target:?}",
570                        column + 1
571                    );
572                }
573            }
574            for column in 0..3 {
575                for row in 0..2 {
576                    let upper = quads[row * 3 + column];
577                    let lower = quads[(row + 1) * 3 + column];
578                    // Image row `row + 1` is *below* row `row`, so in world
579                    // space it is the lower band: its top edge is the upper
580                    // band's bottom.
581                    assert_eq!(
582                        lower.rect[1] + lower.rect[3],
583                        upper.rect[1],
584                        "world gap between rows {row} and {} of column {column} at {target:?}",
585                        row + 1
586                    );
587                    assert_eq!(
588                        upper.uv[3],
589                        lower.uv[1],
590                        "UV gap between rows {row} and {} of column {column} at {target:?}",
591                        row + 1
592                    );
593                }
594            }
595
596            // And the outside edges are the target's own, not a sum that drifted.
597            assert_eq!(quads[6].rect[0], target[0]);
598            assert_eq!(quads[6].rect[1], target[1]);
599            assert_eq!(quads[2].rect[0] + quads[2].rect[2], target[0] + target[2]);
600            assert_eq!(quads[2].rect[1] + quads[2].rect[3], target[1] + target[3]);
601            // The UVs span the whole frame, top-left first.
602            assert_eq!([quads[0].uv[0], quads[0].uv[1]], [US[0], VS[0]]);
603            assert_eq!([quads[8].uv[2], quads[8].uv[3]], [US[3], VS[3]]);
604        }
605    }
606
607    // -----------------------------------------------------------------------
608    // Degenerate bands
609    // -----------------------------------------------------------------------
610
611    /// **A three-slice emits three quads, not nine.** `top == bottom == 0` is
612    /// the ordinary shape of a horizontal bar, and the six zero-height quads an
613    /// unconditional nine would emit are invisible, cost a full instance each,
614    /// and carry a UV rectangle of zero extent.
615    #[test]
616    fn a_three_slice_emits_three_quads_and_a_plain_frame_emits_one() {
617        let mut source = source();
618        source.nine = NineSlice::new(3, 5, 0, 0);
619        let quads = source.expand([100.0, 200.0, 48.0, 40.0]);
620        assert_eq!(quads.len(), 3, "left cap, stretch, right cap");
621        assert_eq!(
622            quads.as_slice(),
623            [
624                quad([100.0, 200.0, 3.0, 40.0], [US[0], VS[0], US[1], VS[3]]),
625                quad([103.0, 200.0, 40.0, 40.0], [US[1], VS[0], US[2], VS[3]]),
626                quad([143.0, 200.0, 5.0, 40.0], [US[2], VS[0], US[3], VS[3]]),
627            ],
628            "each spans the frame's full height, and none is zero-height"
629        );
630
631        // The other three-slice, vertical: `left == right == 0`.
632        source.nine = NineSlice::new(0, 0, 2, 1);
633        let quads = source.expand([100.0, 200.0, 48.0, 40.0]);
634        assert_eq!(quads.len(), 3, "top cap, stretch, bottom cap");
635        assert_eq!(
636            quads.as_slice(),
637            [
638                quad([100.0, 238.0, 48.0, 2.0], [US[0], VS[0], US[3], VS[1]]),
639                quad([100.0, 201.0, 48.0, 37.0], [US[0], VS[1], US[3], VS[2]]),
640                quad([100.0, 200.0, 48.0, 1.0], [US[0], VS[2], US[3], VS[3]]),
641            ]
642        );
643
644        // And no insets at all is one quad that *is* the plain sprite: the
645        // target rect, and the frame's own UVs.
646        source.nine = NineSlice::new(0, 0, 0, 0);
647        let quads = source.expand([100.0, 200.0, 48.0, 40.0]);
648        assert_eq!(quads.len(), 1);
649        assert_eq!(
650            quads[0],
651            quad([100.0, 200.0, 48.0, 40.0], [US[0], VS[0], US[3], VS[3]])
652        );
653        let sheet_uv = Sheet {
654            width: 32,
655            height: 16,
656            frames: vec![Frame {
657                name: "only".into(),
658                rect: FRAME,
659                hold: 1,
660            }],
661            ..Sheet::default()
662        }
663        .uv(0)
664        .expect("the frame exists");
665        assert_eq!(
666            quads[0].uv, sheet_uv,
667            "an un-inset expansion must agree with Sheet::uv exactly, or the two \
668             paths sample different pixels for the same frame"
669        );
670    }
671
672    /// A band that is non-empty in texels but zero in **world** units is dropped
673    /// too: a target exactly as tall as `top + bottom` has no centre to draw.
674    #[test]
675    fn a_band_with_no_world_extent_is_dropped_even_when_it_has_texels() {
676        // Height exactly 3 = top + bottom, width 48.
677        let quads = source().expand([100.0, 200.0, 48.0, 3.0]);
678        assert_eq!(quads.len(), 6, "the middle image row has nowhere to go");
679        for quad in quads.as_slice() {
680            assert!(quad.rect[3] > 0.0, "{quad:?} has no height");
681            assert!(quad.rect[2] > 0.0, "{quad:?} has no width");
682        }
683        // Still exactly the two rows, touching: the bottom band is 200..201 and
684        // the top band 201..203, with no gap where the centre would have been.
685        assert_eq!((quads[0].rect[1], quads[0].rect[3]), (201.0, 2.0));
686        assert_eq!((quads[3].rect[1], quads[3].rect[3]), (200.0, 1.0));
687        assert_eq!(quads[3].rect[1] + quads[3].rect[3], quads[0].rect[1]);
688    }
689
690    /// A target with no area, and a nonsense one, draw nothing rather than
691    /// something inside out.
692    #[test]
693    fn a_target_with_no_area_draws_nothing() {
694        let source = source();
695        assert!(source.expand([0.0, 0.0, 0.0, 40.0]).is_empty());
696        assert!(source.expand([0.0, 0.0, 40.0, 0.0]).is_empty());
697        assert!(source.expand([0.0, 0.0, -10.0, -10.0]).is_empty());
698        assert!(source.expand([0.0, 0.0, f32::NAN, 40.0]).is_empty());
699
700        // A sheet with no size would divide by zero and hand a NaN to a vertex
701        // buffer — the case `Sheet::uv` refuses for the same reason.
702        let sizeless = NineSliceSource {
703            sheet_width: 0,
704            ..source
705        };
706        assert!(sizeless.expand([0.0, 0.0, 40.0, 40.0]).is_empty());
707    }
708
709    // -----------------------------------------------------------------------
710    // Below the minimum
711    // -----------------------------------------------------------------------
712
713    /// **Below `minimum_size` the fixed bands shrink in proportion, the
714    /// stretched band vanishes, and the quads still tile the target exactly.**
715    ///
716    /// The decision is written up on [`NineSliceSource::expand`]. What is
717    /// asserted here is the part a reader would otherwise have to take on trust:
718    /// nothing inverts, nothing leaves the target, and the four corners are
719    /// still all that is drawn.
720    #[test]
721    fn a_target_below_the_minimum_shrinks_the_corners_rather_than_overlapping() {
722        let source = source();
723        assert_eq!(source.minimum_size(), (8.0, 3.0), "3 + 5 wide, 2 + 1 tall");
724
725        // Half the minimum width, two thirds the minimum height.
726        let quads = source.expand([0.0, 0.0, 4.0, 2.0]);
727        assert_eq!(quads.len(), 4, "the four corners and nothing else");
728        // `left = 3, right = 5` at half scale is 1.5 and 2.5; `bottom = 1,
729        // top = 2` at two thirds is 0.666… and 1.333….
730        let third = 2.0f32 / 3.0;
731        assert_eq!(
732            quads.as_slice(),
733            [
734                quad([0.0, third, 1.5, 2.0 - third], [US[0], VS[0], US[1], VS[1]]),
735                quad([1.5, third, 2.5, 2.0 - third], [US[2], VS[0], US[3], VS[1]]),
736                quad([0.0, 0.0, 1.5, third], [US[0], VS[2], US[1], VS[3]]),
737                quad([1.5, 0.0, 2.5, third], [US[2], VS[2], US[3], VS[3]]),
738            ]
739        );
740
741        // The properties, said directly rather than left implicit in the
742        // numbers: inside the target, tiling it, no overlap.
743        for quad in quads.as_slice() {
744            assert!(
745                quad.rect[2] > 0.0 && quad.rect[3] > 0.0,
746                "{quad:?} inverted"
747            );
748            assert!(quad.rect[0] >= 0.0 && quad.rect[0] + quad.rect[2] <= 4.0);
749            assert!(quad.rect[1] >= 0.0 && quad.rect[1] + quad.rect[3] <= 2.0);
750        }
751        let area: f32 = quads.iter().map(|quad| quad.rect[2] * quad.rect[3]).sum();
752        assert!(
753            (area - 8.0).abs() < 1e-5,
754            "the four corners must tile the whole 4x2 target with no overlap; \
755             they cover {area}"
756        );
757
758        // **Continuity at the boundary.** Approaching the minimum from below has
759        // to arrive where the ordinary path starts, or a shrinking pipe jumps.
760        let just_under = source.expand([0.0, 0.0, 8.0 - 1e-4, 3.0]);
761        let at_minimum = source.expand([0.0, 0.0, 8.0, 3.0]);
762        assert_eq!(at_minimum.len(), 4, "no centre and no edges at the minimum");
763        for (under, at) in just_under.iter().zip(at_minimum.iter()) {
764            for lane in 0..4 {
765                assert!(
766                    (under.rect[lane] - at.rect[lane]).abs() < 1e-3,
767                    "a jump at the minimum: {under:?} against {at:?}"
768                );
769            }
770        }
771
772        // Each axis decides on its own.
773        let narrow = source.expand([0.0, 0.0, 4.0, 40.0]);
774        assert_eq!(narrow.len(), 6, "squashed across, still stretched down");
775        assert_eq!(narrow[0].rect[2], 1.5, "the left cap shrank");
776        assert_eq!(narrow[2].rect[3], 37.0, "and the left edge still stretched");
777    }
778
779    /// Insets that overrun the frame are trimmed rather than producing cut lines
780    /// that run backwards. [`Sheet::validate`] refuses such a sheet, but this
781    /// type can be built from any [`NineSlice`].
782    #[test]
783    fn insets_wider_than_the_frame_are_trimmed_rather_than_inverted() {
784        let mut source = source();
785        source.nine = NineSlice::new(20, 20, 0, 0);
786        let quads = source.expand([0.0, 0.0, 100.0, 10.0]);
787        assert!(!quads.is_empty(), "a bad slice must still draw something");
788        for quad in quads.as_slice() {
789            assert!(
790                quad.uv[0] <= quad.uv[2] && quad.uv[1] <= quad.uv[3],
791                "{quad:?} has an inside-out UV rect"
792            );
793            assert!(quad.rect[2] > 0.0 && quad.rect[3] > 0.0);
794        }
795        // The frame is 16 wide, so `left` takes all of it and `right` gets none.
796        assert_eq!(quads.len(), 1);
797        assert_eq!(quads[0].uv, [US[0], VS[0], US[3], VS[3]]);
798    }
799
800    // -----------------------------------------------------------------------
801    // The texels-per-unit scale
802    // -----------------------------------------------------------------------
803
804    /// **A scale turns the fixed bands into caller units.** A pipe-style
805    /// three-slice (`top == bottom == 6` texels) at twenty texels per unit draws
806    /// its caps 6 / 20 = 0.3 units tall, and `minimum_size` reports the same
807    /// units.
808    #[test]
809    fn a_scale_makes_the_fixed_bands_come_back_in_caller_units() {
810        let mut source = source();
811        source.nine = NineSlice::new(0, 0, 6, 6);
812        // Taller than the frame the helper ships with: the clamp trims insets
813        // to the frame, and the pipe both caps fit in needs 12 texels of height.
814        source.frame = Rect::new(8, 4, 16, 24);
815        let scaled = source.with_texels_per_unit(20.0);
816
817        assert_eq!(
818            scaled.minimum_size(),
819            (0.0, 12.0 / 20.0),
820            "0 + 0 wide, 6 + 6 tall, in caller units"
821        );
822        assert_eq!(
823            source.minimum_size(),
824            (0.0, 12.0),
825            "the un-scaled source keeps its texel-sized minimum"
826        );
827
828        let quads = scaled.expand([0.0, 0.0, 2.0, 20.0]);
829        assert_eq!(quads.len(), 3, "a three-slice: cap, shaft, cap");
830        for (cap, which) in [(0usize, "top"), (2, "bottom")] {
831            let h = quads[cap].rect[3];
832            assert!(
833                (h - 6.0 / 20.0).abs() < 1e-4,
834                "the {which} cap is {h} tall, not 0.3"
835            );
836        }
837        // The shaft takes the rest of the 20-unit target.
838        assert!((quads[1].rect[3] - 19.4).abs() < 1e-4);
839
840        // Without the scale the same target draws 6-unit caps — the behaviour
841        // this feature exists to replace.
842        let plain = source.expand([0.0, 0.0, 2.0, 20.0]);
843        assert_eq!(plain[0].rect[3], 6.0);
844        assert_eq!(plain[2].rect[3], 6.0);
845    }
846
847    /// **A scaled expand still tiles the target exactly and samples the same
848    /// texels.** Only the units change: the quads cover the target edge-to-edge
849    /// with the corners at their natural size, and their UVs are the unscaled
850    /// ones — the texel cuts never see the scale.
851    #[test]
852    fn a_scaled_expand_tiles_the_target_with_the_same_uvs() {
853        let plain = source();
854        let scaled = plain.with_texels_per_unit(20.0);
855        let target = [100.0f32, 200.0, 16.0, 8.0];
856        let quads = scaled.expand(target);
857        assert_eq!(quads.len(), 9, "the target is well above the minimum");
858
859        // Same nine quads, in the same order, sampling the same texels.
860        for (scaled_quad, plain_quad) in quads.iter().zip(plain.expand(target).iter()) {
861            assert_eq!(scaled_quad.uv, plain_quad.uv, "the scale touched the UVs");
862        }
863
864        // The corners are at their natural size: `inset / texels_per_unit`.
865        for corner in [0usize, 2, 6, 8] {
866            let (w, h) = (quads[corner].rect[2], quads[corner].rect[3]);
867            assert!(
868                (w - 3.0 / 20.0).abs() < 1e-4 || (w - 5.0 / 20.0).abs() < 1e-4,
869                "corner {corner} is {w} wide, not an inset-sized block"
870            );
871            assert!(
872                (h - 2.0 / 20.0).abs() < 1e-4 || (h - 1.0 / 20.0).abs() < 1e-4,
873                "corner {corner} is {h} tall, not an inset-sized block"
874            );
875        }
876
877        // And the quads tile `target` exactly: shared edges are the *same*
878        // float and the outside edges are the target's own.
879        for row in 0..3 {
880            for column in 0..2 {
881                let left = quads[row * 3 + column];
882                let right = quads[row * 3 + column + 1];
883                assert_eq!(
884                    left.rect[0] + left.rect[2],
885                    right.rect[0],
886                    "world gap between columns {column} and {} of row {row}",
887                    column + 1
888                );
889            }
890        }
891        for column in 0..3 {
892            for row in 0..2 {
893                let upper = quads[row * 3 + column];
894                let lower = quads[(row + 1) * 3 + column];
895                assert_eq!(
896                    lower.rect[1] + lower.rect[3],
897                    upper.rect[1],
898                    "world gap between rows {row} and {} of column {column}",
899                    row + 1
900                );
901            }
902        }
903        assert_eq!(quads[6].rect[0], target[0]);
904        assert_eq!(quads[6].rect[1], target[1]);
905        assert_eq!(quads[2].rect[0] + quads[2].rect[2], target[0] + target[2]);
906        assert_eq!(quads[2].rect[1] + quads[2].rect[3], target[1] + target[3]);
907    }
908
909    /// **A scale of one is exactly the old behaviour.** `from_sheet` defaults
910    /// the field to 1 and this pins the two together: the identity, the
911    /// stretch, the below-minimum and the awkward-fractional targets all come
912    /// back identical to an un-scaled source, bit for bit.
913    #[test]
914    fn a_scale_of_one_is_exactly_the_default() {
915        let source = source();
916        let one = source.with_texels_per_unit(1.0);
917        for target in [
918            [100.0f32, 200.0, 16.0, 8.0],
919            [100.0, 200.0, 16.0, 40.0],
920            [0.0, 0.0, 4.0, 2.0],
921            [-13.7, 4.3, 91.1, 250.9],
922        ] {
923            assert_eq!(one.expand(target), source.expand(target), "{target:?}");
924        }
925        assert_eq!(one.minimum_size(), source.minimum_size());
926    }
927
928    // -----------------------------------------------------------------------
929    // The bridge to the renderer
930    // -----------------------------------------------------------------------
931
932    /// `from_sheet` reads the insets, the frame and the divisor from one place,
933    /// and refuses the three cases that would produce a `NaN` or index nothing.
934    #[test]
935    fn a_source_can_be_taken_straight_off_a_sheet() {
936        let mut sheet = Sheet {
937            width: 32,
938            height: 16,
939            frames: vec![Frame {
940                name: "pipe".into(),
941                rect: FRAME,
942                hold: 1,
943            }],
944            clips: Vec::new(),
945            nine: Some(NINE),
946            sample: SampleMode::Pixel,
947        };
948        sheet.validate().expect("well formed");
949        let source = NineSliceSource::from_sheet(&sheet, 0).expect("it has a nine and a frame");
950        assert_eq!(source, self::source());
951        assert_eq!(
952            NineSliceSource::from_sheet(&sheet, 1),
953            None,
954            "no such frame"
955        );
956
957        sheet.nine = None;
958        assert_eq!(
959            NineSliceSource::from_sheet(&sheet, 0),
960            None,
961            "no nine-slice"
962        );
963
964        sheet.nine = Some(NINE);
965        sheet.height = 0;
966        assert_eq!(
967            NineSliceSource::from_sheet(&sheet, 0),
968            None,
969            "a sheet with no size is the divide-by-zero Sheet::uv also refuses"
970        );
971    }
972
973    /// The quads become sprites without a conversion: same rect, same uv, the
974    /// sheet and tint the caller named, and **in the order they were emitted**.
975    #[test]
976    fn quads_become_sprites_in_order_with_the_sheet_and_tint_they_were_given() {
977        let quads = source().expand([100.0, 200.0, 48.0, 40.0]);
978        let sheet = SheetId(3);
979        let tint = [0.1, 0.2, 0.3, 0.4];
980        let sprites: Vec<Sprite> = quads.sprites(sheet, tint).collect();
981        assert_eq!(sprites.len(), quads.len());
982        for (sprite, quad) in sprites.iter().zip(quads.iter()) {
983            assert_eq!(sprite.sheet, sheet);
984            assert_eq!(sprite.rect, quad.rect);
985            assert_eq!(sprite.uv, quad.uv);
986            assert_eq!(sprite.tint, tint);
987        }
988    }
989}