repose-core 0.31.10

Repose's core runtime, view model, signals, composition locals, and animation clock.
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
use crate::Vec2;

/// Y′CbCr or RGB signal range.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ColorRange {
    /// Studio swing: Y 16–235, Cb/Cr 16–240 (the standard for broadcast video).
    #[default]
    Limited,
    /// Full swing: 0–255 for all channels (JPEG, computer graphics).
    Full,
}

/// Matrix coefficients for luma/chroma-to-RGB conversion (H.273 Table 4).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum MatrixCoeffs {
    /// Identity / GBR -> the "matrix" is the identity, meaning the
    /// signal *is* RGB (or GBR order with different primaries).
    Identity,
    /// BT.601 525-line (Kr=0.299, Kb=0.114).
    Bt601,
    /// BT.709 (Kr=0.2126, Kb=0.0722).
    #[default]
    Bt709,
    /// BT.2020 non-constant luminance (Kr=0.2627, Kb=0.0593).
    Bt2020Ncl,
}

/// Color primaries (H.273 Table 2 / CICP ColourPrimaries).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Primaries {
    /// BT.709 / sRGB.
    #[default]
    Bt709,
    /// BT.601 625-line (EBU Tech 3213).
    Bt601_625,
    /// BT.601 525-line (SMPTE C).
    Bt601_525,
    /// BT.2020.
    Bt2020,
    /// DCI-P3 (SMPTE ST 428-1 / Display P3).
    DciP3,
}

/// Transfer characteristics (H.273 Table 3 / CICP TransferCharacteristics).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Transfer {
    /// BT.709 / BT.601 (gamma ≈ 2.2, same curve as BT.1886).
    Bt709,
    /// sRGB (IEC 61966-2-1) -> piecewise 2.4 gamma with linear toe.
    #[default]
    Srgb,
    /// SMPTE ST 2084 (Perceptual Quantizer) for HDR10.
    Pq,
    /// ITU-R BT.2100 Hybrid Log-Gamma for HDR broadcast.
    Hlg,
    /// Linear light (no gamma).
    Linear,
}

/// Chroma sample siting (horizontal and vertical alignment).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ChromaSiting {
    /// "Left" / MPEG-2 / H.264 / AV1 default: chroma samples aligned
    /// with the left edge of luma samples.
    #[default]
    Left,
    /// "Center" / MPEG-4: chroma samples aligned with luma sample centers.
    Center,
    /// Top-left: chroma aligned with top-left corner (rare, some JPEG).
    TopLeft,
}

/// Describes the memory layout of a planar (or packed) video frame.
///
/// Maps 1:1 to common video pixel formats. Each variant implies the
/// number of planes, their texture formats, and subsampling factors.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PixelFormat {
    /// 8-bit YUV 4:2:0, 2 planes: Y (R8, full res), interleaved UV (Rg8, half res).
    #[default]
    Nv12,
    /// 8-bit YUV 4:2:0, 3 planes: Y (R8), U (R8), V (R8), all half res.
    I420,
    /// 8-bit YUV 4:4:4, 3 planes: Y (R8), U (R8), V (R8), full res.
    I444,
    /// 10-bit YUV 4:2:0, 2 planes: Y (R16Unorm, high bits), UV (Rg16Unorm, high bits), half res.
    P010,
    /// Packed 8-bit RGBA (single Rgba8Unorm plane, full res).
    Rgba,
}

impl PixelFormat {
    pub fn num_planes(&self) -> u32 {
        match self {
            PixelFormat::Nv12 | PixelFormat::P010 => 2,
            PixelFormat::I420 | PixelFormat::I444 => 3,
            PixelFormat::Rgba => 1,
        }
    }

    /// Chroma width/height for a given luma resolution.
    /// Returns `(0, 0)` for RGB-like formats.
    pub fn chroma_size(&self, luma_w: u32, luma_h: u32) -> (u32, u32) {
        match self {
            PixelFormat::Nv12 | PixelFormat::I420 | PixelFormat::P010 => {
                (luma_w.div_ceil(2), luma_h.div_ceil(2))
            }
            PixelFormat::I444 => (luma_w, luma_h),
            PixelFormat::Rgba => (0, 0),
        }
    }
}

/// Minimum viable color metadata for a video frame or stream.
///
/// Maps 1:1 to the values carried in H.264 VUI
/// (`matrix_coefficients`, `transfer_characteristics`, `colour_primaries`,
/// `video_full_range_flag`) and the AV1 sequence header `color_config`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ColorInfo {
    pub range: ColorRange,
    pub matrix: MatrixCoeffs,
    pub primaries: Primaries,
    pub transfer: Transfer,
    pub chroma_siting: ChromaSiting,
}

impl Default for ColorInfo {
    fn default() -> Self {
        Self {
            range: ColorRange::Limited,
            matrix: MatrixCoeffs::Bt709,
            primaries: Primaries::Bt709,
            transfer: Transfer::Bt709,
            chroma_siting: ChromaSiting::Left,
        }
    }
}

/// Pre-computed affine transform from Y′CbCr (raw texel values 0..1) to
/// gamma-encoded R′G′B′ (0..1).
///
/// Folded in:
/// - Range expansion (16/219, 128/224 offsets for limited range)
/// - Matrix coefficients (601 / 709 / 2020 / Identity)
///
/// The shader applies: `rgb = M * yuv + b`, then clamps and applies the
/// sRGB EOTF before writing to the srgb render target.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct YuvTransform {
    /// 3×3 matrix applied to (Y, U, V).
    pub m: [[f32; 3]; 3],
    /// 3-element bias (added after the matrix multiply).
    pub b: [f32; 3],
}

impl ColorInfo {
    /// Compute the single affine transform that the fragment shader applies.
    ///
    /// The shader samples raw texel values `y`, `u`, `v` ∈ [0..1] and does:
    /// ```ignore
    /// let rgb = clamp(transform.m * vec3(y, u, v) + transform.b, 0, 1);
    /// ```
    pub fn to_yuv_transform(&self) -> YuvTransform {
        let (y_scale, y_off, uv_scale, uv_off) = match self.range {
            ColorRange::Limited => (255.0 / 219.0, 16.0 / 255.0, 255.0 / 224.0, 128.0 / 255.0),
            ColorRange::Full => (1.0, 0.0, 1.0, 0.5),
        };

        if self.matrix == MatrixCoeffs::Identity {
            return YuvTransform {
                m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
                b: [0.0; 3],
            };
        }

        let (kr, kb) = match self.matrix {
            MatrixCoeffs::Bt601 => (0.299_f32, 0.114_f32),
            MatrixCoeffs::Bt709 => (0.2126_f32, 0.0722_f32),
            MatrixCoeffs::Bt2020Ncl => (0.2627_f32, 0.0593_f32),
            _ => unreachable!(), // Identity already handled above.
        };
        let kg = 1.0 - kr - kb;

        // G′ coefficient for Cb and Cr
        let cb_factor = 2.0 * kb * (1.0 - kb) / kg;
        let cr_factor = 2.0 * kr * (1.0 - kr) / kg;

        // Combined matrix: [M] * [range_expansion]
        let m00 = y_scale;
        let m01 = 0.0;
        let m02 = 2.0 * (1.0 - kr) * uv_scale;

        let m10 = y_scale;
        let m11 = -cb_factor * uv_scale;
        let m12 = -cr_factor * uv_scale;

        let m20 = y_scale;
        let m21 = 2.0 * (1.0 - kb) * uv_scale;
        let m22 = 0.0;

        // Combined bias: [M] * [-range_offset]
        let b0 = -y_scale * y_off - 2.0 * (1.0 - kr) * uv_scale * uv_off;
        let b1 = -y_scale * y_off + cb_factor * uv_scale * uv_off + cr_factor * uv_scale * uv_off;
        let b2 = -y_scale * y_off - 2.0 * (1.0 - kb) * uv_scale * uv_off;

        YuvTransform {
            m: [[m00, m01, m02], [m10, m11, m12], [m20, m21, m22]],
            b: [b0, b1, b2],
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Color(pub u8, pub u8, pub u8, pub u8);

impl Color {
    pub const TRANSPARENT: Color = Color(0, 0, 0, 0);
    pub const BLACK: Color = Color(0, 0, 0, 255);
    pub const WHITE: Color = Color(255, 255, 255, 255);

    pub fn from_rgb(r: u8, g: u8, b: u8) -> Self {
        Color(r, g, b, 255)
    }
    pub fn from_rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
        Color(r, g, b, a)
    }
    pub fn from_hex(hex: &str) -> Self {
        let s = hex.trim_start_matches('#');
        let (r, g, b, a) = match s.len() {
            6 => (
                u8::from_str_radix(&s[0..2], 16).unwrap_or(0),
                u8::from_str_radix(&s[2..4], 16).unwrap_or(0),
                u8::from_str_radix(&s[4..6], 16).unwrap_or(0),
                255,
            ),
            8 => (
                u8::from_str_radix(&s[0..2], 16).unwrap_or(0),
                u8::from_str_radix(&s[2..4], 16).unwrap_or(0),
                u8::from_str_radix(&s[4..6], 16).unwrap_or(0),
                u8::from_str_radix(&s[6..8], 16).unwrap_or(255),
            ),
            _ => (0, 0, 0, 255),
        };
        Color(r, g, b, a)
    }
    pub fn with_alpha(self, a: u8) -> Self {
        Color(self.0, self.1, self.2, a)
    }

    pub fn with_alpha_f32(self, a: f32) -> Self {
        Color(
            self.0,
            self.1,
            self.2,
            (a * 255.0).round().clamp(0.0, 255.0) as u8,
        )
    }

    /// Composite `self` (as a foreground with alpha) over a `background` color.
    /// Result has same alpha as background (treats background as opaque).
    pub fn composite_over(&self, background: Color) -> Color {
        let a = self.3 as f32 / 255.0;
        let inv_a = 1.0 - a;
        Color(
            (self.0 as f32 * a + background.0 as f32 * inv_a)
                .round()
                .clamp(0.0, 255.0) as u8,
            (self.1 as f32 * a + background.1 as f32 * inv_a)
                .round()
                .clamp(0.0, 255.0) as u8,
            (self.2 as f32 * a + background.2 as f32 * inv_a)
                .round()
                .clamp(0.0, 255.0) as u8,
            background.3,
        )
    }

    pub fn to_linear(self) -> [f32; 4] {
        fn srgb_to_linear(c: f32) -> f32 {
            if c <= 0.04045 {
                c / 12.92
            } else {
                ((c + 0.055) / 1.055).powf(2.4)
            }
        }
        let r = srgb_to_linear(self.0 as f32 / 255.0);
        let g = srgb_to_linear(self.1 as f32 / 255.0);
        let b = srgb_to_linear(self.2 as f32 / 255.0);
        let a = self.3 as f32 / 255.0;
        [r, g, b, a]
    }

    /// Relative luminance in linear sRGB (Rec. 709 weights).
    pub fn relative_luminance(self) -> f32 {
        let lin = self.to_linear();
        0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2]
    }

    /// Whether this color reads as dark (useful for syncing OS window chrome).
    pub fn is_dark(self) -> bool {
        self.relative_luminance() < 0.5
    }
}

/// Brush for filling shapes.
///
/// This can be a solid color or a gradient. Higher‑level APIs (Modifier,
/// widgets) should talk in terms of `Brush` rather than raw `Color` so that
/// gradients and future brush types (radial, image) can share the same path.
/// Mirrors Compose's `Brush` sealed class.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum Brush {
    /// Solid color fill
    Solid(Color),

    /// Linear gradient between two points in local coordinates.
    ///
    /// The gradient is defined in the local space of the node being drawn:
    /// `(0,0)` is the shape's top-left and endpoints are px offsets from
    /// there (e.g. a rect's bottom-right is `(w,h)`). `LinearGradient::vertical`
    /// spans exactly the shape height.
    Linear {
        start: Vec2,
        end: Vec2,
        start_color: Color,
        end_color: Color,
    },

    /// Linear gradient with endpoints normalized to the shape bounds.
    LinearNormalized {
        start: Vec2,
        end: Vec2,
        start_color: Color,
        end_color: Color,
    },

    /// Radial gradient centered at `center` with the given `radius`.
    ///
    /// Like [`Brush::Linear`], coordinates are shape-local px from the
    /// shape's top-left. Pixels beyond `radius` clamp to `end_color`, matching
    /// Compose's [`TileMode::Clamp`](crate::TileMode) default.
    Radial {
        center: Vec2,
        radius: f32,
        start_color: Color,
        end_color: Color,
    },

    /// Angular sweep gradient rotating clockwise around `center` from 3 o'clock.
    /// `center` is shape-local px from the shape's top-left.
    Sweep {
        center: Vec2,
        start_color: Color,
        end_color: Color,
    },
}

/// Out-of-bounds behavior for gradient brushes, mirroring Compose `TileMode`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TileMode {
    /// Repeat the edge color (Compose default).
    #[default]
    Clamp,
    /// Tile the gradient (`x - floor(x)`).
    Repeated,
    /// Mirror the gradient every other tile.
    Mirror,
}

impl From<Color> for Brush {
    fn from(c: Color) -> Self {
        Brush::Solid(c)
    }
}

pub struct LinearGradient {
    pub start: Vec2,
    pub end: Vec2,
    pub start_color: Color,
    pub end_color: Color,
}

impl LinearGradient {
    /// Vertical gradient spanning the shape's full height.
    pub fn vertical(top: Color, bottom: Color) -> Brush {
        Brush::LinearNormalized {
            start: Vec2 { x: 0.0, y: 0.0 },
            end: Vec2 { x: 0.0, y: 1.0 },
            start_color: top,
            end_color: bottom,
        }
    }

    /// Horizontal gradient spanning the shape's full width. Same
    /// shape-local caveat as [`vertical`](Self::vertical).
    pub fn horizontal(left: Color, right: Color) -> Brush {
        Brush::LinearNormalized {
            start: Vec2 { x: 0.0, y: 0.0 },
            end: Vec2 { x: 1.0, y: 0.0 },
            start_color: left,
            end_color: right,
        }
    }
}