viewport-lib-types 0.4.0

Pure-data types for viewport-lib: submission payloads, handles, and frame config, free of any GPU dependency.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! An RGBA colour, stored in linear space.
//!
//! The renderer works in linear light and writes to an sRGB target, so the
//! hardware applies a linear->sRGB encode on write. A colour taken from a hex
//! code or a colour picker is an sRGB value; handing those bytes straight to the
//! renderer encodes them a second time and washes them out. [`Colour`] removes
//! that trap: you build it from whatever space your value is in (`srgb`, `rgb`,
//! `hex`, `hsl`, or `linear`) and it stores the linear form, so every colour
//! reaching the GPU is already in the space the pipeline expects.
//!
//! Pick the constructor by where the value came from:
//!
//! - A hex code, a colour picker, a design token: [`Colour::hex`],
//!   [`Colour::rgb`], [`Colour::srgb`], [`Colour::hsl`]. These decode sRGB to
//!   linear for you.
//! - A light colour, a value you computed in linear space, a colourmap sample:
//!   [`Colour::linear`]. This passes through untouched.

/// Decode one 0..=1 sRGB channel to linear (the sRGB electro-optical transfer
/// function). Alpha is not an sRGB quantity and must not be passed through here.
pub fn srgb_to_linear(c: f32) -> f32 {
    if c <= 0.040_45 {
        c / 12.92
    } else {
        ((c + 0.055) / 1.055).powf(2.4)
    }
}

/// Encode one linear channel back to 0..=1 sRGB (the inverse of
/// [`srgb_to_linear`]). Useful for reporting a stored linear colour as the hex
/// a consumer would recognise.
pub fn linear_to_srgb(c: f32) -> f32 {
    if c <= 0.003_130_8 {
        12.92 * c
    } else {
        1.055 * c.powf(1.0 / 2.4) - 0.055
    }
}

/// The colour space a set of channel values is expressed in.
///
/// Used at boundaries where the same byte layout can mean either space: an
/// 8-bit texture is sRGB when it holds a base-colour image and linear when it
/// holds data (roughness, metallic, a normal map). Direct [`Colour`] values do
/// not need this, since the constructor already fixes the space.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ColourSpace {
    /// sRGB-encoded: decode to linear before use.
    Srgb,
    /// Already linear: use as-is.
    Linear,
}

/// An RGBA colour in linear space, alpha last.
///
/// Construct it from the space your value is in; it stores the linear form.
/// [`to_linear_rgba`](Self::to_linear_rgba) and
/// [`to_linear_rgb`](Self::to_linear_rgb) hand the pipeline the array it wants.
///
/// Channels must be finite. Values above 1.0 are valid and meaningful: an
/// emissive or otherwise HDR colour carries radiance beyond the display range,
/// so `Colour` never clamps. A NaN or infinite channel, by contrast, is never a
/// valid colour and produces undefined output when written to the target; the
/// constructors do not reject it (a `sRGB` build from finite input can never
/// manufacture one), so guard external data with [`is_finite`](Self::is_finite)
/// if its provenance is uncertain.
///
/// ```
/// use viewport_lib_types::colour::Colour;
/// // Navy #183054 from a hex code renders faithfully:
/// let navy = Colour::hex("#183054").unwrap();
/// // A light colour is already linear:
/// let warm = Colour::linear_rgb(1.0, 0.9, 0.7);
/// ```
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct Colour([f32; 4]);

impl Colour {
    /// Opaque white.
    pub const WHITE: Colour = Colour([1.0, 1.0, 1.0, 1.0]);
    /// Opaque black.
    pub const BLACK: Colour = Colour([0.0, 0.0, 0.0, 1.0]);
    /// Fully transparent (all channels zero).
    pub const TRANSPARENT: Colour = Colour([0.0, 0.0, 0.0, 0.0]);

    /// A linear RGBA colour, stored verbatim. Use this for light colours,
    /// colourmap samples, and any value already computed in linear space.
    pub const fn linear(r: f32, g: f32, b: f32, a: f32) -> Self {
        Colour([r, g, b, a])
    }

    /// A linear RGB colour with alpha 1.0. See [`linear`](Self::linear).
    pub const fn linear_rgb(r: f32, g: f32, b: f32) -> Self {
        Colour([r, g, b, 1.0])
    }

    /// A linear RGBA array, stored verbatim: for values already held as arrays,
    /// such as a colourmap sample or a vertex colour read from a buffer.
    pub const fn from_linear_array(rgba: [f32; 4]) -> Self {
        Colour(rgba)
    }

    /// A linear RGB array with alpha 1.0. See
    /// [`from_linear_array`](Self::from_linear_array).
    pub const fn from_linear_rgb_array(rgb: [f32; 3]) -> Self {
        Colour([rgb[0], rgb[1], rgb[2], 1.0])
    }

    /// An sRGB RGBA colour with 0..=1 channels. The RGB channels are decoded to
    /// linear; alpha is a linear coverage value and is stored as given.
    pub fn srgb(r: f32, g: f32, b: f32, a: f32) -> Self {
        Colour([srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), a])
    }

    /// An sRGB RGB colour with 0..=1 channels and alpha 1.0. See
    /// [`srgb`](Self::srgb).
    pub fn srgb_rgb(r: f32, g: f32, b: f32) -> Self {
        Self::srgb(r, g, b, 1.0)
    }

    /// An sRGB RGBA array with 0..=1 channels: for values already held as
    /// arrays, such as a theme table or a colour read from a saved document.
    /// See [`srgb`](Self::srgb).
    pub fn from_srgb_array([r, g, b, a]: [f32; 4]) -> Self {
        Self::srgb(r, g, b, a)
    }

    /// An sRGB RGB array with alpha 1.0. See
    /// [`from_srgb_array`](Self::from_srgb_array).
    pub fn from_srgb_rgb_array([r, g, b]: [f32; 3]) -> Self {
        Self::srgb(r, g, b, 1.0)
    }

    /// An sRGB RGBA colour from 8-bit channels (the form a hex code or colour
    /// picker gives). RGB is decoded to linear; alpha is scaled to 0..=1.
    pub fn srgb_u8(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self::srgb(
            r as f32 / 255.0,
            g as f32 / 255.0,
            b as f32 / 255.0,
            a as f32 / 255.0,
        )
    }

    /// An opaque sRGB colour from 8-bit channels, `rgb(r, g, b)`. Alpha 255.
    pub fn rgb(r: u8, g: u8, b: u8) -> Self {
        Self::srgb_u8(r, g, b, 255)
    }

    /// An sRGB colour from 8-bit channels including alpha, `rgba(r, g, b, a)`.
    pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self::srgb_u8(r, g, b, a)
    }

    /// Parse an sRGB hex code: `#RGB`, `#RRGGBB`, or `#RRGGBBAA` (the leading
    /// `#` is optional). RGB is decoded to linear; alpha defaults to opaque when
    /// absent.
    pub fn hex(s: &str) -> Result<Self, ColourParseError> {
        let h = s.strip_prefix('#').unwrap_or(s);
        // Expand the shorthand #RGB to #RRGGBB.
        let expanded: String;
        let h = if h.len() == 3 {
            expanded = h.chars().flat_map(|c| [c, c]).collect();
            expanded.as_str()
        } else {
            h
        };
        let byte = |i: usize| -> Result<u8, ColourParseError> {
            u8::from_str_radix(&h[i..i + 2], 16).map_err(|_| ColourParseError::BadDigit)
        };
        match h.len() {
            6 => Ok(Self::rgb(byte(0)?, byte(2)?, byte(4)?)),
            8 => Ok(Self::rgba(byte(0)?, byte(2)?, byte(4)?, byte(6)?)),
            _ => Err(ColourParseError::BadLength),
        }
    }

    /// An sRGB colour from hue-saturation-lightness. `h` is in degrees
    /// (wrapped into 0..360), `s` and `l` are 0..=1. The result is treated as
    /// sRGB and decoded to linear. Alpha 1.0.
    pub fn hsl(h: f32, s: f32, l: f32) -> Self {
        let (r, g, b) = hsl_to_rgb(h, s, l);
        Self::srgb_rgb(r, g, b)
    }

    /// An sRGB colour from hue-saturation-value. `h` is in degrees (wrapped
    /// into 0..360), `s` and `v` are 0..=1. The result is treated as sRGB and
    /// decoded to linear. Alpha 1.0.
    pub fn hsv(h: f32, s: f32, v: f32) -> Self {
        let (r, g, b) = hsv_to_rgb(h, s, v);
        Self::srgb_rgb(r, g, b)
    }

    /// This colour with its alpha replaced (alpha is linear coverage, 0..=1).
    pub fn with_alpha(self, a: f32) -> Self {
        Colour([self.0[0], self.0[1], self.0[2], a])
    }

    /// The linear RGBA array the GPU consumes.
    pub const fn to_linear_rgba(self) -> [f32; 4] {
        self.0
    }

    /// The linear RGB array, dropping alpha. For fields that carry colour
    /// without an alpha channel (base colour, emissive, light colour).
    pub const fn to_linear_rgb(self) -> [f32; 3] {
        [self.0[0], self.0[1], self.0[2]]
    }

    /// The sRGB RGBA array, the inverse of [`srgb`](Self::srgb): RGB is
    /// encoded, alpha is returned as stored. For comparing against the colour a
    /// theme or document asked for, or showing it in a colour picker.
    pub fn to_srgb_rgba(self) -> [f32; 4] {
        [
            linear_to_srgb(self.0[0]),
            linear_to_srgb(self.0[1]),
            linear_to_srgb(self.0[2]),
            self.0[3],
        ]
    }

    /// The sRGB RGB array, dropping alpha. See
    /// [`to_srgb_rgba`](Self::to_srgb_rgba).
    pub fn to_srgb_rgb(self) -> [f32; 3] {
        let [r, g, b, _] = self.to_srgb_rgba();
        [r, g, b]
    }

    /// The alpha channel (linear coverage, 0..=1).
    pub const fn alpha(self) -> f32 {
        self.0[3]
    }

    /// Relative luminance, from the Rec. 709 weights on the linear channels.
    /// Alpha is ignored. `0.0` is black and `1.0` is white; HDR colours go
    /// above one.
    pub fn luminance(self) -> f32 {
        0.2126 * self.0[0] + 0.7152 * self.0[1] + 0.0722 * self.0[2]
    }

    /// Interpolate towards `other` by `t`, per channel in linear space, alpha
    /// included. `t` is not clamped, so values outside `0..=1` extrapolate.
    pub fn lerp(self, other: Colour, t: f32) -> Colour {
        let [a, b] = [self.0, other.0];
        Colour(std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t))
    }

    /// This colour composited over `below`, the standard source-over blend for
    /// straight (unpremultiplied) alpha, in linear space. Fully transparent
    /// over fully transparent is [`TRANSPARENT`](Self::TRANSPARENT).
    pub fn over(self, below: Colour) -> Colour {
        let (src, dst) = (self.0, below.0);
        let dst_weight = dst[3] * (1.0 - src[3]);
        let alpha = src[3] + dst_weight;
        if alpha <= 0.0 {
            return Self::TRANSPARENT;
        }
        let mix = |i: usize| (src[i] * src[3] + dst[i] * dst_weight) / alpha;
        Colour([mix(0), mix(1), mix(2), alpha])
    }

    /// Whether every channel (including alpha) is finite. A NaN or infinite
    /// channel is never a valid colour and writes undefined output to the
    /// target. Values above 1.0 are finite and valid (HDR / emissive), so this
    /// returns `true` for them. Use it to screen colours built from external or
    /// computed data before handing them to the renderer.
    pub fn is_finite(self) -> bool {
        self.0.iter().all(|c| c.is_finite())
    }

    /// Re-encode to opaque-agnostic 8-bit sRGB channels `[r, g, b, a]`, the
    /// inverse of [`srgb_u8`](Self::srgb_u8). Handy for logging a stored colour
    /// as the hex a consumer would recognise.
    pub fn to_srgb_u8(self) -> [u8; 4] {
        let enc = |c: f32| (linear_to_srgb(c).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
        [
            enc(self.0[0]),
            enc(self.0[1]),
            enc(self.0[2]),
            (self.0[3].clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
        ]
    }
}

impl From<Colour> for [f32; 4] {
    fn from(c: Colour) -> Self {
        c.0
    }
}

impl From<Colour> for [f32; 3] {
    fn from(c: Colour) -> Self {
        c.to_linear_rgb()
    }
}

/// Why parsing a hex colour failed.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ColourParseError {
    /// The string was not 3, 6, or 8 hex digits (after an optional `#`).
    BadLength,
    /// A character was not a hex digit.
    BadDigit,
}

impl core::fmt::Display for ColourParseError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            ColourParseError::BadLength => f.write_str("hex colour must be 3, 6, or 8 hex digits"),
            ColourParseError::BadDigit => f.write_str("hex colour contains a non-hex character"),
        }
    }
}

impl std::error::Error for ColourParseError {}

/// HSL to sRGB RGB, all outputs 0..=1. `h` in degrees, `s`/`l` in 0..=1.
fn hsl_to_rgb(h: f32, s: f32, l: f32) -> (f32, f32, f32) {
    let h = h.rem_euclid(360.0);
    let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
    let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
    let m = l - c / 2.0;
    let (r, g, b) = hue_sector(h, c, x);
    (r + m, g + m, b + m)
}

/// HSV to sRGB RGB, all outputs 0..=1. `h` in degrees, `s`/`v` in 0..=1.
fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) {
    let h = h.rem_euclid(360.0);
    let c = v * s;
    let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
    let m = v - c;
    let (r, g, b) = hue_sector(h, c, x);
    (r + m, g + m, b + m)
}

/// Place the chroma/second-largest components into RGB by hue sector.
fn hue_sector(h: f32, c: f32, x: f32) -> (f32, f32, f32) {
    match h as u32 / 60 {
        0 => (c, x, 0.0),
        1 => (x, c, 0.0),
        2 => (0.0, c, x),
        3 => (0.0, x, c),
        4 => (x, 0.0, c),
        _ => (c, 0.0, x),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn luminance_runs_black_to_white() {
        assert_eq!(Colour::BLACK.luminance(), 0.0);
        assert!((Colour::WHITE.luminance() - 1.0).abs() < 1e-6);
        // Green carries most of the weight.
        let g = Colour::linear_rgb(0.0, 1.0, 0.0).luminance();
        let r = Colour::linear_rgb(1.0, 0.0, 0.0).luminance();
        assert!(g > r);
    }

    #[test]
    fn lerp_hits_both_ends() {
        let a = Colour::linear(0.0, 0.2, 0.4, 1.0);
        let b = Colour::linear(1.0, 0.6, 0.0, 0.0);
        assert_eq!(a.lerp(b, 0.0), a);
        assert_eq!(a.lerp(b, 1.0), b);
        let mid = a.lerp(b, 0.5).to_linear_rgba();
        for (m, e) in mid.iter().zip([0.5, 0.4, 0.2, 0.5]) {
            assert!((m - e).abs() < 1e-6, "{mid:?}");
        }
    }

    #[test]
    fn over_composites_straight_alpha() {
        let red = Colour::linear(1.0, 0.0, 0.0, 1.0);
        let blue = Colour::linear(0.0, 0.0, 1.0, 1.0);
        assert_eq!(red.over(blue), red, "opaque source covers");
        assert_eq!(
            Colour::TRANSPARENT.over(blue),
            blue,
            "transparent source shows through"
        );
        assert_eq!(
            Colour::TRANSPARENT.over(Colour::TRANSPARENT),
            Colour::TRANSPARENT
        );

        // Half red over opaque blue: an even mix, fully opaque.
        let c = red.with_alpha(0.5).over(blue).to_linear_rgba();
        assert_eq!(c, [0.5, 0.0, 0.5, 1.0]);

        // Over a transparent backdrop the source keeps its own colour.
        let c = red
            .with_alpha(0.5)
            .over(Colour::TRANSPARENT)
            .to_linear_rgba();
        assert_eq!(c, [1.0, 0.0, 0.0, 0.5]);
    }

    #[test]
    fn linear_passthrough() {
        let c = Colour::linear(0.1, 0.2, 0.3, 0.4);
        assert_eq!(c.to_linear_rgba(), [0.1, 0.2, 0.3, 0.4]);
    }

    #[test]
    fn srgb_decodes_and_round_trips() {
        // Navy #183054 and gold #FADA16 must re-encode to the original bytes.
        for (r, g, b) in [(24, 48, 84), (250, 218, 22)] {
            let c = Colour::rgb(r, g, b);
            assert_eq!(c.to_srgb_u8(), [r, g, b, 255]);
        }
    }

    #[test]
    fn srgb_arrays_match_the_channel_constructors_and_round_trip() {
        let rgba = [0.2, 0.45, 0.9, 0.5];
        let c = Colour::from_srgb_array(rgba);
        assert_eq!(c, Colour::srgb(0.2, 0.45, 0.9, 0.5));
        assert_eq!(
            Colour::from_srgb_rgb_array([0.2, 0.45, 0.9]),
            Colour::srgb_rgb(0.2, 0.45, 0.9)
        );
        for (got, want) in c.to_srgb_rgba().iter().zip(rgba) {
            assert!((got - want).abs() < 1e-5, "{got} vs {want}");
        }
        assert_eq!(c.to_srgb_rgba()[3], 0.5);
        assert_eq!(c.to_srgb_rgb(), {
            let [r, g, b, _] = c.to_srgb_rgba();
            [r, g, b]
        });
    }

    #[test]
    fn hex_forms() {
        assert_eq!(Colour::hex("#183054").unwrap(), Colour::rgb(24, 48, 84));
        assert_eq!(Colour::hex("183054").unwrap(), Colour::rgb(24, 48, 84));
        // #RGB shorthand expands each nibble.
        assert_eq!(Colour::hex("#abc").unwrap(), Colour::rgb(0xaa, 0xbb, 0xcc));
        // #RRGGBBAA carries alpha.
        assert_eq!(
            Colour::hex("#18305480").unwrap(),
            Colour::rgba(24, 48, 84, 0x80)
        );
        assert_eq!(Colour::hex("#zz").err(), Some(ColourParseError::BadLength));
        assert_eq!(
            Colour::hex("#gggggg").err(),
            Some(ColourParseError::BadDigit)
        );
    }

    #[test]
    fn alpha_is_not_decoded() {
        // Alpha 128/255 stays a straight ratio, not an sRGB-decoded one.
        let c = Colour::rgba(0, 0, 0, 128);
        assert!((c.alpha() - 128.0 / 255.0).abs() < 1e-4);
    }

    #[test]
    fn srgb_is_darker_than_linear_for_same_bytes() {
        // The whole point: sRGB 0.5 decodes to a smaller linear value.
        let s = Colour::srgb_rgb(0.5, 0.5, 0.5).to_linear_rgb();
        assert!(s[0] < 0.5 - 0.05);
    }

    #[test]
    fn is_finite_flags_bad_channels() {
        assert!(Colour::rgb(24, 48, 84).is_finite());
        // HDR values above 1.0 are valid, not flagged.
        assert!(Colour::linear(2.5, 0.0, 0.0, 1.0).is_finite());
        assert!(!Colour::linear(f32::NAN, 0.0, 0.0, 1.0).is_finite());
        assert!(!Colour::linear(0.0, f32::INFINITY, 0.0, 1.0).is_finite());
        // A finite sRGB build never manufactures a NaN.
        assert!(Colour::srgb(-0.1, 0.5, 1.2, 1.0).is_finite());
    }

    #[test]
    fn hsl_matches_known_colour() {
        // HSL(216, 56%, 21%) is navy #183054 (from the colour viewer). The HSL
        // percentages are rounded, so allow a byte of slack.
        let c = Colour::hsl(216.0, 0.56, 0.21).to_srgb_u8();
        let expected = [24u8, 48, 84, 255];
        for (got, want) in c.iter().zip(expected) {
            assert!(
                (*got as i32 - want as i32).abs() <= 1,
                "{c:?} vs {expected:?}"
            );
        }
    }
}